ASTContext.cpp revision 200fa53fd420aa8369586f569dbece04930ad6a3
1//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/CharUnits.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExternalASTSource.h"
23#include "clang/AST/ASTMutationListener.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/Mangle.h"
26#include "clang/Basic/Builtins.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/TargetInfo.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/Support/MathExtras.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Support/Capacity.h"
34#include "CXXABI.h"
35#include <map>
36
37using namespace clang;
38
39unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
41unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
43unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
45unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
47unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
49unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
52enum FloatingRank {
53  HalfRank, FloatRank, DoubleRank, LongDoubleRank
54};
55
56void
57ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
58                                               TemplateTemplateParmDecl *Parm) {
59  ID.AddInteger(Parm->getDepth());
60  ID.AddInteger(Parm->getPosition());
61  ID.AddBoolean(Parm->isParameterPack());
62
63  TemplateParameterList *Params = Parm->getTemplateParameters();
64  ID.AddInteger(Params->size());
65  for (TemplateParameterList::const_iterator P = Params->begin(),
66                                          PEnd = Params->end();
67       P != PEnd; ++P) {
68    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
69      ID.AddInteger(0);
70      ID.AddBoolean(TTP->isParameterPack());
71      continue;
72    }
73
74    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
75      ID.AddInteger(1);
76      ID.AddBoolean(NTTP->isParameterPack());
77      ID.AddPointer(NTTP->getType().getAsOpaquePtr());
78      if (NTTP->isExpandedParameterPack()) {
79        ID.AddBoolean(true);
80        ID.AddInteger(NTTP->getNumExpansionTypes());
81        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I)
82          ID.AddPointer(NTTP->getExpansionType(I).getAsOpaquePtr());
83      } else
84        ID.AddBoolean(false);
85      continue;
86    }
87
88    TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
89    ID.AddInteger(2);
90    Profile(ID, TTP);
91  }
92}
93
94TemplateTemplateParmDecl *
95ASTContext::getCanonicalTemplateTemplateParmDecl(
96                                          TemplateTemplateParmDecl *TTP) const {
97  // Check if we already have a canonical template template parameter.
98  llvm::FoldingSetNodeID ID;
99  CanonicalTemplateTemplateParm::Profile(ID, TTP);
100  void *InsertPos = 0;
101  CanonicalTemplateTemplateParm *Canonical
102    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
103  if (Canonical)
104    return Canonical->getParam();
105
106  // Build a canonical template parameter list.
107  TemplateParameterList *Params = TTP->getTemplateParameters();
108  SmallVector<NamedDecl *, 4> CanonParams;
109  CanonParams.reserve(Params->size());
110  for (TemplateParameterList::const_iterator P = Params->begin(),
111                                          PEnd = Params->end();
112       P != PEnd; ++P) {
113    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
114      CanonParams.push_back(
115                  TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
116                                               SourceLocation(),
117                                               SourceLocation(),
118                                               TTP->getDepth(),
119                                               TTP->getIndex(), 0, false,
120                                               TTP->isParameterPack()));
121    else if (NonTypeTemplateParmDecl *NTTP
122             = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
123      QualType T = getCanonicalType(NTTP->getType());
124      TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
125      NonTypeTemplateParmDecl *Param;
126      if (NTTP->isExpandedParameterPack()) {
127        SmallVector<QualType, 2> ExpandedTypes;
128        SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
129        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
130          ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
131          ExpandedTInfos.push_back(
132                                getTrivialTypeSourceInfo(ExpandedTypes.back()));
133        }
134
135        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
136                                                SourceLocation(),
137                                                SourceLocation(),
138                                                NTTP->getDepth(),
139                                                NTTP->getPosition(), 0,
140                                                T,
141                                                TInfo,
142                                                ExpandedTypes.data(),
143                                                ExpandedTypes.size(),
144                                                ExpandedTInfos.data());
145      } else {
146        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
147                                                SourceLocation(),
148                                                SourceLocation(),
149                                                NTTP->getDepth(),
150                                                NTTP->getPosition(), 0,
151                                                T,
152                                                NTTP->isParameterPack(),
153                                                TInfo);
154      }
155      CanonParams.push_back(Param);
156
157    } else
158      CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
159                                           cast<TemplateTemplateParmDecl>(*P)));
160  }
161
162  TemplateTemplateParmDecl *CanonTTP
163    = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
164                                       SourceLocation(), TTP->getDepth(),
165                                       TTP->getPosition(),
166                                       TTP->isParameterPack(),
167                                       0,
168                         TemplateParameterList::Create(*this, SourceLocation(),
169                                                       SourceLocation(),
170                                                       CanonParams.data(),
171                                                       CanonParams.size(),
172                                                       SourceLocation()));
173
174  // Get the new insert position for the node we care about.
175  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
176  assert(Canonical == 0 && "Shouldn't be in the map!");
177  (void)Canonical;
178
179  // Create the canonical template template parameter entry.
180  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
181  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
182  return CanonTTP;
183}
184
185CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
186  if (!LangOpts.CPlusPlus) return 0;
187
188  switch (T.getCXXABI()) {
189  case CXXABI_ARM:
190    return CreateARMCXXABI(*this);
191  case CXXABI_Itanium:
192    return CreateItaniumCXXABI(*this);
193  case CXXABI_Microsoft:
194    return CreateMicrosoftCXXABI(*this);
195  }
196  llvm_unreachable("Invalid CXXABI type!");
197}
198
199static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
200                                             const LangOptions &LOpts) {
201  if (LOpts.FakeAddressSpaceMap) {
202    // The fake address space map must have a distinct entry for each
203    // language-specific address space.
204    static const unsigned FakeAddrSpaceMap[] = {
205      1, // opencl_global
206      2, // opencl_local
207      3  // opencl_constant
208    };
209    return &FakeAddrSpaceMap;
210  } else {
211    return &T.getAddressSpaceMap();
212  }
213}
214
215ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
216                       const TargetInfo *t,
217                       IdentifierTable &idents, SelectorTable &sels,
218                       Builtin::Context &builtins,
219                       unsigned size_reserve,
220                       bool DelayInitialization)
221  : FunctionProtoTypes(this_()),
222    TemplateSpecializationTypes(this_()),
223    DependentTemplateSpecializationTypes(this_()),
224    SubstTemplateTemplateParmPacks(this_()),
225    GlobalNestedNameSpecifier(0),
226    Int128Decl(0), UInt128Decl(0),
227    ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
228    CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
229    FILEDecl(0),
230    jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
231    BlockDescriptorType(0), BlockDescriptorExtendedType(0),
232    cudaConfigureCallDecl(0),
233    NullTypeSourceInfo(QualType()),
234    FirstLocalImport(), LastLocalImport(),
235    SourceMgr(SM), LangOpts(LOpts),
236    AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
237    Idents(idents), Selectors(sels),
238    BuiltinInfo(builtins),
239    DeclarationNames(*this),
240    ExternalSource(0), Listener(0),
241    LastSDM(0, 0),
242    UniqueBlockByRefTypeID(0)
243{
244  if (size_reserve > 0) Types.reserve(size_reserve);
245  TUDecl = TranslationUnitDecl::Create(*this);
246
247  if (!DelayInitialization) {
248    assert(t && "No target supplied for ASTContext initialization");
249    InitBuiltinTypes(*t);
250  }
251}
252
253ASTContext::~ASTContext() {
254  // Release the DenseMaps associated with DeclContext objects.
255  // FIXME: Is this the ideal solution?
256  ReleaseDeclContextMaps();
257
258  // Call all of the deallocation functions.
259  for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
260    Deallocations[I].first(Deallocations[I].second);
261
262  // Release all of the memory associated with overridden C++ methods.
263  for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
264         OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
265       OM != OMEnd; ++OM)
266    OM->second.Destroy();
267
268  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
269  // because they can contain DenseMaps.
270  for (llvm::DenseMap<const ObjCContainerDecl*,
271       const ASTRecordLayout*>::iterator
272       I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
273    // Increment in loop to prevent using deallocated memory.
274    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
275      R->Destroy(*this);
276
277  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
278       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
279    // Increment in loop to prevent using deallocated memory.
280    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
281      R->Destroy(*this);
282  }
283
284  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
285                                                    AEnd = DeclAttrs.end();
286       A != AEnd; ++A)
287    A->second->~AttrVec();
288}
289
290void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
291  Deallocations.push_back(std::make_pair(Callback, Data));
292}
293
294void
295ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
296  ExternalSource.reset(Source.take());
297}
298
299void ASTContext::PrintStats() const {
300  llvm::errs() << "\n*** AST Context Stats:\n";
301  llvm::errs() << "  " << Types.size() << " types total.\n";
302
303  unsigned counts[] = {
304#define TYPE(Name, Parent) 0,
305#define ABSTRACT_TYPE(Name, Parent)
306#include "clang/AST/TypeNodes.def"
307    0 // Extra
308  };
309
310  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
311    Type *T = Types[i];
312    counts[(unsigned)T->getTypeClass()]++;
313  }
314
315  unsigned Idx = 0;
316  unsigned TotalBytes = 0;
317#define TYPE(Name, Parent)                                              \
318  if (counts[Idx])                                                      \
319    llvm::errs() << "    " << counts[Idx] << " " << #Name               \
320                 << " types\n";                                         \
321  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
322  ++Idx;
323#define ABSTRACT_TYPE(Name, Parent)
324#include "clang/AST/TypeNodes.def"
325
326  llvm::errs() << "Total bytes = " << TotalBytes << "\n";
327
328  // Implicit special member functions.
329  llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
330               << NumImplicitDefaultConstructors
331               << " implicit default constructors created\n";
332  llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
333               << NumImplicitCopyConstructors
334               << " implicit copy constructors created\n";
335  if (getLangOptions().CPlusPlus)
336    llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
337                 << NumImplicitMoveConstructors
338                 << " implicit move constructors created\n";
339  llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
340               << NumImplicitCopyAssignmentOperators
341               << " implicit copy assignment operators created\n";
342  if (getLangOptions().CPlusPlus)
343    llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
344                 << NumImplicitMoveAssignmentOperators
345                 << " implicit move assignment operators created\n";
346  llvm::errs() << NumImplicitDestructorsDeclared << "/"
347               << NumImplicitDestructors
348               << " implicit destructors created\n";
349
350  if (ExternalSource.get()) {
351    llvm::errs() << "\n";
352    ExternalSource->PrintStats();
353  }
354
355  BumpAlloc.PrintStats();
356}
357
358TypedefDecl *ASTContext::getInt128Decl() const {
359  if (!Int128Decl) {
360    TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
361    Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
362                                     getTranslationUnitDecl(),
363                                     SourceLocation(),
364                                     SourceLocation(),
365                                     &Idents.get("__int128_t"),
366                                     TInfo);
367  }
368
369  return Int128Decl;
370}
371
372TypedefDecl *ASTContext::getUInt128Decl() const {
373  if (!UInt128Decl) {
374    TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
375    UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
376                                     getTranslationUnitDecl(),
377                                     SourceLocation(),
378                                     SourceLocation(),
379                                     &Idents.get("__uint128_t"),
380                                     TInfo);
381  }
382
383  return UInt128Decl;
384}
385
386void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
387  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
388  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
389  Types.push_back(Ty);
390}
391
392void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
393  assert((!this->Target || this->Target == &Target) &&
394         "Incorrect target reinitialization");
395  assert(VoidTy.isNull() && "Context reinitialized?");
396
397  this->Target = &Target;
398
399  ABI.reset(createCXXABI(Target));
400  AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
401
402  // C99 6.2.5p19.
403  InitBuiltinType(VoidTy,              BuiltinType::Void);
404
405  // C99 6.2.5p2.
406  InitBuiltinType(BoolTy,              BuiltinType::Bool);
407  // C99 6.2.5p3.
408  if (LangOpts.CharIsSigned)
409    InitBuiltinType(CharTy,            BuiltinType::Char_S);
410  else
411    InitBuiltinType(CharTy,            BuiltinType::Char_U);
412  // C99 6.2.5p4.
413  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
414  InitBuiltinType(ShortTy,             BuiltinType::Short);
415  InitBuiltinType(IntTy,               BuiltinType::Int);
416  InitBuiltinType(LongTy,              BuiltinType::Long);
417  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
418
419  // C99 6.2.5p6.
420  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
421  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
422  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
423  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
424  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
425
426  // C99 6.2.5p10.
427  InitBuiltinType(FloatTy,             BuiltinType::Float);
428  InitBuiltinType(DoubleTy,            BuiltinType::Double);
429  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
430
431  // GNU extension, 128-bit integers.
432  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
433  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
434
435  if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
436    if (TargetInfo::isTypeSigned(Target.getWCharType()))
437      InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
438    else  // -fshort-wchar makes wchar_t be unsigned.
439      InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
440  } else // C99
441    WCharTy = getFromTargetType(Target.getWCharType());
442
443  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
444    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
445  else // C99
446    Char16Ty = getFromTargetType(Target.getChar16Type());
447
448  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
449    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
450  else // C99
451    Char32Ty = getFromTargetType(Target.getChar32Type());
452
453  // Placeholder type for type-dependent expressions whose type is
454  // completely unknown. No code should ever check a type against
455  // DependentTy and users should never see it; however, it is here to
456  // help diagnose failures to properly check for type-dependent
457  // expressions.
458  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
459
460  // Placeholder type for functions.
461  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
462
463  // Placeholder type for bound members.
464  InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
465
466  // Placeholder type for pseudo-objects.
467  InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
468
469  // "any" type; useful for debugger-like clients.
470  InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
471
472  // Placeholder type for unbridged ARC casts.
473  InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
474
475  // C99 6.2.5p11.
476  FloatComplexTy      = getComplexType(FloatTy);
477  DoubleComplexTy     = getComplexType(DoubleTy);
478  LongDoubleComplexTy = getComplexType(LongDoubleTy);
479
480  BuiltinVaListType = QualType();
481
482  // Builtin types for 'id', 'Class', and 'SEL'.
483  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
484  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
485  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
486
487  ObjCConstantStringType = QualType();
488
489  // void * type
490  VoidPtrTy = getPointerType(VoidTy);
491
492  // nullptr type (C++0x 2.14.7)
493  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
494
495  // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
496  InitBuiltinType(HalfTy, BuiltinType::Half);
497}
498
499DiagnosticsEngine &ASTContext::getDiagnostics() const {
500  return SourceMgr.getDiagnostics();
501}
502
503AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
504  AttrVec *&Result = DeclAttrs[D];
505  if (!Result) {
506    void *Mem = Allocate(sizeof(AttrVec));
507    Result = new (Mem) AttrVec;
508  }
509
510  return *Result;
511}
512
513/// \brief Erase the attributes corresponding to the given declaration.
514void ASTContext::eraseDeclAttrs(const Decl *D) {
515  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
516  if (Pos != DeclAttrs.end()) {
517    Pos->second->~AttrVec();
518    DeclAttrs.erase(Pos);
519  }
520}
521
522MemberSpecializationInfo *
523ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
524  assert(Var->isStaticDataMember() && "Not a static data member");
525  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
526    = InstantiatedFromStaticDataMember.find(Var);
527  if (Pos == InstantiatedFromStaticDataMember.end())
528    return 0;
529
530  return Pos->second;
531}
532
533void
534ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
535                                                TemplateSpecializationKind TSK,
536                                          SourceLocation PointOfInstantiation) {
537  assert(Inst->isStaticDataMember() && "Not a static data member");
538  assert(Tmpl->isStaticDataMember() && "Not a static data member");
539  assert(!InstantiatedFromStaticDataMember[Inst] &&
540         "Already noted what static data member was instantiated from");
541  InstantiatedFromStaticDataMember[Inst]
542    = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
543}
544
545FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
546                                                     const FunctionDecl *FD){
547  assert(FD && "Specialization is 0");
548  llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
549    = ClassScopeSpecializationPattern.find(FD);
550  if (Pos == ClassScopeSpecializationPattern.end())
551    return 0;
552
553  return Pos->second;
554}
555
556void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
557                                        FunctionDecl *Pattern) {
558  assert(FD && "Specialization is 0");
559  assert(Pattern && "Class scope specialization pattern is 0");
560  ClassScopeSpecializationPattern[FD] = Pattern;
561}
562
563NamedDecl *
564ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
565  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
566    = InstantiatedFromUsingDecl.find(UUD);
567  if (Pos == InstantiatedFromUsingDecl.end())
568    return 0;
569
570  return Pos->second;
571}
572
573void
574ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
575  assert((isa<UsingDecl>(Pattern) ||
576          isa<UnresolvedUsingValueDecl>(Pattern) ||
577          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
578         "pattern decl is not a using decl");
579  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
580  InstantiatedFromUsingDecl[Inst] = Pattern;
581}
582
583UsingShadowDecl *
584ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
585  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
586    = InstantiatedFromUsingShadowDecl.find(Inst);
587  if (Pos == InstantiatedFromUsingShadowDecl.end())
588    return 0;
589
590  return Pos->second;
591}
592
593void
594ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
595                                               UsingShadowDecl *Pattern) {
596  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
597  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
598}
599
600FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
601  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
602    = InstantiatedFromUnnamedFieldDecl.find(Field);
603  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
604    return 0;
605
606  return Pos->second;
607}
608
609void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
610                                                     FieldDecl *Tmpl) {
611  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
612  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
613  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
614         "Already noted what unnamed field was instantiated from");
615
616  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
617}
618
619bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
620                                    const FieldDecl *LastFD) const {
621  return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
622          FD->getBitWidthValue(*this) == 0);
623}
624
625bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
626                                             const FieldDecl *LastFD) const {
627  return (FD->isBitField() && LastFD && LastFD->isBitField() &&
628          FD->getBitWidthValue(*this) == 0 &&
629          LastFD->getBitWidthValue(*this) != 0);
630}
631
632bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
633                                         const FieldDecl *LastFD) const {
634  return (FD->isBitField() && LastFD && LastFD->isBitField() &&
635          FD->getBitWidthValue(*this) &&
636          LastFD->getBitWidthValue(*this));
637}
638
639bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
640                                         const FieldDecl *LastFD) const {
641  return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
642          LastFD->getBitWidthValue(*this));
643}
644
645bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
646                                             const FieldDecl *LastFD) const {
647  return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
648          FD->getBitWidthValue(*this));
649}
650
651ASTContext::overridden_cxx_method_iterator
652ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
653  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
654    = OverriddenMethods.find(Method);
655  if (Pos == OverriddenMethods.end())
656    return 0;
657
658  return Pos->second.begin();
659}
660
661ASTContext::overridden_cxx_method_iterator
662ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
663  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
664    = OverriddenMethods.find(Method);
665  if (Pos == OverriddenMethods.end())
666    return 0;
667
668  return Pos->second.end();
669}
670
671unsigned
672ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
673  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
674    = OverriddenMethods.find(Method);
675  if (Pos == OverriddenMethods.end())
676    return 0;
677
678  return Pos->second.size();
679}
680
681void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
682                                     const CXXMethodDecl *Overridden) {
683  OverriddenMethods[Method].push_back(Overridden);
684}
685
686void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
687  assert(!Import->NextLocalImport && "Import declaration already in the chain");
688  assert(!Import->isFromASTFile() && "Non-local import declaration");
689  if (!FirstLocalImport) {
690    FirstLocalImport = Import;
691    LastLocalImport = Import;
692    return;
693  }
694
695  LastLocalImport->NextLocalImport = Import;
696  LastLocalImport = Import;
697}
698
699//===----------------------------------------------------------------------===//
700//                         Type Sizing and Analysis
701//===----------------------------------------------------------------------===//
702
703/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
704/// scalar floating point type.
705const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
706  const BuiltinType *BT = T->getAs<BuiltinType>();
707  assert(BT && "Not a floating point type!");
708  switch (BT->getKind()) {
709  default: llvm_unreachable("Not a floating point type!");
710  case BuiltinType::Half:       return Target->getHalfFormat();
711  case BuiltinType::Float:      return Target->getFloatFormat();
712  case BuiltinType::Double:     return Target->getDoubleFormat();
713  case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
714  }
715}
716
717/// getDeclAlign - Return a conservative estimate of the alignment of the
718/// specified decl.  Note that bitfields do not have a valid alignment, so
719/// this method will assert on them.
720/// If @p RefAsPointee, references are treated like their underlying type
721/// (for alignof), else they're treated like pointers (for CodeGen).
722CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
723  unsigned Align = Target->getCharWidth();
724
725  bool UseAlignAttrOnly = false;
726  if (unsigned AlignFromAttr = D->getMaxAlignment()) {
727    Align = AlignFromAttr;
728
729    // __attribute__((aligned)) can increase or decrease alignment
730    // *except* on a struct or struct member, where it only increases
731    // alignment unless 'packed' is also specified.
732    //
733    // It is an error for alignas to decrease alignment, so we can
734    // ignore that possibility;  Sema should diagnose it.
735    if (isa<FieldDecl>(D)) {
736      UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
737        cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
738    } else {
739      UseAlignAttrOnly = true;
740    }
741  }
742  else if (isa<FieldDecl>(D))
743      UseAlignAttrOnly =
744        D->hasAttr<PackedAttr>() ||
745        cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
746
747  // If we're using the align attribute only, just ignore everything
748  // else about the declaration and its type.
749  if (UseAlignAttrOnly) {
750    // do nothing
751
752  } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
753    QualType T = VD->getType();
754    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
755      if (RefAsPointee)
756        T = RT->getPointeeType();
757      else
758        T = getPointerType(RT->getPointeeType());
759    }
760    if (!T->isIncompleteType() && !T->isFunctionType()) {
761      // Adjust alignments of declarations with array type by the
762      // large-array alignment on the target.
763      unsigned MinWidth = Target->getLargeArrayMinWidth();
764      const ArrayType *arrayType;
765      if (MinWidth && (arrayType = getAsArrayType(T))) {
766        if (isa<VariableArrayType>(arrayType))
767          Align = std::max(Align, Target->getLargeArrayAlign());
768        else if (isa<ConstantArrayType>(arrayType) &&
769                 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
770          Align = std::max(Align, Target->getLargeArrayAlign());
771
772        // Walk through any array types while we're at it.
773        T = getBaseElementType(arrayType);
774      }
775      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
776    }
777
778    // Fields can be subject to extra alignment constraints, like if
779    // the field is packed, the struct is packed, or the struct has a
780    // a max-field-alignment constraint (#pragma pack).  So calculate
781    // the actual alignment of the field within the struct, and then
782    // (as we're expected to) constrain that by the alignment of the type.
783    if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
784      // So calculate the alignment of the field.
785      const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
786
787      // Start with the record's overall alignment.
788      unsigned fieldAlign = toBits(layout.getAlignment());
789
790      // Use the GCD of that and the offset within the record.
791      uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
792      if (offset > 0) {
793        // Alignment is always a power of 2, so the GCD will be a power of 2,
794        // which means we get to do this crazy thing instead of Euclid's.
795        uint64_t lowBitOfOffset = offset & (~offset + 1);
796        if (lowBitOfOffset < fieldAlign)
797          fieldAlign = static_cast<unsigned>(lowBitOfOffset);
798      }
799
800      Align = std::min(Align, fieldAlign);
801    }
802  }
803
804  return toCharUnitsFromBits(Align);
805}
806
807std::pair<CharUnits, CharUnits>
808ASTContext::getTypeInfoInChars(const Type *T) const {
809  std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
810  return std::make_pair(toCharUnitsFromBits(Info.first),
811                        toCharUnitsFromBits(Info.second));
812}
813
814std::pair<CharUnits, CharUnits>
815ASTContext::getTypeInfoInChars(QualType T) const {
816  return getTypeInfoInChars(T.getTypePtr());
817}
818
819/// getTypeSize - Return the size of the specified type, in bits.  This method
820/// does not work on incomplete types.
821///
822/// FIXME: Pointers into different addr spaces could have different sizes and
823/// alignment requirements: getPointerInfo should take an AddrSpace, this
824/// should take a QualType, &c.
825std::pair<uint64_t, unsigned>
826ASTContext::getTypeInfo(const Type *T) const {
827  uint64_t Width=0;
828  unsigned Align=8;
829  switch (T->getTypeClass()) {
830#define TYPE(Class, Base)
831#define ABSTRACT_TYPE(Class, Base)
832#define NON_CANONICAL_TYPE(Class, Base)
833#define DEPENDENT_TYPE(Class, Base) case Type::Class:
834#include "clang/AST/TypeNodes.def"
835    llvm_unreachable("Should not see dependent types");
836
837  case Type::FunctionNoProto:
838  case Type::FunctionProto:
839    // GCC extension: alignof(function) = 32 bits
840    Width = 0;
841    Align = 32;
842    break;
843
844  case Type::IncompleteArray:
845  case Type::VariableArray:
846    Width = 0;
847    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
848    break;
849
850  case Type::ConstantArray: {
851    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
852
853    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
854    uint64_t Size = CAT->getSize().getZExtValue();
855    assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && "Overflow in array type bit size evaluation");
856    Width = EltInfo.first*Size;
857    Align = EltInfo.second;
858    Width = llvm::RoundUpToAlignment(Width, Align);
859    break;
860  }
861  case Type::ExtVector:
862  case Type::Vector: {
863    const VectorType *VT = cast<VectorType>(T);
864    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
865    Width = EltInfo.first*VT->getNumElements();
866    Align = Width;
867    // If the alignment is not a power of 2, round up to the next power of 2.
868    // This happens for non-power-of-2 length vectors.
869    if (Align & (Align-1)) {
870      Align = llvm::NextPowerOf2(Align);
871      Width = llvm::RoundUpToAlignment(Width, Align);
872    }
873    break;
874  }
875
876  case Type::Builtin:
877    switch (cast<BuiltinType>(T)->getKind()) {
878    default: llvm_unreachable("Unknown builtin type!");
879    case BuiltinType::Void:
880      // GCC extension: alignof(void) = 8 bits.
881      Width = 0;
882      Align = 8;
883      break;
884
885    case BuiltinType::Bool:
886      Width = Target->getBoolWidth();
887      Align = Target->getBoolAlign();
888      break;
889    case BuiltinType::Char_S:
890    case BuiltinType::Char_U:
891    case BuiltinType::UChar:
892    case BuiltinType::SChar:
893      Width = Target->getCharWidth();
894      Align = Target->getCharAlign();
895      break;
896    case BuiltinType::WChar_S:
897    case BuiltinType::WChar_U:
898      Width = Target->getWCharWidth();
899      Align = Target->getWCharAlign();
900      break;
901    case BuiltinType::Char16:
902      Width = Target->getChar16Width();
903      Align = Target->getChar16Align();
904      break;
905    case BuiltinType::Char32:
906      Width = Target->getChar32Width();
907      Align = Target->getChar32Align();
908      break;
909    case BuiltinType::UShort:
910    case BuiltinType::Short:
911      Width = Target->getShortWidth();
912      Align = Target->getShortAlign();
913      break;
914    case BuiltinType::UInt:
915    case BuiltinType::Int:
916      Width = Target->getIntWidth();
917      Align = Target->getIntAlign();
918      break;
919    case BuiltinType::ULong:
920    case BuiltinType::Long:
921      Width = Target->getLongWidth();
922      Align = Target->getLongAlign();
923      break;
924    case BuiltinType::ULongLong:
925    case BuiltinType::LongLong:
926      Width = Target->getLongLongWidth();
927      Align = Target->getLongLongAlign();
928      break;
929    case BuiltinType::Int128:
930    case BuiltinType::UInt128:
931      Width = 128;
932      Align = 128; // int128_t is 128-bit aligned on all targets.
933      break;
934    case BuiltinType::Half:
935      Width = Target->getHalfWidth();
936      Align = Target->getHalfAlign();
937      break;
938    case BuiltinType::Float:
939      Width = Target->getFloatWidth();
940      Align = Target->getFloatAlign();
941      break;
942    case BuiltinType::Double:
943      Width = Target->getDoubleWidth();
944      Align = Target->getDoubleAlign();
945      break;
946    case BuiltinType::LongDouble:
947      Width = Target->getLongDoubleWidth();
948      Align = Target->getLongDoubleAlign();
949      break;
950    case BuiltinType::NullPtr:
951      Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
952      Align = Target->getPointerAlign(0); //   == sizeof(void*)
953      break;
954    case BuiltinType::ObjCId:
955    case BuiltinType::ObjCClass:
956    case BuiltinType::ObjCSel:
957      Width = Target->getPointerWidth(0);
958      Align = Target->getPointerAlign(0);
959      break;
960    }
961    break;
962  case Type::ObjCObjectPointer:
963    Width = Target->getPointerWidth(0);
964    Align = Target->getPointerAlign(0);
965    break;
966  case Type::BlockPointer: {
967    unsigned AS = getTargetAddressSpace(
968        cast<BlockPointerType>(T)->getPointeeType());
969    Width = Target->getPointerWidth(AS);
970    Align = Target->getPointerAlign(AS);
971    break;
972  }
973  case Type::LValueReference:
974  case Type::RValueReference: {
975    // alignof and sizeof should never enter this code path here, so we go
976    // the pointer route.
977    unsigned AS = getTargetAddressSpace(
978        cast<ReferenceType>(T)->getPointeeType());
979    Width = Target->getPointerWidth(AS);
980    Align = Target->getPointerAlign(AS);
981    break;
982  }
983  case Type::Pointer: {
984    unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
985    Width = Target->getPointerWidth(AS);
986    Align = Target->getPointerAlign(AS);
987    break;
988  }
989  case Type::MemberPointer: {
990    const MemberPointerType *MPT = cast<MemberPointerType>(T);
991    std::pair<uint64_t, unsigned> PtrDiffInfo =
992      getTypeInfo(getPointerDiffType());
993    Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
994    Align = PtrDiffInfo.second;
995    break;
996  }
997  case Type::Complex: {
998    // Complex types have the same alignment as their elements, but twice the
999    // size.
1000    std::pair<uint64_t, unsigned> EltInfo =
1001      getTypeInfo(cast<ComplexType>(T)->getElementType());
1002    Width = EltInfo.first*2;
1003    Align = EltInfo.second;
1004    break;
1005  }
1006  case Type::ObjCObject:
1007    return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1008  case Type::ObjCInterface: {
1009    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1010    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1011    Width = toBits(Layout.getSize());
1012    Align = toBits(Layout.getAlignment());
1013    break;
1014  }
1015  case Type::Record:
1016  case Type::Enum: {
1017    const TagType *TT = cast<TagType>(T);
1018
1019    if (TT->getDecl()->isInvalidDecl()) {
1020      Width = 8;
1021      Align = 8;
1022      break;
1023    }
1024
1025    if (const EnumType *ET = dyn_cast<EnumType>(TT))
1026      return getTypeInfo(ET->getDecl()->getIntegerType());
1027
1028    const RecordType *RT = cast<RecordType>(TT);
1029    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1030    Width = toBits(Layout.getSize());
1031    Align = toBits(Layout.getAlignment());
1032    break;
1033  }
1034
1035  case Type::SubstTemplateTypeParm:
1036    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1037                       getReplacementType().getTypePtr());
1038
1039  case Type::Auto: {
1040    const AutoType *A = cast<AutoType>(T);
1041    assert(A->isDeduced() && "Cannot request the size of a dependent type");
1042    return getTypeInfo(A->getDeducedType().getTypePtr());
1043  }
1044
1045  case Type::Paren:
1046    return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1047
1048  case Type::Typedef: {
1049    const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1050    std::pair<uint64_t, unsigned> Info
1051      = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1052    // If the typedef has an aligned attribute on it, it overrides any computed
1053    // alignment we have.  This violates the GCC documentation (which says that
1054    // attribute(aligned) can only round up) but matches its implementation.
1055    if (unsigned AttrAlign = Typedef->getMaxAlignment())
1056      Align = AttrAlign;
1057    else
1058      Align = Info.second;
1059    Width = Info.first;
1060    break;
1061  }
1062
1063  case Type::TypeOfExpr:
1064    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1065                         .getTypePtr());
1066
1067  case Type::TypeOf:
1068    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1069
1070  case Type::Decltype:
1071    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1072                        .getTypePtr());
1073
1074  case Type::UnaryTransform:
1075    return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1076
1077  case Type::Elaborated:
1078    return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1079
1080  case Type::Attributed:
1081    return getTypeInfo(
1082                  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1083
1084  case Type::TemplateSpecialization: {
1085    assert(getCanonicalType(T) != T &&
1086           "Cannot request the size of a dependent type");
1087    const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1088    // A type alias template specialization may refer to a typedef with the
1089    // aligned attribute on it.
1090    if (TST->isTypeAlias())
1091      return getTypeInfo(TST->getAliasedType().getTypePtr());
1092    else
1093      return getTypeInfo(getCanonicalType(T));
1094  }
1095
1096  case Type::Atomic: {
1097    std::pair<uint64_t, unsigned> Info
1098      = getTypeInfo(cast<AtomicType>(T)->getValueType());
1099    Width = Info.first;
1100    Align = Info.second;
1101    if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1102        llvm::isPowerOf2_64(Width)) {
1103      // We can potentially perform lock-free atomic operations for this
1104      // type; promote the alignment appropriately.
1105      // FIXME: We could potentially promote the width here as well...
1106      // is that worthwhile?  (Non-struct atomic types generally have
1107      // power-of-two size anyway, but structs might not.  Requires a bit
1108      // of implementation work to make sure we zero out the extra bits.)
1109      Align = static_cast<unsigned>(Width);
1110    }
1111  }
1112
1113  }
1114
1115  assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1116  return std::make_pair(Width, Align);
1117}
1118
1119/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1120CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1121  return CharUnits::fromQuantity(BitSize / getCharWidth());
1122}
1123
1124/// toBits - Convert a size in characters to a size in characters.
1125int64_t ASTContext::toBits(CharUnits CharSize) const {
1126  return CharSize.getQuantity() * getCharWidth();
1127}
1128
1129/// getTypeSizeInChars - Return the size of the specified type, in characters.
1130/// This method does not work on incomplete types.
1131CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1132  return toCharUnitsFromBits(getTypeSize(T));
1133}
1134CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1135  return toCharUnitsFromBits(getTypeSize(T));
1136}
1137
1138/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1139/// characters. This method does not work on incomplete types.
1140CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1141  return toCharUnitsFromBits(getTypeAlign(T));
1142}
1143CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1144  return toCharUnitsFromBits(getTypeAlign(T));
1145}
1146
1147/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1148/// type for the current target in bits.  This can be different than the ABI
1149/// alignment in cases where it is beneficial for performance to overalign
1150/// a data type.
1151unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1152  unsigned ABIAlign = getTypeAlign(T);
1153
1154  // Double and long long should be naturally aligned if possible.
1155  if (const ComplexType* CT = T->getAs<ComplexType>())
1156    T = CT->getElementType().getTypePtr();
1157  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1158      T->isSpecificBuiltinType(BuiltinType::LongLong))
1159    return std::max(ABIAlign, (unsigned)getTypeSize(T));
1160
1161  return ABIAlign;
1162}
1163
1164/// DeepCollectObjCIvars -
1165/// This routine first collects all declared, but not synthesized, ivars in
1166/// super class and then collects all ivars, including those synthesized for
1167/// current class. This routine is used for implementation of current class
1168/// when all ivars, declared and synthesized are known.
1169///
1170void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1171                                      bool leafClass,
1172                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1173  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1174    DeepCollectObjCIvars(SuperClass, false, Ivars);
1175  if (!leafClass) {
1176    for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1177         E = OI->ivar_end(); I != E; ++I)
1178      Ivars.push_back(*I);
1179  } else {
1180    ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1181    for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1182         Iv= Iv->getNextIvar())
1183      Ivars.push_back(Iv);
1184  }
1185}
1186
1187/// CollectInheritedProtocols - Collect all protocols in current class and
1188/// those inherited by it.
1189void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1190                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1191  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1192    // We can use protocol_iterator here instead of
1193    // all_referenced_protocol_iterator since we are walking all categories.
1194    for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1195         PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1196      ObjCProtocolDecl *Proto = (*P);
1197      Protocols.insert(Proto->getCanonicalDecl());
1198      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1199           PE = Proto->protocol_end(); P != PE; ++P) {
1200        Protocols.insert((*P)->getCanonicalDecl());
1201        CollectInheritedProtocols(*P, Protocols);
1202      }
1203    }
1204
1205    // Categories of this Interface.
1206    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1207         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1208      CollectInheritedProtocols(CDeclChain, Protocols);
1209    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1210      while (SD) {
1211        CollectInheritedProtocols(SD, Protocols);
1212        SD = SD->getSuperClass();
1213      }
1214  } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1215    for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1216         PE = OC->protocol_end(); P != PE; ++P) {
1217      ObjCProtocolDecl *Proto = (*P);
1218      Protocols.insert(Proto->getCanonicalDecl());
1219      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1220           PE = Proto->protocol_end(); P != PE; ++P)
1221        CollectInheritedProtocols(*P, Protocols);
1222    }
1223  } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1224    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1225         PE = OP->protocol_end(); P != PE; ++P) {
1226      ObjCProtocolDecl *Proto = (*P);
1227      Protocols.insert(Proto->getCanonicalDecl());
1228      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1229           PE = Proto->protocol_end(); P != PE; ++P)
1230        CollectInheritedProtocols(*P, Protocols);
1231    }
1232  }
1233}
1234
1235unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1236  unsigned count = 0;
1237  // Count ivars declared in class extension.
1238  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1239       CDecl = CDecl->getNextClassExtension())
1240    count += CDecl->ivar_size();
1241
1242  // Count ivar defined in this class's implementation.  This
1243  // includes synthesized ivars.
1244  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1245    count += ImplDecl->ivar_size();
1246
1247  return count;
1248}
1249
1250bool ASTContext::isSentinelNullExpr(const Expr *E) {
1251  if (!E)
1252    return false;
1253
1254  // nullptr_t is always treated as null.
1255  if (E->getType()->isNullPtrType()) return true;
1256
1257  if (E->getType()->isAnyPointerType() &&
1258      E->IgnoreParenCasts()->isNullPointerConstant(*this,
1259                                                Expr::NPC_ValueDependentIsNull))
1260    return true;
1261
1262  // Unfortunately, __null has type 'int'.
1263  if (isa<GNUNullExpr>(E)) return true;
1264
1265  return false;
1266}
1267
1268/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1269ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1270  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1271    I = ObjCImpls.find(D);
1272  if (I != ObjCImpls.end())
1273    return cast<ObjCImplementationDecl>(I->second);
1274  return 0;
1275}
1276/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1277ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1278  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1279    I = ObjCImpls.find(D);
1280  if (I != ObjCImpls.end())
1281    return cast<ObjCCategoryImplDecl>(I->second);
1282  return 0;
1283}
1284
1285/// \brief Set the implementation of ObjCInterfaceDecl.
1286void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1287                           ObjCImplementationDecl *ImplD) {
1288  assert(IFaceD && ImplD && "Passed null params");
1289  ObjCImpls[IFaceD] = ImplD;
1290}
1291/// \brief Set the implementation of ObjCCategoryDecl.
1292void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1293                           ObjCCategoryImplDecl *ImplD) {
1294  assert(CatD && ImplD && "Passed null params");
1295  ObjCImpls[CatD] = ImplD;
1296}
1297
1298ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1299  if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1300    return ID;
1301  if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1302    return CD->getClassInterface();
1303  if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1304    return IMD->getClassInterface();
1305
1306  return 0;
1307}
1308
1309/// \brief Get the copy initialization expression of VarDecl,or NULL if
1310/// none exists.
1311Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1312  assert(VD && "Passed null params");
1313  assert(VD->hasAttr<BlocksAttr>() &&
1314         "getBlockVarCopyInits - not __block var");
1315  llvm::DenseMap<const VarDecl*, Expr*>::iterator
1316    I = BlockVarCopyInits.find(VD);
1317  return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1318}
1319
1320/// \brief Set the copy inialization expression of a block var decl.
1321void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1322  assert(VD && Init && "Passed null params");
1323  assert(VD->hasAttr<BlocksAttr>() &&
1324         "setBlockVarCopyInits - not __block var");
1325  BlockVarCopyInits[VD] = Init;
1326}
1327
1328/// \brief Allocate an uninitialized TypeSourceInfo.
1329///
1330/// The caller should initialize the memory held by TypeSourceInfo using
1331/// the TypeLoc wrappers.
1332///
1333/// \param T the type that will be the basis for type source info. This type
1334/// should refer to how the declarator was written in source code, not to
1335/// what type semantic analysis resolved the declarator to.
1336TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1337                                                 unsigned DataSize) const {
1338  if (!DataSize)
1339    DataSize = TypeLoc::getFullDataSizeForType(T);
1340  else
1341    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1342           "incorrect data size provided to CreateTypeSourceInfo!");
1343
1344  TypeSourceInfo *TInfo =
1345    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1346  new (TInfo) TypeSourceInfo(T);
1347  return TInfo;
1348}
1349
1350TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1351                                                     SourceLocation L) const {
1352  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1353  DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1354  return DI;
1355}
1356
1357const ASTRecordLayout &
1358ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1359  return getObjCLayout(D, 0);
1360}
1361
1362const ASTRecordLayout &
1363ASTContext::getASTObjCImplementationLayout(
1364                                        const ObjCImplementationDecl *D) const {
1365  return getObjCLayout(D->getClassInterface(), D);
1366}
1367
1368//===----------------------------------------------------------------------===//
1369//                   Type creation/memoization methods
1370//===----------------------------------------------------------------------===//
1371
1372QualType
1373ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1374  unsigned fastQuals = quals.getFastQualifiers();
1375  quals.removeFastQualifiers();
1376
1377  // Check if we've already instantiated this type.
1378  llvm::FoldingSetNodeID ID;
1379  ExtQuals::Profile(ID, baseType, quals);
1380  void *insertPos = 0;
1381  if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1382    assert(eq->getQualifiers() == quals);
1383    return QualType(eq, fastQuals);
1384  }
1385
1386  // If the base type is not canonical, make the appropriate canonical type.
1387  QualType canon;
1388  if (!baseType->isCanonicalUnqualified()) {
1389    SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1390    canonSplit.Quals.addConsistentQualifiers(quals);
1391    canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
1392
1393    // Re-find the insert position.
1394    (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1395  }
1396
1397  ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1398  ExtQualNodes.InsertNode(eq, insertPos);
1399  return QualType(eq, fastQuals);
1400}
1401
1402QualType
1403ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
1404  QualType CanT = getCanonicalType(T);
1405  if (CanT.getAddressSpace() == AddressSpace)
1406    return T;
1407
1408  // If we are composing extended qualifiers together, merge together
1409  // into one ExtQuals node.
1410  QualifierCollector Quals;
1411  const Type *TypeNode = Quals.strip(T);
1412
1413  // If this type already has an address space specified, it cannot get
1414  // another one.
1415  assert(!Quals.hasAddressSpace() &&
1416         "Type cannot be in multiple addr spaces!");
1417  Quals.addAddressSpace(AddressSpace);
1418
1419  return getExtQualType(TypeNode, Quals);
1420}
1421
1422QualType ASTContext::getObjCGCQualType(QualType T,
1423                                       Qualifiers::GC GCAttr) const {
1424  QualType CanT = getCanonicalType(T);
1425  if (CanT.getObjCGCAttr() == GCAttr)
1426    return T;
1427
1428  if (const PointerType *ptr = T->getAs<PointerType>()) {
1429    QualType Pointee = ptr->getPointeeType();
1430    if (Pointee->isAnyPointerType()) {
1431      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1432      return getPointerType(ResultType);
1433    }
1434  }
1435
1436  // If we are composing extended qualifiers together, merge together
1437  // into one ExtQuals node.
1438  QualifierCollector Quals;
1439  const Type *TypeNode = Quals.strip(T);
1440
1441  // If this type already has an ObjCGC specified, it cannot get
1442  // another one.
1443  assert(!Quals.hasObjCGCAttr() &&
1444         "Type cannot have multiple ObjCGCs!");
1445  Quals.addObjCGCAttr(GCAttr);
1446
1447  return getExtQualType(TypeNode, Quals);
1448}
1449
1450const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1451                                                   FunctionType::ExtInfo Info) {
1452  if (T->getExtInfo() == Info)
1453    return T;
1454
1455  QualType Result;
1456  if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1457    Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1458  } else {
1459    const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1460    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1461    EPI.ExtInfo = Info;
1462    Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1463                             FPT->getNumArgs(), EPI);
1464  }
1465
1466  return cast<FunctionType>(Result.getTypePtr());
1467}
1468
1469/// getComplexType - Return the uniqued reference to the type for a complex
1470/// number with the specified element type.
1471QualType ASTContext::getComplexType(QualType T) const {
1472  // Unique pointers, to guarantee there is only one pointer of a particular
1473  // structure.
1474  llvm::FoldingSetNodeID ID;
1475  ComplexType::Profile(ID, T);
1476
1477  void *InsertPos = 0;
1478  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1479    return QualType(CT, 0);
1480
1481  // If the pointee type isn't canonical, this won't be a canonical type either,
1482  // so fill in the canonical type field.
1483  QualType Canonical;
1484  if (!T.isCanonical()) {
1485    Canonical = getComplexType(getCanonicalType(T));
1486
1487    // Get the new insert position for the node we care about.
1488    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1489    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1490  }
1491  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1492  Types.push_back(New);
1493  ComplexTypes.InsertNode(New, InsertPos);
1494  return QualType(New, 0);
1495}
1496
1497/// getPointerType - Return the uniqued reference to the type for a pointer to
1498/// the specified type.
1499QualType ASTContext::getPointerType(QualType T) const {
1500  // Unique pointers, to guarantee there is only one pointer of a particular
1501  // structure.
1502  llvm::FoldingSetNodeID ID;
1503  PointerType::Profile(ID, T);
1504
1505  void *InsertPos = 0;
1506  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1507    return QualType(PT, 0);
1508
1509  // If the pointee type isn't canonical, this won't be a canonical type either,
1510  // so fill in the canonical type field.
1511  QualType Canonical;
1512  if (!T.isCanonical()) {
1513    Canonical = getPointerType(getCanonicalType(T));
1514
1515    // Get the new insert position for the node we care about.
1516    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1517    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1518  }
1519  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1520  Types.push_back(New);
1521  PointerTypes.InsertNode(New, InsertPos);
1522  return QualType(New, 0);
1523}
1524
1525/// getBlockPointerType - Return the uniqued reference to the type for
1526/// a pointer to the specified block.
1527QualType ASTContext::getBlockPointerType(QualType T) const {
1528  assert(T->isFunctionType() && "block of function types only");
1529  // Unique pointers, to guarantee there is only one block of a particular
1530  // structure.
1531  llvm::FoldingSetNodeID ID;
1532  BlockPointerType::Profile(ID, T);
1533
1534  void *InsertPos = 0;
1535  if (BlockPointerType *PT =
1536        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1537    return QualType(PT, 0);
1538
1539  // If the block pointee type isn't canonical, this won't be a canonical
1540  // type either so fill in the canonical type field.
1541  QualType Canonical;
1542  if (!T.isCanonical()) {
1543    Canonical = getBlockPointerType(getCanonicalType(T));
1544
1545    // Get the new insert position for the node we care about.
1546    BlockPointerType *NewIP =
1547      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1548    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1549  }
1550  BlockPointerType *New
1551    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1552  Types.push_back(New);
1553  BlockPointerTypes.InsertNode(New, InsertPos);
1554  return QualType(New, 0);
1555}
1556
1557/// getLValueReferenceType - Return the uniqued reference to the type for an
1558/// lvalue reference to the specified type.
1559QualType
1560ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
1561  assert(getCanonicalType(T) != OverloadTy &&
1562         "Unresolved overloaded function type");
1563
1564  // Unique pointers, to guarantee there is only one pointer of a particular
1565  // structure.
1566  llvm::FoldingSetNodeID ID;
1567  ReferenceType::Profile(ID, T, SpelledAsLValue);
1568
1569  void *InsertPos = 0;
1570  if (LValueReferenceType *RT =
1571        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1572    return QualType(RT, 0);
1573
1574  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1575
1576  // If the referencee type isn't canonical, this won't be a canonical type
1577  // either, so fill in the canonical type field.
1578  QualType Canonical;
1579  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1580    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1581    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1582
1583    // Get the new insert position for the node we care about.
1584    LValueReferenceType *NewIP =
1585      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1586    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1587  }
1588
1589  LValueReferenceType *New
1590    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1591                                                     SpelledAsLValue);
1592  Types.push_back(New);
1593  LValueReferenceTypes.InsertNode(New, InsertPos);
1594
1595  return QualType(New, 0);
1596}
1597
1598/// getRValueReferenceType - Return the uniqued reference to the type for an
1599/// rvalue reference to the specified type.
1600QualType ASTContext::getRValueReferenceType(QualType T) const {
1601  // Unique pointers, to guarantee there is only one pointer of a particular
1602  // structure.
1603  llvm::FoldingSetNodeID ID;
1604  ReferenceType::Profile(ID, T, false);
1605
1606  void *InsertPos = 0;
1607  if (RValueReferenceType *RT =
1608        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1609    return QualType(RT, 0);
1610
1611  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1612
1613  // If the referencee type isn't canonical, this won't be a canonical type
1614  // either, so fill in the canonical type field.
1615  QualType Canonical;
1616  if (InnerRef || !T.isCanonical()) {
1617    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1618    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1619
1620    // Get the new insert position for the node we care about.
1621    RValueReferenceType *NewIP =
1622      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1623    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1624  }
1625
1626  RValueReferenceType *New
1627    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1628  Types.push_back(New);
1629  RValueReferenceTypes.InsertNode(New, InsertPos);
1630  return QualType(New, 0);
1631}
1632
1633/// getMemberPointerType - Return the uniqued reference to the type for a
1634/// member pointer to the specified type, in the specified class.
1635QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
1636  // Unique pointers, to guarantee there is only one pointer of a particular
1637  // structure.
1638  llvm::FoldingSetNodeID ID;
1639  MemberPointerType::Profile(ID, T, Cls);
1640
1641  void *InsertPos = 0;
1642  if (MemberPointerType *PT =
1643      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1644    return QualType(PT, 0);
1645
1646  // If the pointee or class type isn't canonical, this won't be a canonical
1647  // type either, so fill in the canonical type field.
1648  QualType Canonical;
1649  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1650    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1651
1652    // Get the new insert position for the node we care about.
1653    MemberPointerType *NewIP =
1654      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1655    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1656  }
1657  MemberPointerType *New
1658    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1659  Types.push_back(New);
1660  MemberPointerTypes.InsertNode(New, InsertPos);
1661  return QualType(New, 0);
1662}
1663
1664/// getConstantArrayType - Return the unique reference to the type for an
1665/// array of the specified element type.
1666QualType ASTContext::getConstantArrayType(QualType EltTy,
1667                                          const llvm::APInt &ArySizeIn,
1668                                          ArrayType::ArraySizeModifier ASM,
1669                                          unsigned IndexTypeQuals) const {
1670  assert((EltTy->isDependentType() ||
1671          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1672         "Constant array of VLAs is illegal!");
1673
1674  // Convert the array size into a canonical width matching the pointer size for
1675  // the target.
1676  llvm::APInt ArySize(ArySizeIn);
1677  ArySize =
1678    ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
1679
1680  llvm::FoldingSetNodeID ID;
1681  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
1682
1683  void *InsertPos = 0;
1684  if (ConstantArrayType *ATP =
1685      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1686    return QualType(ATP, 0);
1687
1688  // If the element type isn't canonical or has qualifiers, this won't
1689  // be a canonical type either, so fill in the canonical type field.
1690  QualType Canon;
1691  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1692    SplitQualType canonSplit = getCanonicalType(EltTy).split();
1693    Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
1694                                 ASM, IndexTypeQuals);
1695    Canon = getQualifiedType(Canon, canonSplit.Quals);
1696
1697    // Get the new insert position for the node we care about.
1698    ConstantArrayType *NewIP =
1699      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1700    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1701  }
1702
1703  ConstantArrayType *New = new(*this,TypeAlignment)
1704    ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
1705  ConstantArrayTypes.InsertNode(New, InsertPos);
1706  Types.push_back(New);
1707  return QualType(New, 0);
1708}
1709
1710/// getVariableArrayDecayedType - Turns the given type, which may be
1711/// variably-modified, into the corresponding type with all the known
1712/// sizes replaced with [*].
1713QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1714  // Vastly most common case.
1715  if (!type->isVariablyModifiedType()) return type;
1716
1717  QualType result;
1718
1719  SplitQualType split = type.getSplitDesugaredType();
1720  const Type *ty = split.Ty;
1721  switch (ty->getTypeClass()) {
1722#define TYPE(Class, Base)
1723#define ABSTRACT_TYPE(Class, Base)
1724#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1725#include "clang/AST/TypeNodes.def"
1726    llvm_unreachable("didn't desugar past all non-canonical types?");
1727
1728  // These types should never be variably-modified.
1729  case Type::Builtin:
1730  case Type::Complex:
1731  case Type::Vector:
1732  case Type::ExtVector:
1733  case Type::DependentSizedExtVector:
1734  case Type::ObjCObject:
1735  case Type::ObjCInterface:
1736  case Type::ObjCObjectPointer:
1737  case Type::Record:
1738  case Type::Enum:
1739  case Type::UnresolvedUsing:
1740  case Type::TypeOfExpr:
1741  case Type::TypeOf:
1742  case Type::Decltype:
1743  case Type::UnaryTransform:
1744  case Type::DependentName:
1745  case Type::InjectedClassName:
1746  case Type::TemplateSpecialization:
1747  case Type::DependentTemplateSpecialization:
1748  case Type::TemplateTypeParm:
1749  case Type::SubstTemplateTypeParmPack:
1750  case Type::Auto:
1751  case Type::PackExpansion:
1752    llvm_unreachable("type should never be variably-modified");
1753
1754  // These types can be variably-modified but should never need to
1755  // further decay.
1756  case Type::FunctionNoProto:
1757  case Type::FunctionProto:
1758  case Type::BlockPointer:
1759  case Type::MemberPointer:
1760    return type;
1761
1762  // These types can be variably-modified.  All these modifications
1763  // preserve structure except as noted by comments.
1764  // TODO: if we ever care about optimizing VLAs, there are no-op
1765  // optimizations available here.
1766  case Type::Pointer:
1767    result = getPointerType(getVariableArrayDecayedType(
1768                              cast<PointerType>(ty)->getPointeeType()));
1769    break;
1770
1771  case Type::LValueReference: {
1772    const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1773    result = getLValueReferenceType(
1774                 getVariableArrayDecayedType(lv->getPointeeType()),
1775                                    lv->isSpelledAsLValue());
1776    break;
1777  }
1778
1779  case Type::RValueReference: {
1780    const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1781    result = getRValueReferenceType(
1782                 getVariableArrayDecayedType(lv->getPointeeType()));
1783    break;
1784  }
1785
1786  case Type::Atomic: {
1787    const AtomicType *at = cast<AtomicType>(ty);
1788    result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1789    break;
1790  }
1791
1792  case Type::ConstantArray: {
1793    const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1794    result = getConstantArrayType(
1795                 getVariableArrayDecayedType(cat->getElementType()),
1796                                  cat->getSize(),
1797                                  cat->getSizeModifier(),
1798                                  cat->getIndexTypeCVRQualifiers());
1799    break;
1800  }
1801
1802  case Type::DependentSizedArray: {
1803    const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1804    result = getDependentSizedArrayType(
1805                 getVariableArrayDecayedType(dat->getElementType()),
1806                                        dat->getSizeExpr(),
1807                                        dat->getSizeModifier(),
1808                                        dat->getIndexTypeCVRQualifiers(),
1809                                        dat->getBracketsRange());
1810    break;
1811  }
1812
1813  // Turn incomplete types into [*] types.
1814  case Type::IncompleteArray: {
1815    const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1816    result = getVariableArrayType(
1817                 getVariableArrayDecayedType(iat->getElementType()),
1818                                  /*size*/ 0,
1819                                  ArrayType::Normal,
1820                                  iat->getIndexTypeCVRQualifiers(),
1821                                  SourceRange());
1822    break;
1823  }
1824
1825  // Turn VLA types into [*] types.
1826  case Type::VariableArray: {
1827    const VariableArrayType *vat = cast<VariableArrayType>(ty);
1828    result = getVariableArrayType(
1829                 getVariableArrayDecayedType(vat->getElementType()),
1830                                  /*size*/ 0,
1831                                  ArrayType::Star,
1832                                  vat->getIndexTypeCVRQualifiers(),
1833                                  vat->getBracketsRange());
1834    break;
1835  }
1836  }
1837
1838  // Apply the top-level qualifiers from the original.
1839  return getQualifiedType(result, split.Quals);
1840}
1841
1842/// getVariableArrayType - Returns a non-unique reference to the type for a
1843/// variable array of the specified element type.
1844QualType ASTContext::getVariableArrayType(QualType EltTy,
1845                                          Expr *NumElts,
1846                                          ArrayType::ArraySizeModifier ASM,
1847                                          unsigned IndexTypeQuals,
1848                                          SourceRange Brackets) const {
1849  // Since we don't unique expressions, it isn't possible to unique VLA's
1850  // that have an expression provided for their size.
1851  QualType Canon;
1852
1853  // Be sure to pull qualifiers off the element type.
1854  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1855    SplitQualType canonSplit = getCanonicalType(EltTy).split();
1856    Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
1857                                 IndexTypeQuals, Brackets);
1858    Canon = getQualifiedType(Canon, canonSplit.Quals);
1859  }
1860
1861  VariableArrayType *New = new(*this, TypeAlignment)
1862    VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
1863
1864  VariableArrayTypes.push_back(New);
1865  Types.push_back(New);
1866  return QualType(New, 0);
1867}
1868
1869/// getDependentSizedArrayType - Returns a non-unique reference to
1870/// the type for a dependently-sized array of the specified element
1871/// type.
1872QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1873                                                Expr *numElements,
1874                                                ArrayType::ArraySizeModifier ASM,
1875                                                unsigned elementTypeQuals,
1876                                                SourceRange brackets) const {
1877  assert((!numElements || numElements->isTypeDependent() ||
1878          numElements->isValueDependent()) &&
1879         "Size must be type- or value-dependent!");
1880
1881  // Dependently-sized array types that do not have a specified number
1882  // of elements will have their sizes deduced from a dependent
1883  // initializer.  We do no canonicalization here at all, which is okay
1884  // because they can't be used in most locations.
1885  if (!numElements) {
1886    DependentSizedArrayType *newType
1887      = new (*this, TypeAlignment)
1888          DependentSizedArrayType(*this, elementType, QualType(),
1889                                  numElements, ASM, elementTypeQuals,
1890                                  brackets);
1891    Types.push_back(newType);
1892    return QualType(newType, 0);
1893  }
1894
1895  // Otherwise, we actually build a new type every time, but we
1896  // also build a canonical type.
1897
1898  SplitQualType canonElementType = getCanonicalType(elementType).split();
1899
1900  void *insertPos = 0;
1901  llvm::FoldingSetNodeID ID;
1902  DependentSizedArrayType::Profile(ID, *this,
1903                                   QualType(canonElementType.Ty, 0),
1904                                   ASM, elementTypeQuals, numElements);
1905
1906  // Look for an existing type with these properties.
1907  DependentSizedArrayType *canonTy =
1908    DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1909
1910  // If we don't have one, build one.
1911  if (!canonTy) {
1912    canonTy = new (*this, TypeAlignment)
1913      DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
1914                              QualType(), numElements, ASM, elementTypeQuals,
1915                              brackets);
1916    DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
1917    Types.push_back(canonTy);
1918  }
1919
1920  // Apply qualifiers from the element type to the array.
1921  QualType canon = getQualifiedType(QualType(canonTy,0),
1922                                    canonElementType.Quals);
1923
1924  // If we didn't need extra canonicalization for the element type,
1925  // then just use that as our result.
1926  if (QualType(canonElementType.Ty, 0) == elementType)
1927    return canon;
1928
1929  // Otherwise, we need to build a type which follows the spelling
1930  // of the element type.
1931  DependentSizedArrayType *sugaredType
1932    = new (*this, TypeAlignment)
1933        DependentSizedArrayType(*this, elementType, canon, numElements,
1934                                ASM, elementTypeQuals, brackets);
1935  Types.push_back(sugaredType);
1936  return QualType(sugaredType, 0);
1937}
1938
1939QualType ASTContext::getIncompleteArrayType(QualType elementType,
1940                                            ArrayType::ArraySizeModifier ASM,
1941                                            unsigned elementTypeQuals) const {
1942  llvm::FoldingSetNodeID ID;
1943  IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
1944
1945  void *insertPos = 0;
1946  if (IncompleteArrayType *iat =
1947       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
1948    return QualType(iat, 0);
1949
1950  // If the element type isn't canonical, this won't be a canonical type
1951  // either, so fill in the canonical type field.  We also have to pull
1952  // qualifiers off the element type.
1953  QualType canon;
1954
1955  if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
1956    SplitQualType canonSplit = getCanonicalType(elementType).split();
1957    canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
1958                                   ASM, elementTypeQuals);
1959    canon = getQualifiedType(canon, canonSplit.Quals);
1960
1961    // Get the new insert position for the node we care about.
1962    IncompleteArrayType *existing =
1963      IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
1964    assert(!existing && "Shouldn't be in the map!"); (void) existing;
1965  }
1966
1967  IncompleteArrayType *newType = new (*this, TypeAlignment)
1968    IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
1969
1970  IncompleteArrayTypes.InsertNode(newType, insertPos);
1971  Types.push_back(newType);
1972  return QualType(newType, 0);
1973}
1974
1975/// getVectorType - Return the unique reference to a vector type of
1976/// the specified element type and size. VectorType must be a built-in type.
1977QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1978                                   VectorType::VectorKind VecKind) const {
1979  assert(vecType->isBuiltinType());
1980
1981  // Check if we've already instantiated a vector of this type.
1982  llvm::FoldingSetNodeID ID;
1983  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
1984
1985  void *InsertPos = 0;
1986  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1987    return QualType(VTP, 0);
1988
1989  // If the element type isn't canonical, this won't be a canonical type either,
1990  // so fill in the canonical type field.
1991  QualType Canonical;
1992  if (!vecType.isCanonical()) {
1993    Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
1994
1995    // Get the new insert position for the node we care about.
1996    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1997    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1998  }
1999  VectorType *New = new (*this, TypeAlignment)
2000    VectorType(vecType, NumElts, Canonical, VecKind);
2001  VectorTypes.InsertNode(New, InsertPos);
2002  Types.push_back(New);
2003  return QualType(New, 0);
2004}
2005
2006/// getExtVectorType - Return the unique reference to an extended vector type of
2007/// the specified element type and size. VectorType must be a built-in type.
2008QualType
2009ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2010  assert(vecType->isBuiltinType() || vecType->isDependentType());
2011
2012  // Check if we've already instantiated a vector of this type.
2013  llvm::FoldingSetNodeID ID;
2014  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2015                      VectorType::GenericVector);
2016  void *InsertPos = 0;
2017  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2018    return QualType(VTP, 0);
2019
2020  // If the element type isn't canonical, this won't be a canonical type either,
2021  // so fill in the canonical type field.
2022  QualType Canonical;
2023  if (!vecType.isCanonical()) {
2024    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2025
2026    // Get the new insert position for the node we care about.
2027    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2028    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2029  }
2030  ExtVectorType *New = new (*this, TypeAlignment)
2031    ExtVectorType(vecType, NumElts, Canonical);
2032  VectorTypes.InsertNode(New, InsertPos);
2033  Types.push_back(New);
2034  return QualType(New, 0);
2035}
2036
2037QualType
2038ASTContext::getDependentSizedExtVectorType(QualType vecType,
2039                                           Expr *SizeExpr,
2040                                           SourceLocation AttrLoc) const {
2041  llvm::FoldingSetNodeID ID;
2042  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2043                                       SizeExpr);
2044
2045  void *InsertPos = 0;
2046  DependentSizedExtVectorType *Canon
2047    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2048  DependentSizedExtVectorType *New;
2049  if (Canon) {
2050    // We already have a canonical version of this array type; use it as
2051    // the canonical type for a newly-built type.
2052    New = new (*this, TypeAlignment)
2053      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2054                                  SizeExpr, AttrLoc);
2055  } else {
2056    QualType CanonVecTy = getCanonicalType(vecType);
2057    if (CanonVecTy == vecType) {
2058      New = new (*this, TypeAlignment)
2059        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2060                                    AttrLoc);
2061
2062      DependentSizedExtVectorType *CanonCheck
2063        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2064      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2065      (void)CanonCheck;
2066      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2067    } else {
2068      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2069                                                      SourceLocation());
2070      New = new (*this, TypeAlignment)
2071        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2072    }
2073  }
2074
2075  Types.push_back(New);
2076  return QualType(New, 0);
2077}
2078
2079/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2080///
2081QualType
2082ASTContext::getFunctionNoProtoType(QualType ResultTy,
2083                                   const FunctionType::ExtInfo &Info) const {
2084  const CallingConv DefaultCC = Info.getCC();
2085  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2086                               CC_X86StdCall : DefaultCC;
2087  // Unique functions, to guarantee there is only one function of a particular
2088  // structure.
2089  llvm::FoldingSetNodeID ID;
2090  FunctionNoProtoType::Profile(ID, ResultTy, Info);
2091
2092  void *InsertPos = 0;
2093  if (FunctionNoProtoType *FT =
2094        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2095    return QualType(FT, 0);
2096
2097  QualType Canonical;
2098  if (!ResultTy.isCanonical() ||
2099      getCanonicalCallConv(CallConv) != CallConv) {
2100    Canonical =
2101      getFunctionNoProtoType(getCanonicalType(ResultTy),
2102                     Info.withCallingConv(getCanonicalCallConv(CallConv)));
2103
2104    // Get the new insert position for the node we care about.
2105    FunctionNoProtoType *NewIP =
2106      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2107    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2108  }
2109
2110  FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2111  FunctionNoProtoType *New = new (*this, TypeAlignment)
2112    FunctionNoProtoType(ResultTy, Canonical, newInfo);
2113  Types.push_back(New);
2114  FunctionNoProtoTypes.InsertNode(New, InsertPos);
2115  return QualType(New, 0);
2116}
2117
2118/// getFunctionType - Return a normal function type with a typed argument
2119/// list.  isVariadic indicates whether the argument list includes '...'.
2120QualType
2121ASTContext::getFunctionType(QualType ResultTy,
2122                            const QualType *ArgArray, unsigned NumArgs,
2123                            const FunctionProtoType::ExtProtoInfo &EPI) const {
2124  // Unique functions, to guarantee there is only one function of a particular
2125  // structure.
2126  llvm::FoldingSetNodeID ID;
2127  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
2128
2129  void *InsertPos = 0;
2130  if (FunctionProtoType *FTP =
2131        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2132    return QualType(FTP, 0);
2133
2134  // Determine whether the type being created is already canonical or not.
2135  bool isCanonical= EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical();
2136  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2137    if (!ArgArray[i].isCanonicalAsParam())
2138      isCanonical = false;
2139
2140  const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2141  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2142                               CC_X86StdCall : DefaultCC;
2143
2144  // If this type isn't canonical, get the canonical version of it.
2145  // The exception spec is not part of the canonical type.
2146  QualType Canonical;
2147  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
2148    SmallVector<QualType, 16> CanonicalArgs;
2149    CanonicalArgs.reserve(NumArgs);
2150    for (unsigned i = 0; i != NumArgs; ++i)
2151      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2152
2153    FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2154    CanonicalEPI.ExceptionSpecType = EST_None;
2155    CanonicalEPI.NumExceptions = 0;
2156    CanonicalEPI.ExtInfo
2157      = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2158
2159    Canonical = getFunctionType(getCanonicalType(ResultTy),
2160                                CanonicalArgs.data(), NumArgs,
2161                                CanonicalEPI);
2162
2163    // Get the new insert position for the node we care about.
2164    FunctionProtoType *NewIP =
2165      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2166    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2167  }
2168
2169  // FunctionProtoType objects are allocated with extra bytes after
2170  // them for three variable size arrays at the end:
2171  //  - parameter types
2172  //  - exception types
2173  //  - consumed-arguments flags
2174  // Instead of the exception types, there could be a noexcept
2175  // expression.
2176  size_t Size = sizeof(FunctionProtoType) +
2177                NumArgs * sizeof(QualType);
2178  if (EPI.ExceptionSpecType == EST_Dynamic)
2179    Size += EPI.NumExceptions * sizeof(QualType);
2180  else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2181    Size += sizeof(Expr*);
2182  }
2183  if (EPI.ConsumedArguments)
2184    Size += NumArgs * sizeof(bool);
2185
2186  FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2187  FunctionProtoType::ExtProtoInfo newEPI = EPI;
2188  newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
2189  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
2190  Types.push_back(FTP);
2191  FunctionProtoTypes.InsertNode(FTP, InsertPos);
2192  return QualType(FTP, 0);
2193}
2194
2195#ifndef NDEBUG
2196static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2197  if (!isa<CXXRecordDecl>(D)) return false;
2198  const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2199  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2200    return true;
2201  if (RD->getDescribedClassTemplate() &&
2202      !isa<ClassTemplateSpecializationDecl>(RD))
2203    return true;
2204  return false;
2205}
2206#endif
2207
2208/// getInjectedClassNameType - Return the unique reference to the
2209/// injected class name type for the specified templated declaration.
2210QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2211                                              QualType TST) const {
2212  assert(NeedsInjectedClassNameType(Decl));
2213  if (Decl->TypeForDecl) {
2214    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2215  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2216    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2217    Decl->TypeForDecl = PrevDecl->TypeForDecl;
2218    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2219  } else {
2220    Type *newType =
2221      new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2222    Decl->TypeForDecl = newType;
2223    Types.push_back(newType);
2224  }
2225  return QualType(Decl->TypeForDecl, 0);
2226}
2227
2228/// getTypeDeclType - Return the unique reference to the type for the
2229/// specified type declaration.
2230QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2231  assert(Decl && "Passed null for Decl param");
2232  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2233
2234  if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2235    return getTypedefType(Typedef);
2236
2237  assert(!isa<TemplateTypeParmDecl>(Decl) &&
2238         "Template type parameter types are always available.");
2239
2240  if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2241    assert(!Record->getPreviousDecl() &&
2242           "struct/union has previous declaration");
2243    assert(!NeedsInjectedClassNameType(Record));
2244    return getRecordType(Record);
2245  } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2246    assert(!Enum->getPreviousDecl() &&
2247           "enum has previous declaration");
2248    return getEnumType(Enum);
2249  } else if (const UnresolvedUsingTypenameDecl *Using =
2250               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2251    Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2252    Decl->TypeForDecl = newType;
2253    Types.push_back(newType);
2254  } else
2255    llvm_unreachable("TypeDecl without a type?");
2256
2257  return QualType(Decl->TypeForDecl, 0);
2258}
2259
2260/// getTypedefType - Return the unique reference to the type for the
2261/// specified typedef name decl.
2262QualType
2263ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2264                           QualType Canonical) const {
2265  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2266
2267  if (Canonical.isNull())
2268    Canonical = getCanonicalType(Decl->getUnderlyingType());
2269  TypedefType *newType = new(*this, TypeAlignment)
2270    TypedefType(Type::Typedef, Decl, Canonical);
2271  Decl->TypeForDecl = newType;
2272  Types.push_back(newType);
2273  return QualType(newType, 0);
2274}
2275
2276QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2277  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2278
2279  if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2280    if (PrevDecl->TypeForDecl)
2281      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2282
2283  RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2284  Decl->TypeForDecl = newType;
2285  Types.push_back(newType);
2286  return QualType(newType, 0);
2287}
2288
2289QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2290  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2291
2292  if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
2293    if (PrevDecl->TypeForDecl)
2294      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2295
2296  EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2297  Decl->TypeForDecl = newType;
2298  Types.push_back(newType);
2299  return QualType(newType, 0);
2300}
2301
2302QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2303                                       QualType modifiedType,
2304                                       QualType equivalentType) {
2305  llvm::FoldingSetNodeID id;
2306  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2307
2308  void *insertPos = 0;
2309  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2310  if (type) return QualType(type, 0);
2311
2312  QualType canon = getCanonicalType(equivalentType);
2313  type = new (*this, TypeAlignment)
2314           AttributedType(canon, attrKind, modifiedType, equivalentType);
2315
2316  Types.push_back(type);
2317  AttributedTypes.InsertNode(type, insertPos);
2318
2319  return QualType(type, 0);
2320}
2321
2322
2323/// \brief Retrieve a substitution-result type.
2324QualType
2325ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2326                                         QualType Replacement) const {
2327  assert(Replacement.isCanonical()
2328         && "replacement types must always be canonical");
2329
2330  llvm::FoldingSetNodeID ID;
2331  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2332  void *InsertPos = 0;
2333  SubstTemplateTypeParmType *SubstParm
2334    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2335
2336  if (!SubstParm) {
2337    SubstParm = new (*this, TypeAlignment)
2338      SubstTemplateTypeParmType(Parm, Replacement);
2339    Types.push_back(SubstParm);
2340    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2341  }
2342
2343  return QualType(SubstParm, 0);
2344}
2345
2346/// \brief Retrieve a
2347QualType ASTContext::getSubstTemplateTypeParmPackType(
2348                                          const TemplateTypeParmType *Parm,
2349                                              const TemplateArgument &ArgPack) {
2350#ifndef NDEBUG
2351  for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2352                                    PEnd = ArgPack.pack_end();
2353       P != PEnd; ++P) {
2354    assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2355    assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2356  }
2357#endif
2358
2359  llvm::FoldingSetNodeID ID;
2360  SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2361  void *InsertPos = 0;
2362  if (SubstTemplateTypeParmPackType *SubstParm
2363        = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2364    return QualType(SubstParm, 0);
2365
2366  QualType Canon;
2367  if (!Parm->isCanonicalUnqualified()) {
2368    Canon = getCanonicalType(QualType(Parm, 0));
2369    Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2370                                             ArgPack);
2371    SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2372  }
2373
2374  SubstTemplateTypeParmPackType *SubstParm
2375    = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2376                                                               ArgPack);
2377  Types.push_back(SubstParm);
2378  SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2379  return QualType(SubstParm, 0);
2380}
2381
2382/// \brief Retrieve the template type parameter type for a template
2383/// parameter or parameter pack with the given depth, index, and (optionally)
2384/// name.
2385QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2386                                             bool ParameterPack,
2387                                             TemplateTypeParmDecl *TTPDecl) const {
2388  llvm::FoldingSetNodeID ID;
2389  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
2390  void *InsertPos = 0;
2391  TemplateTypeParmType *TypeParm
2392    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2393
2394  if (TypeParm)
2395    return QualType(TypeParm, 0);
2396
2397  if (TTPDecl) {
2398    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2399    TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
2400
2401    TemplateTypeParmType *TypeCheck
2402      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2403    assert(!TypeCheck && "Template type parameter canonical type broken");
2404    (void)TypeCheck;
2405  } else
2406    TypeParm = new (*this, TypeAlignment)
2407      TemplateTypeParmType(Depth, Index, ParameterPack);
2408
2409  Types.push_back(TypeParm);
2410  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2411
2412  return QualType(TypeParm, 0);
2413}
2414
2415TypeSourceInfo *
2416ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2417                                              SourceLocation NameLoc,
2418                                        const TemplateArgumentListInfo &Args,
2419                                              QualType Underlying) const {
2420  assert(!Name.getAsDependentTemplateName() &&
2421         "No dependent template names here!");
2422  QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
2423
2424  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2425  TemplateSpecializationTypeLoc TL
2426    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2427  TL.setTemplateKeywordLoc(SourceLocation());
2428  TL.setTemplateNameLoc(NameLoc);
2429  TL.setLAngleLoc(Args.getLAngleLoc());
2430  TL.setRAngleLoc(Args.getRAngleLoc());
2431  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2432    TL.setArgLocInfo(i, Args[i].getLocInfo());
2433  return DI;
2434}
2435
2436QualType
2437ASTContext::getTemplateSpecializationType(TemplateName Template,
2438                                          const TemplateArgumentListInfo &Args,
2439                                          QualType Underlying) const {
2440  assert(!Template.getAsDependentTemplateName() &&
2441         "No dependent template names here!");
2442
2443  unsigned NumArgs = Args.size();
2444
2445  SmallVector<TemplateArgument, 4> ArgVec;
2446  ArgVec.reserve(NumArgs);
2447  for (unsigned i = 0; i != NumArgs; ++i)
2448    ArgVec.push_back(Args[i].getArgument());
2449
2450  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2451                                       Underlying);
2452}
2453
2454#ifndef NDEBUG
2455static bool hasAnyPackExpansions(const TemplateArgument *Args,
2456                                 unsigned NumArgs) {
2457  for (unsigned I = 0; I != NumArgs; ++I)
2458    if (Args[I].isPackExpansion())
2459      return true;
2460
2461  return true;
2462}
2463#endif
2464
2465QualType
2466ASTContext::getTemplateSpecializationType(TemplateName Template,
2467                                          const TemplateArgument *Args,
2468                                          unsigned NumArgs,
2469                                          QualType Underlying) const {
2470  assert(!Template.getAsDependentTemplateName() &&
2471         "No dependent template names here!");
2472  // Look through qualified template names.
2473  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2474    Template = TemplateName(QTN->getTemplateDecl());
2475
2476  bool IsTypeAlias =
2477    Template.getAsTemplateDecl() &&
2478    isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2479  QualType CanonType;
2480  if (!Underlying.isNull())
2481    CanonType = getCanonicalType(Underlying);
2482  else {
2483    // We can get here with an alias template when the specialization contains
2484    // a pack expansion that does not match up with a parameter pack.
2485    assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2486           "Caller must compute aliased type");
2487    IsTypeAlias = false;
2488    CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2489                                                       NumArgs);
2490  }
2491
2492  // Allocate the (non-canonical) template specialization type, but don't
2493  // try to unique it: these types typically have location information that
2494  // we don't unique and don't want to lose.
2495  void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2496                       sizeof(TemplateArgument) * NumArgs +
2497                       (IsTypeAlias? sizeof(QualType) : 0),
2498                       TypeAlignment);
2499  TemplateSpecializationType *Spec
2500    = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2501                                         IsTypeAlias ? Underlying : QualType());
2502
2503  Types.push_back(Spec);
2504  return QualType(Spec, 0);
2505}
2506
2507QualType
2508ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2509                                                   const TemplateArgument *Args,
2510                                                   unsigned NumArgs) const {
2511  assert(!Template.getAsDependentTemplateName() &&
2512         "No dependent template names here!");
2513
2514  // Look through qualified template names.
2515  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2516    Template = TemplateName(QTN->getTemplateDecl());
2517
2518  // Build the canonical template specialization type.
2519  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2520  SmallVector<TemplateArgument, 4> CanonArgs;
2521  CanonArgs.reserve(NumArgs);
2522  for (unsigned I = 0; I != NumArgs; ++I)
2523    CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2524
2525  // Determine whether this canonical template specialization type already
2526  // exists.
2527  llvm::FoldingSetNodeID ID;
2528  TemplateSpecializationType::Profile(ID, CanonTemplate,
2529                                      CanonArgs.data(), NumArgs, *this);
2530
2531  void *InsertPos = 0;
2532  TemplateSpecializationType *Spec
2533    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2534
2535  if (!Spec) {
2536    // Allocate a new canonical template specialization type.
2537    void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2538                          sizeof(TemplateArgument) * NumArgs),
2539                         TypeAlignment);
2540    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2541                                                CanonArgs.data(), NumArgs,
2542                                                QualType(), QualType());
2543    Types.push_back(Spec);
2544    TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2545  }
2546
2547  assert(Spec->isDependentType() &&
2548         "Non-dependent template-id type must have a canonical type");
2549  return QualType(Spec, 0);
2550}
2551
2552QualType
2553ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2554                              NestedNameSpecifier *NNS,
2555                              QualType NamedType) const {
2556  llvm::FoldingSetNodeID ID;
2557  ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2558
2559  void *InsertPos = 0;
2560  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2561  if (T)
2562    return QualType(T, 0);
2563
2564  QualType Canon = NamedType;
2565  if (!Canon.isCanonical()) {
2566    Canon = getCanonicalType(NamedType);
2567    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2568    assert(!CheckT && "Elaborated canonical type broken");
2569    (void)CheckT;
2570  }
2571
2572  T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2573  Types.push_back(T);
2574  ElaboratedTypes.InsertNode(T, InsertPos);
2575  return QualType(T, 0);
2576}
2577
2578QualType
2579ASTContext::getParenType(QualType InnerType) const {
2580  llvm::FoldingSetNodeID ID;
2581  ParenType::Profile(ID, InnerType);
2582
2583  void *InsertPos = 0;
2584  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2585  if (T)
2586    return QualType(T, 0);
2587
2588  QualType Canon = InnerType;
2589  if (!Canon.isCanonical()) {
2590    Canon = getCanonicalType(InnerType);
2591    ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2592    assert(!CheckT && "Paren canonical type broken");
2593    (void)CheckT;
2594  }
2595
2596  T = new (*this) ParenType(InnerType, Canon);
2597  Types.push_back(T);
2598  ParenTypes.InsertNode(T, InsertPos);
2599  return QualType(T, 0);
2600}
2601
2602QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2603                                          NestedNameSpecifier *NNS,
2604                                          const IdentifierInfo *Name,
2605                                          QualType Canon) const {
2606  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2607
2608  if (Canon.isNull()) {
2609    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2610    ElaboratedTypeKeyword CanonKeyword = Keyword;
2611    if (Keyword == ETK_None)
2612      CanonKeyword = ETK_Typename;
2613
2614    if (CanonNNS != NNS || CanonKeyword != Keyword)
2615      Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2616  }
2617
2618  llvm::FoldingSetNodeID ID;
2619  DependentNameType::Profile(ID, Keyword, NNS, Name);
2620
2621  void *InsertPos = 0;
2622  DependentNameType *T
2623    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2624  if (T)
2625    return QualType(T, 0);
2626
2627  T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2628  Types.push_back(T);
2629  DependentNameTypes.InsertNode(T, InsertPos);
2630  return QualType(T, 0);
2631}
2632
2633QualType
2634ASTContext::getDependentTemplateSpecializationType(
2635                                 ElaboratedTypeKeyword Keyword,
2636                                 NestedNameSpecifier *NNS,
2637                                 const IdentifierInfo *Name,
2638                                 const TemplateArgumentListInfo &Args) const {
2639  // TODO: avoid this copy
2640  SmallVector<TemplateArgument, 16> ArgCopy;
2641  for (unsigned I = 0, E = Args.size(); I != E; ++I)
2642    ArgCopy.push_back(Args[I].getArgument());
2643  return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2644                                                ArgCopy.size(),
2645                                                ArgCopy.data());
2646}
2647
2648QualType
2649ASTContext::getDependentTemplateSpecializationType(
2650                                 ElaboratedTypeKeyword Keyword,
2651                                 NestedNameSpecifier *NNS,
2652                                 const IdentifierInfo *Name,
2653                                 unsigned NumArgs,
2654                                 const TemplateArgument *Args) const {
2655  assert((!NNS || NNS->isDependent()) &&
2656         "nested-name-specifier must be dependent");
2657
2658  llvm::FoldingSetNodeID ID;
2659  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2660                                               Name, NumArgs, Args);
2661
2662  void *InsertPos = 0;
2663  DependentTemplateSpecializationType *T
2664    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2665  if (T)
2666    return QualType(T, 0);
2667
2668  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2669
2670  ElaboratedTypeKeyword CanonKeyword = Keyword;
2671  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2672
2673  bool AnyNonCanonArgs = false;
2674  SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2675  for (unsigned I = 0; I != NumArgs; ++I) {
2676    CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2677    if (!CanonArgs[I].structurallyEquals(Args[I]))
2678      AnyNonCanonArgs = true;
2679  }
2680
2681  QualType Canon;
2682  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2683    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2684                                                   Name, NumArgs,
2685                                                   CanonArgs.data());
2686
2687    // Find the insert position again.
2688    DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2689  }
2690
2691  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2692                        sizeof(TemplateArgument) * NumArgs),
2693                       TypeAlignment);
2694  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2695                                                    Name, NumArgs, Args, Canon);
2696  Types.push_back(T);
2697  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2698  return QualType(T, 0);
2699}
2700
2701QualType ASTContext::getPackExpansionType(QualType Pattern,
2702                                      llvm::Optional<unsigned> NumExpansions) {
2703  llvm::FoldingSetNodeID ID;
2704  PackExpansionType::Profile(ID, Pattern, NumExpansions);
2705
2706  assert(Pattern->containsUnexpandedParameterPack() &&
2707         "Pack expansions must expand one or more parameter packs");
2708  void *InsertPos = 0;
2709  PackExpansionType *T
2710    = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2711  if (T)
2712    return QualType(T, 0);
2713
2714  QualType Canon;
2715  if (!Pattern.isCanonical()) {
2716    Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
2717
2718    // Find the insert position again.
2719    PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2720  }
2721
2722  T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
2723  Types.push_back(T);
2724  PackExpansionTypes.InsertNode(T, InsertPos);
2725  return QualType(T, 0);
2726}
2727
2728/// CmpProtocolNames - Comparison predicate for sorting protocols
2729/// alphabetically.
2730static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2731                            const ObjCProtocolDecl *RHS) {
2732  return LHS->getDeclName() < RHS->getDeclName();
2733}
2734
2735static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2736                                unsigned NumProtocols) {
2737  if (NumProtocols == 0) return true;
2738
2739  if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2740    return false;
2741
2742  for (unsigned i = 1; i != NumProtocols; ++i)
2743    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2744        Protocols[i]->getCanonicalDecl() != Protocols[i])
2745      return false;
2746  return true;
2747}
2748
2749static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2750                                   unsigned &NumProtocols) {
2751  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2752
2753  // Sort protocols, keyed by name.
2754  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2755
2756  // Canonicalize.
2757  for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2758    Protocols[I] = Protocols[I]->getCanonicalDecl();
2759
2760  // Remove duplicates.
2761  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2762  NumProtocols = ProtocolsEnd-Protocols;
2763}
2764
2765QualType ASTContext::getObjCObjectType(QualType BaseType,
2766                                       ObjCProtocolDecl * const *Protocols,
2767                                       unsigned NumProtocols) const {
2768  // If the base type is an interface and there aren't any protocols
2769  // to add, then the interface type will do just fine.
2770  if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2771    return BaseType;
2772
2773  // Look in the folding set for an existing type.
2774  llvm::FoldingSetNodeID ID;
2775  ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2776  void *InsertPos = 0;
2777  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2778    return QualType(QT, 0);
2779
2780  // Build the canonical type, which has the canonical base type and
2781  // a sorted-and-uniqued list of protocols.
2782  QualType Canonical;
2783  bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2784  if (!ProtocolsSorted || !BaseType.isCanonical()) {
2785    if (!ProtocolsSorted) {
2786      SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2787                                                     Protocols + NumProtocols);
2788      unsigned UniqueCount = NumProtocols;
2789
2790      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2791      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2792                                    &Sorted[0], UniqueCount);
2793    } else {
2794      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2795                                    Protocols, NumProtocols);
2796    }
2797
2798    // Regenerate InsertPos.
2799    ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2800  }
2801
2802  unsigned Size = sizeof(ObjCObjectTypeImpl);
2803  Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2804  void *Mem = Allocate(Size, TypeAlignment);
2805  ObjCObjectTypeImpl *T =
2806    new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2807
2808  Types.push_back(T);
2809  ObjCObjectTypes.InsertNode(T, InsertPos);
2810  return QualType(T, 0);
2811}
2812
2813/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2814/// the given object type.
2815QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
2816  llvm::FoldingSetNodeID ID;
2817  ObjCObjectPointerType::Profile(ID, ObjectT);
2818
2819  void *InsertPos = 0;
2820  if (ObjCObjectPointerType *QT =
2821              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2822    return QualType(QT, 0);
2823
2824  // Find the canonical object type.
2825  QualType Canonical;
2826  if (!ObjectT.isCanonical()) {
2827    Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2828
2829    // Regenerate InsertPos.
2830    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2831  }
2832
2833  // No match.
2834  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2835  ObjCObjectPointerType *QType =
2836    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2837
2838  Types.push_back(QType);
2839  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2840  return QualType(QType, 0);
2841}
2842
2843/// getObjCInterfaceType - Return the unique reference to the type for the
2844/// specified ObjC interface decl. The list of protocols is optional.
2845QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2846                                          ObjCInterfaceDecl *PrevDecl) const {
2847  if (Decl->TypeForDecl)
2848    return QualType(Decl->TypeForDecl, 0);
2849
2850  if (PrevDecl) {
2851    assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2852    Decl->TypeForDecl = PrevDecl->TypeForDecl;
2853    return QualType(PrevDecl->TypeForDecl, 0);
2854  }
2855
2856  // Prefer the definition, if there is one.
2857  if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2858    Decl = Def;
2859
2860  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2861  ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2862  Decl->TypeForDecl = T;
2863  Types.push_back(T);
2864  return QualType(T, 0);
2865}
2866
2867/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2868/// TypeOfExprType AST's (since expression's are never shared). For example,
2869/// multiple declarations that refer to "typeof(x)" all contain different
2870/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2871/// on canonical type's (which are always unique).
2872QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
2873  TypeOfExprType *toe;
2874  if (tofExpr->isTypeDependent()) {
2875    llvm::FoldingSetNodeID ID;
2876    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2877
2878    void *InsertPos = 0;
2879    DependentTypeOfExprType *Canon
2880      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2881    if (Canon) {
2882      // We already have a "canonical" version of an identical, dependent
2883      // typeof(expr) type. Use that as our canonical type.
2884      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2885                                          QualType((TypeOfExprType*)Canon, 0));
2886    } else {
2887      // Build a new, canonical typeof(expr) type.
2888      Canon
2889        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2890      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2891      toe = Canon;
2892    }
2893  } else {
2894    QualType Canonical = getCanonicalType(tofExpr->getType());
2895    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2896  }
2897  Types.push_back(toe);
2898  return QualType(toe, 0);
2899}
2900
2901/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2902/// TypeOfType AST's. The only motivation to unique these nodes would be
2903/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2904/// an issue. This doesn't effect the type checker, since it operates
2905/// on canonical type's (which are always unique).
2906QualType ASTContext::getTypeOfType(QualType tofType) const {
2907  QualType Canonical = getCanonicalType(tofType);
2908  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2909  Types.push_back(tot);
2910  return QualType(tot, 0);
2911}
2912
2913/// getDecltypeForExpr - Given an expr, will return the decltype for that
2914/// expression, according to the rules in C++0x [dcl.type.simple]p4
2915static QualType getDecltypeForExpr(const Expr *e, const ASTContext &Context) {
2916  if (e->isTypeDependent())
2917    return Context.DependentTy;
2918
2919  // If e is an id expression or a class member access, decltype(e) is defined
2920  // as the type of the entity named by e.
2921  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2922    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2923      return VD->getType();
2924  }
2925  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2926    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2927      return FD->getType();
2928  }
2929  // If e is a function call or an invocation of an overloaded operator,
2930  // (parentheses around e are ignored), decltype(e) is defined as the
2931  // return type of that function.
2932  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2933    return CE->getCallReturnType();
2934
2935  QualType T = e->getType();
2936
2937  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2938  // defined as T&, otherwise decltype(e) is defined as T.
2939  if (e->isLValue())
2940    T = Context.getLValueReferenceType(T);
2941
2942  return T;
2943}
2944
2945/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2946/// DecltypeType AST's. The only motivation to unique these nodes would be
2947/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2948/// an issue. This doesn't effect the type checker, since it operates
2949/// on canonical types (which are always unique).
2950QualType ASTContext::getDecltypeType(Expr *e) const {
2951  DecltypeType *dt;
2952
2953  // C++0x [temp.type]p2:
2954  //   If an expression e involves a template parameter, decltype(e) denotes a
2955  //   unique dependent type. Two such decltype-specifiers refer to the same
2956  //   type only if their expressions are equivalent (14.5.6.1).
2957  if (e->isInstantiationDependent()) {
2958    llvm::FoldingSetNodeID ID;
2959    DependentDecltypeType::Profile(ID, *this, e);
2960
2961    void *InsertPos = 0;
2962    DependentDecltypeType *Canon
2963      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2964    if (Canon) {
2965      // We already have a "canonical" version of an equivalent, dependent
2966      // decltype type. Use that as our canonical type.
2967      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2968                                       QualType((DecltypeType*)Canon, 0));
2969    } else {
2970      // Build a new, canonical typeof(expr) type.
2971      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2972      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2973      dt = Canon;
2974    }
2975  } else {
2976    QualType T = getDecltypeForExpr(e, *this);
2977    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2978  }
2979  Types.push_back(dt);
2980  return QualType(dt, 0);
2981}
2982
2983/// getUnaryTransformationType - We don't unique these, since the memory
2984/// savings are minimal and these are rare.
2985QualType ASTContext::getUnaryTransformType(QualType BaseType,
2986                                           QualType UnderlyingType,
2987                                           UnaryTransformType::UTTKind Kind)
2988    const {
2989  UnaryTransformType *Ty =
2990    new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2991                                                   Kind,
2992                                 UnderlyingType->isDependentType() ?
2993                                    QualType() : UnderlyingType);
2994  Types.push_back(Ty);
2995  return QualType(Ty, 0);
2996}
2997
2998/// getAutoType - We only unique auto types after they've been deduced.
2999QualType ASTContext::getAutoType(QualType DeducedType) const {
3000  void *InsertPos = 0;
3001  if (!DeducedType.isNull()) {
3002    // Look in the folding set for an existing type.
3003    llvm::FoldingSetNodeID ID;
3004    AutoType::Profile(ID, DeducedType);
3005    if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3006      return QualType(AT, 0);
3007  }
3008
3009  AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3010  Types.push_back(AT);
3011  if (InsertPos)
3012    AutoTypes.InsertNode(AT, InsertPos);
3013  return QualType(AT, 0);
3014}
3015
3016/// getAtomicType - Return the uniqued reference to the atomic type for
3017/// the given value type.
3018QualType ASTContext::getAtomicType(QualType T) const {
3019  // Unique pointers, to guarantee there is only one pointer of a particular
3020  // structure.
3021  llvm::FoldingSetNodeID ID;
3022  AtomicType::Profile(ID, T);
3023
3024  void *InsertPos = 0;
3025  if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3026    return QualType(AT, 0);
3027
3028  // If the atomic value type isn't canonical, this won't be a canonical type
3029  // either, so fill in the canonical type field.
3030  QualType Canonical;
3031  if (!T.isCanonical()) {
3032    Canonical = getAtomicType(getCanonicalType(T));
3033
3034    // Get the new insert position for the node we care about.
3035    AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3036    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3037  }
3038  AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3039  Types.push_back(New);
3040  AtomicTypes.InsertNode(New, InsertPos);
3041  return QualType(New, 0);
3042}
3043
3044/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3045QualType ASTContext::getAutoDeductType() const {
3046  if (AutoDeductTy.isNull())
3047    AutoDeductTy = getAutoType(QualType());
3048  assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3049  return AutoDeductTy;
3050}
3051
3052/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3053QualType ASTContext::getAutoRRefDeductType() const {
3054  if (AutoRRefDeductTy.isNull())
3055    AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3056  assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3057  return AutoRRefDeductTy;
3058}
3059
3060/// getTagDeclType - Return the unique reference to the type for the
3061/// specified TagDecl (struct/union/class/enum) decl.
3062QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3063  assert (Decl);
3064  // FIXME: What is the design on getTagDeclType when it requires casting
3065  // away const?  mutable?
3066  return getTypeDeclType(const_cast<TagDecl*>(Decl));
3067}
3068
3069/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3070/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3071/// needs to agree with the definition in <stddef.h>.
3072CanQualType ASTContext::getSizeType() const {
3073  return getFromTargetType(Target->getSizeType());
3074}
3075
3076/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3077CanQualType ASTContext::getIntMaxType() const {
3078  return getFromTargetType(Target->getIntMaxType());
3079}
3080
3081/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3082CanQualType ASTContext::getUIntMaxType() const {
3083  return getFromTargetType(Target->getUIntMaxType());
3084}
3085
3086/// getSignedWCharType - Return the type of "signed wchar_t".
3087/// Used when in C++, as a GCC extension.
3088QualType ASTContext::getSignedWCharType() const {
3089  // FIXME: derive from "Target" ?
3090  return WCharTy;
3091}
3092
3093/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3094/// Used when in C++, as a GCC extension.
3095QualType ASTContext::getUnsignedWCharType() const {
3096  // FIXME: derive from "Target" ?
3097  return UnsignedIntTy;
3098}
3099
3100/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3101/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3102QualType ASTContext::getPointerDiffType() const {
3103  return getFromTargetType(Target->getPtrDiffType(0));
3104}
3105
3106//===----------------------------------------------------------------------===//
3107//                              Type Operators
3108//===----------------------------------------------------------------------===//
3109
3110CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3111  // Push qualifiers into arrays, and then discard any remaining
3112  // qualifiers.
3113  T = getCanonicalType(T);
3114  T = getVariableArrayDecayedType(T);
3115  const Type *Ty = T.getTypePtr();
3116  QualType Result;
3117  if (isa<ArrayType>(Ty)) {
3118    Result = getArrayDecayedType(QualType(Ty,0));
3119  } else if (isa<FunctionType>(Ty)) {
3120    Result = getPointerType(QualType(Ty, 0));
3121  } else {
3122    Result = QualType(Ty, 0);
3123  }
3124
3125  return CanQualType::CreateUnsafe(Result);
3126}
3127
3128QualType ASTContext::getUnqualifiedArrayType(QualType type,
3129                                             Qualifiers &quals) {
3130  SplitQualType splitType = type.getSplitUnqualifiedType();
3131
3132  // FIXME: getSplitUnqualifiedType() actually walks all the way to
3133  // the unqualified desugared type and then drops it on the floor.
3134  // We then have to strip that sugar back off with
3135  // getUnqualifiedDesugaredType(), which is silly.
3136  const ArrayType *AT =
3137    dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3138
3139  // If we don't have an array, just use the results in splitType.
3140  if (!AT) {
3141    quals = splitType.Quals;
3142    return QualType(splitType.Ty, 0);
3143  }
3144
3145  // Otherwise, recurse on the array's element type.
3146  QualType elementType = AT->getElementType();
3147  QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3148
3149  // If that didn't change the element type, AT has no qualifiers, so we
3150  // can just use the results in splitType.
3151  if (elementType == unqualElementType) {
3152    assert(quals.empty()); // from the recursive call
3153    quals = splitType.Quals;
3154    return QualType(splitType.Ty, 0);
3155  }
3156
3157  // Otherwise, add in the qualifiers from the outermost type, then
3158  // build the type back up.
3159  quals.addConsistentQualifiers(splitType.Quals);
3160
3161  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3162    return getConstantArrayType(unqualElementType, CAT->getSize(),
3163                                CAT->getSizeModifier(), 0);
3164  }
3165
3166  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3167    return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3168  }
3169
3170  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3171    return getVariableArrayType(unqualElementType,
3172                                VAT->getSizeExpr(),
3173                                VAT->getSizeModifier(),
3174                                VAT->getIndexTypeCVRQualifiers(),
3175                                VAT->getBracketsRange());
3176  }
3177
3178  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3179  return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3180                                    DSAT->getSizeModifier(), 0,
3181                                    SourceRange());
3182}
3183
3184/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
3185/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3186/// they point to and return true. If T1 and T2 aren't pointer types
3187/// or pointer-to-member types, or if they are not similar at this
3188/// level, returns false and leaves T1 and T2 unchanged. Top-level
3189/// qualifiers on T1 and T2 are ignored. This function will typically
3190/// be called in a loop that successively "unwraps" pointer and
3191/// pointer-to-member types to compare them at each level.
3192bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3193  const PointerType *T1PtrType = T1->getAs<PointerType>(),
3194                    *T2PtrType = T2->getAs<PointerType>();
3195  if (T1PtrType && T2PtrType) {
3196    T1 = T1PtrType->getPointeeType();
3197    T2 = T2PtrType->getPointeeType();
3198    return true;
3199  }
3200
3201  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3202                          *T2MPType = T2->getAs<MemberPointerType>();
3203  if (T1MPType && T2MPType &&
3204      hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3205                             QualType(T2MPType->getClass(), 0))) {
3206    T1 = T1MPType->getPointeeType();
3207    T2 = T2MPType->getPointeeType();
3208    return true;
3209  }
3210
3211  if (getLangOptions().ObjC1) {
3212    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3213                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
3214    if (T1OPType && T2OPType) {
3215      T1 = T1OPType->getPointeeType();
3216      T2 = T2OPType->getPointeeType();
3217      return true;
3218    }
3219  }
3220
3221  // FIXME: Block pointers, too?
3222
3223  return false;
3224}
3225
3226DeclarationNameInfo
3227ASTContext::getNameForTemplate(TemplateName Name,
3228                               SourceLocation NameLoc) const {
3229  switch (Name.getKind()) {
3230  case TemplateName::QualifiedTemplate:
3231  case TemplateName::Template:
3232    // DNInfo work in progress: CHECKME: what about DNLoc?
3233    return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3234                               NameLoc);
3235
3236  case TemplateName::OverloadedTemplate: {
3237    OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3238    // DNInfo work in progress: CHECKME: what about DNLoc?
3239    return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3240  }
3241
3242  case TemplateName::DependentTemplate: {
3243    DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3244    DeclarationName DName;
3245    if (DTN->isIdentifier()) {
3246      DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3247      return DeclarationNameInfo(DName, NameLoc);
3248    } else {
3249      DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3250      // DNInfo work in progress: FIXME: source locations?
3251      DeclarationNameLoc DNLoc;
3252      DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3253      DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3254      return DeclarationNameInfo(DName, NameLoc, DNLoc);
3255    }
3256  }
3257
3258  case TemplateName::SubstTemplateTemplateParm: {
3259    SubstTemplateTemplateParmStorage *subst
3260      = Name.getAsSubstTemplateTemplateParm();
3261    return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3262                               NameLoc);
3263  }
3264
3265  case TemplateName::SubstTemplateTemplateParmPack: {
3266    SubstTemplateTemplateParmPackStorage *subst
3267      = Name.getAsSubstTemplateTemplateParmPack();
3268    return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3269                               NameLoc);
3270  }
3271  }
3272
3273  llvm_unreachable("bad template name kind!");
3274}
3275
3276TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3277  switch (Name.getKind()) {
3278  case TemplateName::QualifiedTemplate:
3279  case TemplateName::Template: {
3280    TemplateDecl *Template = Name.getAsTemplateDecl();
3281    if (TemplateTemplateParmDecl *TTP
3282          = dyn_cast<TemplateTemplateParmDecl>(Template))
3283      Template = getCanonicalTemplateTemplateParmDecl(TTP);
3284
3285    // The canonical template name is the canonical template declaration.
3286    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3287  }
3288
3289  case TemplateName::OverloadedTemplate:
3290    llvm_unreachable("cannot canonicalize overloaded template");
3291
3292  case TemplateName::DependentTemplate: {
3293    DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3294    assert(DTN && "Non-dependent template names must refer to template decls.");
3295    return DTN->CanonicalTemplateName;
3296  }
3297
3298  case TemplateName::SubstTemplateTemplateParm: {
3299    SubstTemplateTemplateParmStorage *subst
3300      = Name.getAsSubstTemplateTemplateParm();
3301    return getCanonicalTemplateName(subst->getReplacement());
3302  }
3303
3304  case TemplateName::SubstTemplateTemplateParmPack: {
3305    SubstTemplateTemplateParmPackStorage *subst
3306                                  = Name.getAsSubstTemplateTemplateParmPack();
3307    TemplateTemplateParmDecl *canonParameter
3308      = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3309    TemplateArgument canonArgPack
3310      = getCanonicalTemplateArgument(subst->getArgumentPack());
3311    return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3312  }
3313  }
3314
3315  llvm_unreachable("bad template name!");
3316}
3317
3318bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3319  X = getCanonicalTemplateName(X);
3320  Y = getCanonicalTemplateName(Y);
3321  return X.getAsVoidPointer() == Y.getAsVoidPointer();
3322}
3323
3324TemplateArgument
3325ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
3326  switch (Arg.getKind()) {
3327    case TemplateArgument::Null:
3328      return Arg;
3329
3330    case TemplateArgument::Expression:
3331      return Arg;
3332
3333    case TemplateArgument::Declaration:
3334      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
3335
3336    case TemplateArgument::Template:
3337      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
3338
3339    case TemplateArgument::TemplateExpansion:
3340      return TemplateArgument(getCanonicalTemplateName(
3341                                         Arg.getAsTemplateOrTemplatePattern()),
3342                              Arg.getNumTemplateExpansions());
3343
3344    case TemplateArgument::Integral:
3345      return TemplateArgument(*Arg.getAsIntegral(),
3346                              getCanonicalType(Arg.getIntegralType()));
3347
3348    case TemplateArgument::Type:
3349      return TemplateArgument(getCanonicalType(Arg.getAsType()));
3350
3351    case TemplateArgument::Pack: {
3352      if (Arg.pack_size() == 0)
3353        return Arg;
3354
3355      TemplateArgument *CanonArgs
3356        = new (*this) TemplateArgument[Arg.pack_size()];
3357      unsigned Idx = 0;
3358      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
3359                                        AEnd = Arg.pack_end();
3360           A != AEnd; (void)++A, ++Idx)
3361        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
3362
3363      return TemplateArgument(CanonArgs, Arg.pack_size());
3364    }
3365  }
3366
3367  // Silence GCC warning
3368  llvm_unreachable("Unhandled template argument kind");
3369}
3370
3371NestedNameSpecifier *
3372ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
3373  if (!NNS)
3374    return 0;
3375
3376  switch (NNS->getKind()) {
3377  case NestedNameSpecifier::Identifier:
3378    // Canonicalize the prefix but keep the identifier the same.
3379    return NestedNameSpecifier::Create(*this,
3380                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3381                                       NNS->getAsIdentifier());
3382
3383  case NestedNameSpecifier::Namespace:
3384    // A namespace is canonical; build a nested-name-specifier with
3385    // this namespace and no prefix.
3386    return NestedNameSpecifier::Create(*this, 0,
3387                                 NNS->getAsNamespace()->getOriginalNamespace());
3388
3389  case NestedNameSpecifier::NamespaceAlias:
3390    // A namespace is canonical; build a nested-name-specifier with
3391    // this namespace and no prefix.
3392    return NestedNameSpecifier::Create(*this, 0,
3393                                    NNS->getAsNamespaceAlias()->getNamespace()
3394                                                      ->getOriginalNamespace());
3395
3396  case NestedNameSpecifier::TypeSpec:
3397  case NestedNameSpecifier::TypeSpecWithTemplate: {
3398    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
3399
3400    // If we have some kind of dependent-named type (e.g., "typename T::type"),
3401    // break it apart into its prefix and identifier, then reconsititute those
3402    // as the canonical nested-name-specifier. This is required to canonicalize
3403    // a dependent nested-name-specifier involving typedefs of dependent-name
3404    // types, e.g.,
3405    //   typedef typename T::type T1;
3406    //   typedef typename T1::type T2;
3407    if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
3408      NestedNameSpecifier *Prefix
3409        = getCanonicalNestedNameSpecifier(DNT->getQualifier());
3410      return NestedNameSpecifier::Create(*this, Prefix,
3411                           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3412    }
3413
3414    // Do the same thing as above, but with dependent-named specializations.
3415    if (const DependentTemplateSpecializationType *DTST
3416          = T->getAs<DependentTemplateSpecializationType>()) {
3417      NestedNameSpecifier *Prefix
3418        = getCanonicalNestedNameSpecifier(DTST->getQualifier());
3419
3420      T = getDependentTemplateSpecializationType(DTST->getKeyword(),
3421                                                 Prefix, DTST->getIdentifier(),
3422                                                 DTST->getNumArgs(),
3423                                                 DTST->getArgs());
3424      T = getCanonicalType(T);
3425    }
3426
3427    return NestedNameSpecifier::Create(*this, 0, false,
3428                                       const_cast<Type*>(T.getTypePtr()));
3429  }
3430
3431  case NestedNameSpecifier::Global:
3432    // The global specifier is canonical and unique.
3433    return NNS;
3434  }
3435
3436  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
3437}
3438
3439
3440const ArrayType *ASTContext::getAsArrayType(QualType T) const {
3441  // Handle the non-qualified case efficiently.
3442  if (!T.hasLocalQualifiers()) {
3443    // Handle the common positive case fast.
3444    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3445      return AT;
3446  }
3447
3448  // Handle the common negative case fast.
3449  if (!isa<ArrayType>(T.getCanonicalType()))
3450    return 0;
3451
3452  // Apply any qualifiers from the array type to the element type.  This
3453  // implements C99 6.7.3p8: "If the specification of an array type includes
3454  // any type qualifiers, the element type is so qualified, not the array type."
3455
3456  // If we get here, we either have type qualifiers on the type, or we have
3457  // sugar such as a typedef in the way.  If we have type qualifiers on the type
3458  // we must propagate them down into the element type.
3459
3460  SplitQualType split = T.getSplitDesugaredType();
3461  Qualifiers qs = split.Quals;
3462
3463  // If we have a simple case, just return now.
3464  const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
3465  if (ATy == 0 || qs.empty())
3466    return ATy;
3467
3468  // Otherwise, we have an array and we have qualifiers on it.  Push the
3469  // qualifiers into the array element type and return a new array type.
3470  QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
3471
3472  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3473    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3474                                                CAT->getSizeModifier(),
3475                                           CAT->getIndexTypeCVRQualifiers()));
3476  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3477    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3478                                                  IAT->getSizeModifier(),
3479                                           IAT->getIndexTypeCVRQualifiers()));
3480
3481  if (const DependentSizedArrayType *DSAT
3482        = dyn_cast<DependentSizedArrayType>(ATy))
3483    return cast<ArrayType>(
3484                     getDependentSizedArrayType(NewEltTy,
3485                                                DSAT->getSizeExpr(),
3486                                                DSAT->getSizeModifier(),
3487                                              DSAT->getIndexTypeCVRQualifiers(),
3488                                                DSAT->getBracketsRange()));
3489
3490  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
3491  return cast<ArrayType>(getVariableArrayType(NewEltTy,
3492                                              VAT->getSizeExpr(),
3493                                              VAT->getSizeModifier(),
3494                                              VAT->getIndexTypeCVRQualifiers(),
3495                                              VAT->getBracketsRange()));
3496}
3497
3498QualType ASTContext::getAdjustedParameterType(QualType T) {
3499  // C99 6.7.5.3p7:
3500  //   A declaration of a parameter as "array of type" shall be
3501  //   adjusted to "qualified pointer to type", where the type
3502  //   qualifiers (if any) are those specified within the [ and ] of
3503  //   the array type derivation.
3504  if (T->isArrayType())
3505    return getArrayDecayedType(T);
3506
3507  // C99 6.7.5.3p8:
3508  //   A declaration of a parameter as "function returning type"
3509  //   shall be adjusted to "pointer to function returning type", as
3510  //   in 6.3.2.1.
3511  if (T->isFunctionType())
3512    return getPointerType(T);
3513
3514  return T;
3515}
3516
3517QualType ASTContext::getSignatureParameterType(QualType T) {
3518  T = getVariableArrayDecayedType(T);
3519  T = getAdjustedParameterType(T);
3520  return T.getUnqualifiedType();
3521}
3522
3523/// getArrayDecayedType - Return the properly qualified result of decaying the
3524/// specified array type to a pointer.  This operation is non-trivial when
3525/// handling typedefs etc.  The canonical type of "T" must be an array type,
3526/// this returns a pointer to a properly qualified element of the array.
3527///
3528/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
3529QualType ASTContext::getArrayDecayedType(QualType Ty) const {
3530  // Get the element type with 'getAsArrayType' so that we don't lose any
3531  // typedefs in the element type of the array.  This also handles propagation
3532  // of type qualifiers from the array type into the element type if present
3533  // (C99 6.7.3p8).
3534  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3535  assert(PrettyArrayType && "Not an array type!");
3536
3537  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
3538
3539  // int x[restrict 4] ->  int *restrict
3540  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
3541}
3542
3543QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3544  return getBaseElementType(array->getElementType());
3545}
3546
3547QualType ASTContext::getBaseElementType(QualType type) const {
3548  Qualifiers qs;
3549  while (true) {
3550    SplitQualType split = type.getSplitDesugaredType();
3551    const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
3552    if (!array) break;
3553
3554    type = array->getElementType();
3555    qs.addConsistentQualifiers(split.Quals);
3556  }
3557
3558  return getQualifiedType(type, qs);
3559}
3560
3561/// getConstantArrayElementCount - Returns number of constant array elements.
3562uint64_t
3563ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
3564  uint64_t ElementCount = 1;
3565  do {
3566    ElementCount *= CA->getSize().getZExtValue();
3567    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3568  } while (CA);
3569  return ElementCount;
3570}
3571
3572/// getFloatingRank - Return a relative rank for floating point types.
3573/// This routine will assert if passed a built-in type that isn't a float.
3574static FloatingRank getFloatingRank(QualType T) {
3575  if (const ComplexType *CT = T->getAs<ComplexType>())
3576    return getFloatingRank(CT->getElementType());
3577
3578  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3579  switch (T->getAs<BuiltinType>()->getKind()) {
3580  default: llvm_unreachable("getFloatingRank(): not a floating type");
3581  case BuiltinType::Half:       return HalfRank;
3582  case BuiltinType::Float:      return FloatRank;
3583  case BuiltinType::Double:     return DoubleRank;
3584  case BuiltinType::LongDouble: return LongDoubleRank;
3585  }
3586}
3587
3588/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3589/// point or a complex type (based on typeDomain/typeSize).
3590/// 'typeDomain' is a real floating point or complex type.
3591/// 'typeSize' is a real floating point or complex type.
3592QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3593                                                       QualType Domain) const {
3594  FloatingRank EltRank = getFloatingRank(Size);
3595  if (Domain->isComplexType()) {
3596    switch (EltRank) {
3597    case HalfRank: llvm_unreachable("Complex half is not supported");
3598    case FloatRank:      return FloatComplexTy;
3599    case DoubleRank:     return DoubleComplexTy;
3600    case LongDoubleRank: return LongDoubleComplexTy;
3601    }
3602  }
3603
3604  assert(Domain->isRealFloatingType() && "Unknown domain!");
3605  switch (EltRank) {
3606  case HalfRank: llvm_unreachable("Half ranks are not valid here");
3607  case FloatRank:      return FloatTy;
3608  case DoubleRank:     return DoubleTy;
3609  case LongDoubleRank: return LongDoubleTy;
3610  }
3611  llvm_unreachable("getFloatingRank(): illegal value for rank");
3612}
3613
3614/// getFloatingTypeOrder - Compare the rank of the two specified floating
3615/// point types, ignoring the domain of the type (i.e. 'double' ==
3616/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3617/// LHS < RHS, return -1.
3618int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
3619  FloatingRank LHSR = getFloatingRank(LHS);
3620  FloatingRank RHSR = getFloatingRank(RHS);
3621
3622  if (LHSR == RHSR)
3623    return 0;
3624  if (LHSR > RHSR)
3625    return 1;
3626  return -1;
3627}
3628
3629/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3630/// routine will assert if passed a built-in type that isn't an integer or enum,
3631/// or if it is not canonicalized.
3632unsigned ASTContext::getIntegerRank(const Type *T) const {
3633  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
3634
3635  switch (cast<BuiltinType>(T)->getKind()) {
3636  default: llvm_unreachable("getIntegerRank(): not a built-in integer");
3637  case BuiltinType::Bool:
3638    return 1 + (getIntWidth(BoolTy) << 3);
3639  case BuiltinType::Char_S:
3640  case BuiltinType::Char_U:
3641  case BuiltinType::SChar:
3642  case BuiltinType::UChar:
3643    return 2 + (getIntWidth(CharTy) << 3);
3644  case BuiltinType::Short:
3645  case BuiltinType::UShort:
3646    return 3 + (getIntWidth(ShortTy) << 3);
3647  case BuiltinType::Int:
3648  case BuiltinType::UInt:
3649    return 4 + (getIntWidth(IntTy) << 3);
3650  case BuiltinType::Long:
3651  case BuiltinType::ULong:
3652    return 5 + (getIntWidth(LongTy) << 3);
3653  case BuiltinType::LongLong:
3654  case BuiltinType::ULongLong:
3655    return 6 + (getIntWidth(LongLongTy) << 3);
3656  case BuiltinType::Int128:
3657  case BuiltinType::UInt128:
3658    return 7 + (getIntWidth(Int128Ty) << 3);
3659  }
3660}
3661
3662/// \brief Whether this is a promotable bitfield reference according
3663/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3664///
3665/// \returns the type this bit-field will promote to, or NULL if no
3666/// promotion occurs.
3667QualType ASTContext::isPromotableBitField(Expr *E) const {
3668  if (E->isTypeDependent() || E->isValueDependent())
3669    return QualType();
3670
3671  FieldDecl *Field = E->getBitField();
3672  if (!Field)
3673    return QualType();
3674
3675  QualType FT = Field->getType();
3676
3677  uint64_t BitWidth = Field->getBitWidthValue(*this);
3678  uint64_t IntSize = getTypeSize(IntTy);
3679  // GCC extension compatibility: if the bit-field size is less than or equal
3680  // to the size of int, it gets promoted no matter what its type is.
3681  // For instance, unsigned long bf : 4 gets promoted to signed int.
3682  if (BitWidth < IntSize)
3683    return IntTy;
3684
3685  if (BitWidth == IntSize)
3686    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3687
3688  // Types bigger than int are not subject to promotions, and therefore act
3689  // like the base type.
3690  // FIXME: This doesn't quite match what gcc does, but what gcc does here
3691  // is ridiculous.
3692  return QualType();
3693}
3694
3695/// getPromotedIntegerType - Returns the type that Promotable will
3696/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3697/// integer type.
3698QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
3699  assert(!Promotable.isNull());
3700  assert(Promotable->isPromotableIntegerType());
3701  if (const EnumType *ET = Promotable->getAs<EnumType>())
3702    return ET->getDecl()->getPromotionType();
3703
3704  if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3705    // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3706    // (3.9.1) can be converted to a prvalue of the first of the following
3707    // types that can represent all the values of its underlying type:
3708    // int, unsigned int, long int, unsigned long int, long long int, or
3709    // unsigned long long int [...]
3710    // FIXME: Is there some better way to compute this?
3711    if (BT->getKind() == BuiltinType::WChar_S ||
3712        BT->getKind() == BuiltinType::WChar_U ||
3713        BT->getKind() == BuiltinType::Char16 ||
3714        BT->getKind() == BuiltinType::Char32) {
3715      bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3716      uint64_t FromSize = getTypeSize(BT);
3717      QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3718                                  LongLongTy, UnsignedLongLongTy };
3719      for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3720        uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3721        if (FromSize < ToSize ||
3722            (FromSize == ToSize &&
3723             FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3724          return PromoteTypes[Idx];
3725      }
3726      llvm_unreachable("char type should fit into long long");
3727    }
3728  }
3729
3730  // At this point, we should have a signed or unsigned integer type.
3731  if (Promotable->isSignedIntegerType())
3732    return IntTy;
3733  uint64_t PromotableSize = getTypeSize(Promotable);
3734  uint64_t IntSize = getTypeSize(IntTy);
3735  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3736  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3737}
3738
3739/// \brief Recurses in pointer/array types until it finds an objc retainable
3740/// type and returns its ownership.
3741Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3742  while (!T.isNull()) {
3743    if (T.getObjCLifetime() != Qualifiers::OCL_None)
3744      return T.getObjCLifetime();
3745    if (T->isArrayType())
3746      T = getBaseElementType(T);
3747    else if (const PointerType *PT = T->getAs<PointerType>())
3748      T = PT->getPointeeType();
3749    else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3750      T = RT->getPointeeType();
3751    else
3752      break;
3753  }
3754
3755  return Qualifiers::OCL_None;
3756}
3757
3758/// getIntegerTypeOrder - Returns the highest ranked integer type:
3759/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3760/// LHS < RHS, return -1.
3761int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
3762  const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3763  const Type *RHSC = getCanonicalType(RHS).getTypePtr();
3764  if (LHSC == RHSC) return 0;
3765
3766  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3767  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3768
3769  unsigned LHSRank = getIntegerRank(LHSC);
3770  unsigned RHSRank = getIntegerRank(RHSC);
3771
3772  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
3773    if (LHSRank == RHSRank) return 0;
3774    return LHSRank > RHSRank ? 1 : -1;
3775  }
3776
3777  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3778  if (LHSUnsigned) {
3779    // If the unsigned [LHS] type is larger, return it.
3780    if (LHSRank >= RHSRank)
3781      return 1;
3782
3783    // If the signed type can represent all values of the unsigned type, it
3784    // wins.  Because we are dealing with 2's complement and types that are
3785    // powers of two larger than each other, this is always safe.
3786    return -1;
3787  }
3788
3789  // If the unsigned [RHS] type is larger, return it.
3790  if (RHSRank >= LHSRank)
3791    return -1;
3792
3793  // If the signed type can represent all values of the unsigned type, it
3794  // wins.  Because we are dealing with 2's complement and types that are
3795  // powers of two larger than each other, this is always safe.
3796  return 1;
3797}
3798
3799static RecordDecl *
3800CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3801                 DeclContext *DC, IdentifierInfo *Id) {
3802  SourceLocation Loc;
3803  if (Ctx.getLangOptions().CPlusPlus)
3804    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3805  else
3806    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3807}
3808
3809// getCFConstantStringType - Return the type used for constant CFStrings.
3810QualType ASTContext::getCFConstantStringType() const {
3811  if (!CFConstantStringTypeDecl) {
3812    CFConstantStringTypeDecl =
3813      CreateRecordDecl(*this, TTK_Struct, TUDecl,
3814                       &Idents.get("NSConstantString"));
3815    CFConstantStringTypeDecl->startDefinition();
3816
3817    QualType FieldTypes[4];
3818
3819    // const int *isa;
3820    FieldTypes[0] = getPointerType(IntTy.withConst());
3821    // int flags;
3822    FieldTypes[1] = IntTy;
3823    // const char *str;
3824    FieldTypes[2] = getPointerType(CharTy.withConst());
3825    // long length;
3826    FieldTypes[3] = LongTy;
3827
3828    // Create fields
3829    for (unsigned i = 0; i < 4; ++i) {
3830      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3831                                           SourceLocation(),
3832                                           SourceLocation(), 0,
3833                                           FieldTypes[i], /*TInfo=*/0,
3834                                           /*BitWidth=*/0,
3835                                           /*Mutable=*/false,
3836                                           /*HasInit=*/false);
3837      Field->setAccess(AS_public);
3838      CFConstantStringTypeDecl->addDecl(Field);
3839    }
3840
3841    CFConstantStringTypeDecl->completeDefinition();
3842  }
3843
3844  return getTagDeclType(CFConstantStringTypeDecl);
3845}
3846
3847void ASTContext::setCFConstantStringType(QualType T) {
3848  const RecordType *Rec = T->getAs<RecordType>();
3849  assert(Rec && "Invalid CFConstantStringType");
3850  CFConstantStringTypeDecl = Rec->getDecl();
3851}
3852
3853QualType ASTContext::getBlockDescriptorType() const {
3854  if (BlockDescriptorType)
3855    return getTagDeclType(BlockDescriptorType);
3856
3857  RecordDecl *T;
3858  // FIXME: Needs the FlagAppleBlock bit.
3859  T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3860                       &Idents.get("__block_descriptor"));
3861  T->startDefinition();
3862
3863  QualType FieldTypes[] = {
3864    UnsignedLongTy,
3865    UnsignedLongTy,
3866  };
3867
3868  const char *FieldNames[] = {
3869    "reserved",
3870    "Size"
3871  };
3872
3873  for (size_t i = 0; i < 2; ++i) {
3874    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3875                                         SourceLocation(),
3876                                         &Idents.get(FieldNames[i]),
3877                                         FieldTypes[i], /*TInfo=*/0,
3878                                         /*BitWidth=*/0,
3879                                         /*Mutable=*/false,
3880                                         /*HasInit=*/false);
3881    Field->setAccess(AS_public);
3882    T->addDecl(Field);
3883  }
3884
3885  T->completeDefinition();
3886
3887  BlockDescriptorType = T;
3888
3889  return getTagDeclType(BlockDescriptorType);
3890}
3891
3892QualType ASTContext::getBlockDescriptorExtendedType() const {
3893  if (BlockDescriptorExtendedType)
3894    return getTagDeclType(BlockDescriptorExtendedType);
3895
3896  RecordDecl *T;
3897  // FIXME: Needs the FlagAppleBlock bit.
3898  T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3899                       &Idents.get("__block_descriptor_withcopydispose"));
3900  T->startDefinition();
3901
3902  QualType FieldTypes[] = {
3903    UnsignedLongTy,
3904    UnsignedLongTy,
3905    getPointerType(VoidPtrTy),
3906    getPointerType(VoidPtrTy)
3907  };
3908
3909  const char *FieldNames[] = {
3910    "reserved",
3911    "Size",
3912    "CopyFuncPtr",
3913    "DestroyFuncPtr"
3914  };
3915
3916  for (size_t i = 0; i < 4; ++i) {
3917    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3918                                         SourceLocation(),
3919                                         &Idents.get(FieldNames[i]),
3920                                         FieldTypes[i], /*TInfo=*/0,
3921                                         /*BitWidth=*/0,
3922                                         /*Mutable=*/false,
3923                                         /*HasInit=*/false);
3924    Field->setAccess(AS_public);
3925    T->addDecl(Field);
3926  }
3927
3928  T->completeDefinition();
3929
3930  BlockDescriptorExtendedType = T;
3931
3932  return getTagDeclType(BlockDescriptorExtendedType);
3933}
3934
3935bool ASTContext::BlockRequiresCopying(QualType Ty) const {
3936  if (Ty->isObjCRetainableType())
3937    return true;
3938  if (getLangOptions().CPlusPlus) {
3939    if (const RecordType *RT = Ty->getAs<RecordType>()) {
3940      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3941      return RD->hasConstCopyConstructor();
3942
3943    }
3944  }
3945  return false;
3946}
3947
3948QualType
3949ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
3950  //  type = struct __Block_byref_1_X {
3951  //    void *__isa;
3952  //    struct __Block_byref_1_X *__forwarding;
3953  //    unsigned int __flags;
3954  //    unsigned int __size;
3955  //    void *__copy_helper;            // as needed
3956  //    void *__destroy_help            // as needed
3957  //    int X;
3958  //  } *
3959
3960  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3961
3962  // FIXME: Move up
3963  SmallString<36> Name;
3964  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3965                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3966  RecordDecl *T;
3967  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
3968  T->startDefinition();
3969  QualType Int32Ty = IntTy;
3970  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3971  QualType FieldTypes[] = {
3972    getPointerType(VoidPtrTy),
3973    getPointerType(getTagDeclType(T)),
3974    Int32Ty,
3975    Int32Ty,
3976    getPointerType(VoidPtrTy),
3977    getPointerType(VoidPtrTy),
3978    Ty
3979  };
3980
3981  StringRef FieldNames[] = {
3982    "__isa",
3983    "__forwarding",
3984    "__flags",
3985    "__size",
3986    "__copy_helper",
3987    "__destroy_helper",
3988    DeclName,
3989  };
3990
3991  for (size_t i = 0; i < 7; ++i) {
3992    if (!HasCopyAndDispose && i >=4 && i <= 5)
3993      continue;
3994    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3995                                         SourceLocation(),
3996                                         &Idents.get(FieldNames[i]),
3997                                         FieldTypes[i], /*TInfo=*/0,
3998                                         /*BitWidth=*/0, /*Mutable=*/false,
3999                                         /*HasInit=*/false);
4000    Field->setAccess(AS_public);
4001    T->addDecl(Field);
4002  }
4003
4004  T->completeDefinition();
4005
4006  return getPointerType(getTagDeclType(T));
4007}
4008
4009TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4010  if (!ObjCInstanceTypeDecl)
4011    ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4012                                               getTranslationUnitDecl(),
4013                                               SourceLocation(),
4014                                               SourceLocation(),
4015                                               &Idents.get("instancetype"),
4016                                     getTrivialTypeSourceInfo(getObjCIdType()));
4017  return ObjCInstanceTypeDecl;
4018}
4019
4020// This returns true if a type has been typedefed to BOOL:
4021// typedef <type> BOOL;
4022static bool isTypeTypedefedAsBOOL(QualType T) {
4023  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4024    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4025      return II->isStr("BOOL");
4026
4027  return false;
4028}
4029
4030/// getObjCEncodingTypeSize returns size of type for objective-c encoding
4031/// purpose.
4032CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4033  if (!type->isIncompleteArrayType() && type->isIncompleteType())
4034    return CharUnits::Zero();
4035
4036  CharUnits sz = getTypeSizeInChars(type);
4037
4038  // Make all integer and enum types at least as large as an int
4039  if (sz.isPositive() && type->isIntegralOrEnumerationType())
4040    sz = std::max(sz, getTypeSizeInChars(IntTy));
4041  // Treat arrays as pointers, since that's how they're passed in.
4042  else if (type->isArrayType())
4043    sz = getTypeSizeInChars(VoidPtrTy);
4044  return sz;
4045}
4046
4047static inline
4048std::string charUnitsToString(const CharUnits &CU) {
4049  return llvm::itostr(CU.getQuantity());
4050}
4051
4052/// getObjCEncodingForBlock - Return the encoded type for this block
4053/// declaration.
4054std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4055  std::string S;
4056
4057  const BlockDecl *Decl = Expr->getBlockDecl();
4058  QualType BlockTy =
4059      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4060  // Encode result type.
4061  getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
4062  // Compute size of all parameters.
4063  // Start with computing size of a pointer in number of bytes.
4064  // FIXME: There might(should) be a better way of doing this computation!
4065  SourceLocation Loc;
4066  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4067  CharUnits ParmOffset = PtrSize;
4068  for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
4069       E = Decl->param_end(); PI != E; ++PI) {
4070    QualType PType = (*PI)->getType();
4071    CharUnits sz = getObjCEncodingTypeSize(PType);
4072    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4073    ParmOffset += sz;
4074  }
4075  // Size of the argument frame
4076  S += charUnitsToString(ParmOffset);
4077  // Block pointer and offset.
4078  S += "@?0";
4079
4080  // Argument types.
4081  ParmOffset = PtrSize;
4082  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4083       Decl->param_end(); PI != E; ++PI) {
4084    ParmVarDecl *PVDecl = *PI;
4085    QualType PType = PVDecl->getOriginalType();
4086    if (const ArrayType *AT =
4087          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4088      // Use array's original type only if it has known number of
4089      // elements.
4090      if (!isa<ConstantArrayType>(AT))
4091        PType = PVDecl->getType();
4092    } else if (PType->isFunctionType())
4093      PType = PVDecl->getType();
4094    getObjCEncodingForType(PType, S);
4095    S += charUnitsToString(ParmOffset);
4096    ParmOffset += getObjCEncodingTypeSize(PType);
4097  }
4098
4099  return S;
4100}
4101
4102bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4103                                                std::string& S) {
4104  // Encode result type.
4105  getObjCEncodingForType(Decl->getResultType(), S);
4106  CharUnits ParmOffset;
4107  // Compute size of all parameters.
4108  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4109       E = Decl->param_end(); PI != E; ++PI) {
4110    QualType PType = (*PI)->getType();
4111    CharUnits sz = getObjCEncodingTypeSize(PType);
4112    if (sz.isZero())
4113      return true;
4114
4115    assert (sz.isPositive() &&
4116        "getObjCEncodingForFunctionDecl - Incomplete param type");
4117    ParmOffset += sz;
4118  }
4119  S += charUnitsToString(ParmOffset);
4120  ParmOffset = CharUnits::Zero();
4121
4122  // Argument types.
4123  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4124       E = Decl->param_end(); PI != E; ++PI) {
4125    ParmVarDecl *PVDecl = *PI;
4126    QualType PType = PVDecl->getOriginalType();
4127    if (const ArrayType *AT =
4128          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4129      // Use array's original type only if it has known number of
4130      // elements.
4131      if (!isa<ConstantArrayType>(AT))
4132        PType = PVDecl->getType();
4133    } else if (PType->isFunctionType())
4134      PType = PVDecl->getType();
4135    getObjCEncodingForType(PType, S);
4136    S += charUnitsToString(ParmOffset);
4137    ParmOffset += getObjCEncodingTypeSize(PType);
4138  }
4139
4140  return false;
4141}
4142
4143/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4144/// method parameter or return type. If Extended, include class names and
4145/// block object types.
4146void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4147                                                   QualType T, std::string& S,
4148                                                   bool Extended) const {
4149  // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4150  getObjCEncodingForTypeQualifier(QT, S);
4151  // Encode parameter type.
4152  getObjCEncodingForTypeImpl(T, S, true, true, 0,
4153                             true     /*OutermostType*/,
4154                             false    /*EncodingProperty*/,
4155                             false    /*StructField*/,
4156                             Extended /*EncodeBlockParameters*/,
4157                             Extended /*EncodeClassNames*/);
4158}
4159
4160/// getObjCEncodingForMethodDecl - Return the encoded type for this method
4161/// declaration.
4162bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4163                                              std::string& S,
4164                                              bool Extended) const {
4165  // FIXME: This is not very efficient.
4166  // Encode return type.
4167  getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4168                                    Decl->getResultType(), S, Extended);
4169  // Compute size of all parameters.
4170  // Start with computing size of a pointer in number of bytes.
4171  // FIXME: There might(should) be a better way of doing this computation!
4172  SourceLocation Loc;
4173  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4174  // The first two arguments (self and _cmd) are pointers; account for
4175  // their size.
4176  CharUnits ParmOffset = 2 * PtrSize;
4177  for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4178       E = Decl->sel_param_end(); PI != E; ++PI) {
4179    QualType PType = (*PI)->getType();
4180    CharUnits sz = getObjCEncodingTypeSize(PType);
4181    if (sz.isZero())
4182      return true;
4183
4184    assert (sz.isPositive() &&
4185        "getObjCEncodingForMethodDecl - Incomplete param type");
4186    ParmOffset += sz;
4187  }
4188  S += charUnitsToString(ParmOffset);
4189  S += "@0:";
4190  S += charUnitsToString(PtrSize);
4191
4192  // Argument types.
4193  ParmOffset = 2 * PtrSize;
4194  for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4195       E = Decl->sel_param_end(); PI != E; ++PI) {
4196    const ParmVarDecl *PVDecl = *PI;
4197    QualType PType = PVDecl->getOriginalType();
4198    if (const ArrayType *AT =
4199          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4200      // Use array's original type only if it has known number of
4201      // elements.
4202      if (!isa<ConstantArrayType>(AT))
4203        PType = PVDecl->getType();
4204    } else if (PType->isFunctionType())
4205      PType = PVDecl->getType();
4206    getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4207                                      PType, S, Extended);
4208    S += charUnitsToString(ParmOffset);
4209    ParmOffset += getObjCEncodingTypeSize(PType);
4210  }
4211
4212  return false;
4213}
4214
4215/// getObjCEncodingForPropertyDecl - Return the encoded type for this
4216/// property declaration. If non-NULL, Container must be either an
4217/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4218/// NULL when getting encodings for protocol properties.
4219/// Property attributes are stored as a comma-delimited C string. The simple
4220/// attributes readonly and bycopy are encoded as single characters. The
4221/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4222/// encoded as single characters, followed by an identifier. Property types
4223/// are also encoded as a parametrized attribute. The characters used to encode
4224/// these attributes are defined by the following enumeration:
4225/// @code
4226/// enum PropertyAttributes {
4227/// kPropertyReadOnly = 'R',   // property is read-only.
4228/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
4229/// kPropertyByref = '&',  // property is a reference to the value last assigned
4230/// kPropertyDynamic = 'D',    // property is dynamic
4231/// kPropertyGetter = 'G',     // followed by getter selector name
4232/// kPropertySetter = 'S',     // followed by setter selector name
4233/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
4234/// kPropertyType = 't'              // followed by old-style type encoding.
4235/// kPropertyWeak = 'W'              // 'weak' property
4236/// kPropertyStrong = 'P'            // property GC'able
4237/// kPropertyNonAtomic = 'N'         // property non-atomic
4238/// };
4239/// @endcode
4240void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4241                                                const Decl *Container,
4242                                                std::string& S) const {
4243  // Collect information from the property implementation decl(s).
4244  bool Dynamic = false;
4245  ObjCPropertyImplDecl *SynthesizePID = 0;
4246
4247  // FIXME: Duplicated code due to poor abstraction.
4248  if (Container) {
4249    if (const ObjCCategoryImplDecl *CID =
4250        dyn_cast<ObjCCategoryImplDecl>(Container)) {
4251      for (ObjCCategoryImplDecl::propimpl_iterator
4252             i = CID->propimpl_begin(), e = CID->propimpl_end();
4253           i != e; ++i) {
4254        ObjCPropertyImplDecl *PID = *i;
4255        if (PID->getPropertyDecl() == PD) {
4256          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4257            Dynamic = true;
4258          } else {
4259            SynthesizePID = PID;
4260          }
4261        }
4262      }
4263    } else {
4264      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4265      for (ObjCCategoryImplDecl::propimpl_iterator
4266             i = OID->propimpl_begin(), e = OID->propimpl_end();
4267           i != e; ++i) {
4268        ObjCPropertyImplDecl *PID = *i;
4269        if (PID->getPropertyDecl() == PD) {
4270          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4271            Dynamic = true;
4272          } else {
4273            SynthesizePID = PID;
4274          }
4275        }
4276      }
4277    }
4278  }
4279
4280  // FIXME: This is not very efficient.
4281  S = "T";
4282
4283  // Encode result type.
4284  // GCC has some special rules regarding encoding of properties which
4285  // closely resembles encoding of ivars.
4286  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4287                             true /* outermost type */,
4288                             true /* encoding for property */);
4289
4290  if (PD->isReadOnly()) {
4291    S += ",R";
4292  } else {
4293    switch (PD->getSetterKind()) {
4294    case ObjCPropertyDecl::Assign: break;
4295    case ObjCPropertyDecl::Copy:   S += ",C"; break;
4296    case ObjCPropertyDecl::Retain: S += ",&"; break;
4297    case ObjCPropertyDecl::Weak:   S += ",W"; break;
4298    }
4299  }
4300
4301  // It really isn't clear at all what this means, since properties
4302  // are "dynamic by default".
4303  if (Dynamic)
4304    S += ",D";
4305
4306  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4307    S += ",N";
4308
4309  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4310    S += ",G";
4311    S += PD->getGetterName().getAsString();
4312  }
4313
4314  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4315    S += ",S";
4316    S += PD->getSetterName().getAsString();
4317  }
4318
4319  if (SynthesizePID) {
4320    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4321    S += ",V";
4322    S += OID->getNameAsString();
4323  }
4324
4325  // FIXME: OBJCGC: weak & strong
4326}
4327
4328/// getLegacyIntegralTypeEncoding -
4329/// Another legacy compatibility encoding: 32-bit longs are encoded as
4330/// 'l' or 'L' , but not always.  For typedefs, we need to use
4331/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4332///
4333void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
4334  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
4335    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
4336      if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
4337        PointeeTy = UnsignedIntTy;
4338      else
4339        if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
4340          PointeeTy = IntTy;
4341    }
4342  }
4343}
4344
4345void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
4346                                        const FieldDecl *Field) const {
4347  // We follow the behavior of gcc, expanding structures which are
4348  // directly pointed to, and expanding embedded structures. Note that
4349  // these rules are sufficient to prevent recursive encoding of the
4350  // same type.
4351  getObjCEncodingForTypeImpl(T, S, true, true, Field,
4352                             true /* outermost type */);
4353}
4354
4355static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4356    switch (T->getAs<BuiltinType>()->getKind()) {
4357    default: llvm_unreachable("Unhandled builtin type kind");
4358    case BuiltinType::Void:       return 'v';
4359    case BuiltinType::Bool:       return 'B';
4360    case BuiltinType::Char_U:
4361    case BuiltinType::UChar:      return 'C';
4362    case BuiltinType::UShort:     return 'S';
4363    case BuiltinType::UInt:       return 'I';
4364    case BuiltinType::ULong:
4365        return C->getIntWidth(T) == 32 ? 'L' : 'Q';
4366    case BuiltinType::UInt128:    return 'T';
4367    case BuiltinType::ULongLong:  return 'Q';
4368    case BuiltinType::Char_S:
4369    case BuiltinType::SChar:      return 'c';
4370    case BuiltinType::Short:      return 's';
4371    case BuiltinType::WChar_S:
4372    case BuiltinType::WChar_U:
4373    case BuiltinType::Int:        return 'i';
4374    case BuiltinType::Long:
4375      return C->getIntWidth(T) == 32 ? 'l' : 'q';
4376    case BuiltinType::LongLong:   return 'q';
4377    case BuiltinType::Int128:     return 't';
4378    case BuiltinType::Float:      return 'f';
4379    case BuiltinType::Double:     return 'd';
4380    case BuiltinType::LongDouble: return 'D';
4381    }
4382}
4383
4384static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4385  EnumDecl *Enum = ET->getDecl();
4386
4387  // The encoding of an non-fixed enum type is always 'i', regardless of size.
4388  if (!Enum->isFixed())
4389    return 'i';
4390
4391  // The encoding of a fixed enum type matches its fixed underlying type.
4392  return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4393}
4394
4395static void EncodeBitField(const ASTContext *Ctx, std::string& S,
4396                           QualType T, const FieldDecl *FD) {
4397  assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
4398  S += 'b';
4399  // The NeXT runtime encodes bit fields as b followed by the number of bits.
4400  // The GNU runtime requires more information; bitfields are encoded as b,
4401  // then the offset (in bits) of the first element, then the type of the
4402  // bitfield, then the size in bits.  For example, in this structure:
4403  //
4404  // struct
4405  // {
4406  //    int integer;
4407  //    int flags:2;
4408  // };
4409  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4410  // runtime, but b32i2 for the GNU runtime.  The reason for this extra
4411  // information is not especially sensible, but we're stuck with it for
4412  // compatibility with GCC, although providing it breaks anything that
4413  // actually uses runtime introspection and wants to work on both runtimes...
4414  if (!Ctx->getLangOptions().NeXTRuntime) {
4415    const RecordDecl *RD = FD->getParent();
4416    const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4417    S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
4418    if (const EnumType *ET = T->getAs<EnumType>())
4419      S += ObjCEncodingForEnumType(Ctx, ET);
4420    else
4421      S += ObjCEncodingForPrimitiveKind(Ctx, T);
4422  }
4423  S += llvm::utostr(FD->getBitWidthValue(*Ctx));
4424}
4425
4426// FIXME: Use SmallString for accumulating string.
4427void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4428                                            bool ExpandPointedToStructures,
4429                                            bool ExpandStructures,
4430                                            const FieldDecl *FD,
4431                                            bool OutermostType,
4432                                            bool EncodingProperty,
4433                                            bool StructField,
4434                                            bool EncodeBlockParameters,
4435                                            bool EncodeClassNames) const {
4436  if (T->getAs<BuiltinType>()) {
4437    if (FD && FD->isBitField())
4438      return EncodeBitField(this, S, T, FD);
4439    S += ObjCEncodingForPrimitiveKind(this, T);
4440    return;
4441  }
4442
4443  if (const ComplexType *CT = T->getAs<ComplexType>()) {
4444    S += 'j';
4445    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
4446                               false);
4447    return;
4448  }
4449
4450  // encoding for pointer or r3eference types.
4451  QualType PointeeTy;
4452  if (const PointerType *PT = T->getAs<PointerType>()) {
4453    if (PT->isObjCSelType()) {
4454      S += ':';
4455      return;
4456    }
4457    PointeeTy = PT->getPointeeType();
4458  }
4459  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4460    PointeeTy = RT->getPointeeType();
4461  if (!PointeeTy.isNull()) {
4462    bool isReadOnly = false;
4463    // For historical/compatibility reasons, the read-only qualifier of the
4464    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
4465    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
4466    // Also, do not emit the 'r' for anything but the outermost type!
4467    if (isa<TypedefType>(T.getTypePtr())) {
4468      if (OutermostType && T.isConstQualified()) {
4469        isReadOnly = true;
4470        S += 'r';
4471      }
4472    } else if (OutermostType) {
4473      QualType P = PointeeTy;
4474      while (P->getAs<PointerType>())
4475        P = P->getAs<PointerType>()->getPointeeType();
4476      if (P.isConstQualified()) {
4477        isReadOnly = true;
4478        S += 'r';
4479      }
4480    }
4481    if (isReadOnly) {
4482      // Another legacy compatibility encoding. Some ObjC qualifier and type
4483      // combinations need to be rearranged.
4484      // Rewrite "in const" from "nr" to "rn"
4485      if (StringRef(S).endswith("nr"))
4486        S.replace(S.end()-2, S.end(), "rn");
4487    }
4488
4489    if (PointeeTy->isCharType()) {
4490      // char pointer types should be encoded as '*' unless it is a
4491      // type that has been typedef'd to 'BOOL'.
4492      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
4493        S += '*';
4494        return;
4495      }
4496    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
4497      // GCC binary compat: Need to convert "struct objc_class *" to "#".
4498      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4499        S += '#';
4500        return;
4501      }
4502      // GCC binary compat: Need to convert "struct objc_object *" to "@".
4503      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4504        S += '@';
4505        return;
4506      }
4507      // fall through...
4508    }
4509    S += '^';
4510    getLegacyIntegralTypeEncoding(PointeeTy);
4511
4512    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
4513                               NULL);
4514    return;
4515  }
4516
4517  if (const ArrayType *AT =
4518      // Ignore type qualifiers etc.
4519        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
4520    if (isa<IncompleteArrayType>(AT) && !StructField) {
4521      // Incomplete arrays are encoded as a pointer to the array element.
4522      S += '^';
4523
4524      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4525                                 false, ExpandStructures, FD);
4526    } else {
4527      S += '[';
4528
4529      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4530        if (getTypeSize(CAT->getElementType()) == 0)
4531          S += '0';
4532        else
4533          S += llvm::utostr(CAT->getSize().getZExtValue());
4534      } else {
4535        //Variable length arrays are encoded as a regular array with 0 elements.
4536        assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4537               "Unknown array type!");
4538        S += '0';
4539      }
4540
4541      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4542                                 false, ExpandStructures, FD);
4543      S += ']';
4544    }
4545    return;
4546  }
4547
4548  if (T->getAs<FunctionType>()) {
4549    S += '?';
4550    return;
4551  }
4552
4553  if (const RecordType *RTy = T->getAs<RecordType>()) {
4554    RecordDecl *RDecl = RTy->getDecl();
4555    S += RDecl->isUnion() ? '(' : '{';
4556    // Anonymous structures print as '?'
4557    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4558      S += II->getName();
4559      if (ClassTemplateSpecializationDecl *Spec
4560          = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4561        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4562        std::string TemplateArgsStr
4563          = TemplateSpecializationType::PrintTemplateArgumentList(
4564                                            TemplateArgs.data(),
4565                                            TemplateArgs.size(),
4566                                            (*this).getPrintingPolicy());
4567
4568        S += TemplateArgsStr;
4569      }
4570    } else {
4571      S += '?';
4572    }
4573    if (ExpandStructures) {
4574      S += '=';
4575      if (!RDecl->isUnion()) {
4576        getObjCEncodingForStructureImpl(RDecl, S, FD);
4577      } else {
4578        for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4579                                     FieldEnd = RDecl->field_end();
4580             Field != FieldEnd; ++Field) {
4581          if (FD) {
4582            S += '"';
4583            S += Field->getNameAsString();
4584            S += '"';
4585          }
4586
4587          // Special case bit-fields.
4588          if (Field->isBitField()) {
4589            getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4590                                       (*Field));
4591          } else {
4592            QualType qt = Field->getType();
4593            getLegacyIntegralTypeEncoding(qt);
4594            getObjCEncodingForTypeImpl(qt, S, false, true,
4595                                       FD, /*OutermostType*/false,
4596                                       /*EncodingProperty*/false,
4597                                       /*StructField*/true);
4598          }
4599        }
4600      }
4601    }
4602    S += RDecl->isUnion() ? ')' : '}';
4603    return;
4604  }
4605
4606  if (const EnumType *ET = T->getAs<EnumType>()) {
4607    if (FD && FD->isBitField())
4608      EncodeBitField(this, S, T, FD);
4609    else
4610      S += ObjCEncodingForEnumType(this, ET);
4611    return;
4612  }
4613
4614  if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
4615    S += "@?"; // Unlike a pointer-to-function, which is "^?".
4616    if (EncodeBlockParameters) {
4617      const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4618
4619      S += '<';
4620      // Block return type
4621      getObjCEncodingForTypeImpl(FT->getResultType(), S,
4622                                 ExpandPointedToStructures, ExpandStructures,
4623                                 FD,
4624                                 false /* OutermostType */,
4625                                 EncodingProperty,
4626                                 false /* StructField */,
4627                                 EncodeBlockParameters,
4628                                 EncodeClassNames);
4629      // Block self
4630      S += "@?";
4631      // Block parameters
4632      if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4633        for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4634               E = FPT->arg_type_end(); I && (I != E); ++I) {
4635          getObjCEncodingForTypeImpl(*I, S,
4636                                     ExpandPointedToStructures,
4637                                     ExpandStructures,
4638                                     FD,
4639                                     false /* OutermostType */,
4640                                     EncodingProperty,
4641                                     false /* StructField */,
4642                                     EncodeBlockParameters,
4643                                     EncodeClassNames);
4644        }
4645      }
4646      S += '>';
4647    }
4648    return;
4649  }
4650
4651  // Ignore protocol qualifiers when mangling at this level.
4652  if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4653    T = OT->getBaseType();
4654
4655  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
4656    // @encode(class_name)
4657    ObjCInterfaceDecl *OI = OIT->getDecl();
4658    S += '{';
4659    const IdentifierInfo *II = OI->getIdentifier();
4660    S += II->getName();
4661    S += '=';
4662    SmallVector<const ObjCIvarDecl*, 32> Ivars;
4663    DeepCollectObjCIvars(OI, true, Ivars);
4664    for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4665      const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4666      if (Field->isBitField())
4667        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
4668      else
4669        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
4670    }
4671    S += '}';
4672    return;
4673  }
4674
4675  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
4676    if (OPT->isObjCIdType()) {
4677      S += '@';
4678      return;
4679    }
4680
4681    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4682      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4683      // Since this is a binary compatibility issue, need to consult with runtime
4684      // folks. Fortunately, this is a *very* obsure construct.
4685      S += '#';
4686      return;
4687    }
4688
4689    if (OPT->isObjCQualifiedIdType()) {
4690      getObjCEncodingForTypeImpl(getObjCIdType(), S,
4691                                 ExpandPointedToStructures,
4692                                 ExpandStructures, FD);
4693      if (FD || EncodingProperty || EncodeClassNames) {
4694        // Note that we do extended encoding of protocol qualifer list
4695        // Only when doing ivar or property encoding.
4696        S += '"';
4697        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4698             E = OPT->qual_end(); I != E; ++I) {
4699          S += '<';
4700          S += (*I)->getNameAsString();
4701          S += '>';
4702        }
4703        S += '"';
4704      }
4705      return;
4706    }
4707
4708    QualType PointeeTy = OPT->getPointeeType();
4709    if (!EncodingProperty &&
4710        isa<TypedefType>(PointeeTy.getTypePtr())) {
4711      // Another historical/compatibility reason.
4712      // We encode the underlying type which comes out as
4713      // {...};
4714      S += '^';
4715      getObjCEncodingForTypeImpl(PointeeTy, S,
4716                                 false, ExpandPointedToStructures,
4717                                 NULL);
4718      return;
4719    }
4720
4721    S += '@';
4722    if (OPT->getInterfaceDecl() &&
4723        (FD || EncodingProperty || EncodeClassNames)) {
4724      S += '"';
4725      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
4726      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4727           E = OPT->qual_end(); I != E; ++I) {
4728        S += '<';
4729        S += (*I)->getNameAsString();
4730        S += '>';
4731      }
4732      S += '"';
4733    }
4734    return;
4735  }
4736
4737  // gcc just blithely ignores member pointers.
4738  // TODO: maybe there should be a mangling for these
4739  if (T->getAs<MemberPointerType>())
4740    return;
4741
4742  if (T->isVectorType()) {
4743    // This matches gcc's encoding, even though technically it is
4744    // insufficient.
4745    // FIXME. We should do a better job than gcc.
4746    return;
4747  }
4748
4749  llvm_unreachable("@encode for type not implemented!");
4750}
4751
4752void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4753                                                 std::string &S,
4754                                                 const FieldDecl *FD,
4755                                                 bool includeVBases) const {
4756  assert(RDecl && "Expected non-null RecordDecl");
4757  assert(!RDecl->isUnion() && "Should not be called for unions");
4758  if (!RDecl->getDefinition())
4759    return;
4760
4761  CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4762  std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4763  const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4764
4765  if (CXXRec) {
4766    for (CXXRecordDecl::base_class_iterator
4767           BI = CXXRec->bases_begin(),
4768           BE = CXXRec->bases_end(); BI != BE; ++BI) {
4769      if (!BI->isVirtual()) {
4770        CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4771        if (base->isEmpty())
4772          continue;
4773        uint64_t offs = layout.getBaseClassOffsetInBits(base);
4774        FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4775                                  std::make_pair(offs, base));
4776      }
4777    }
4778  }
4779
4780  unsigned i = 0;
4781  for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4782                               FieldEnd = RDecl->field_end();
4783       Field != FieldEnd; ++Field, ++i) {
4784    uint64_t offs = layout.getFieldOffset(i);
4785    FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4786                              std::make_pair(offs, *Field));
4787  }
4788
4789  if (CXXRec && includeVBases) {
4790    for (CXXRecordDecl::base_class_iterator
4791           BI = CXXRec->vbases_begin(),
4792           BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4793      CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4794      if (base->isEmpty())
4795        continue;
4796      uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4797      if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4798        FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4799                                  std::make_pair(offs, base));
4800    }
4801  }
4802
4803  CharUnits size;
4804  if (CXXRec) {
4805    size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4806  } else {
4807    size = layout.getSize();
4808  }
4809
4810  uint64_t CurOffs = 0;
4811  std::multimap<uint64_t, NamedDecl *>::iterator
4812    CurLayObj = FieldOrBaseOffsets.begin();
4813
4814  if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4815      (CurLayObj == FieldOrBaseOffsets.end() &&
4816         CXXRec && CXXRec->isDynamicClass())) {
4817    assert(CXXRec && CXXRec->isDynamicClass() &&
4818           "Offset 0 was empty but no VTable ?");
4819    if (FD) {
4820      S += "\"_vptr$";
4821      std::string recname = CXXRec->getNameAsString();
4822      if (recname.empty()) recname = "?";
4823      S += recname;
4824      S += '"';
4825    }
4826    S += "^^?";
4827    CurOffs += getTypeSize(VoidPtrTy);
4828  }
4829
4830  if (!RDecl->hasFlexibleArrayMember()) {
4831    // Mark the end of the structure.
4832    uint64_t offs = toBits(size);
4833    FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4834                              std::make_pair(offs, (NamedDecl*)0));
4835  }
4836
4837  for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4838    assert(CurOffs <= CurLayObj->first);
4839
4840    if (CurOffs < CurLayObj->first) {
4841      uint64_t padding = CurLayObj->first - CurOffs;
4842      // FIXME: There doesn't seem to be a way to indicate in the encoding that
4843      // packing/alignment of members is different that normal, in which case
4844      // the encoding will be out-of-sync with the real layout.
4845      // If the runtime switches to just consider the size of types without
4846      // taking into account alignment, we could make padding explicit in the
4847      // encoding (e.g. using arrays of chars). The encoding strings would be
4848      // longer then though.
4849      CurOffs += padding;
4850    }
4851
4852    NamedDecl *dcl = CurLayObj->second;
4853    if (dcl == 0)
4854      break; // reached end of structure.
4855
4856    if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4857      // We expand the bases without their virtual bases since those are going
4858      // in the initial structure. Note that this differs from gcc which
4859      // expands virtual bases each time one is encountered in the hierarchy,
4860      // making the encoding type bigger than it really is.
4861      getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
4862      assert(!base->isEmpty());
4863      CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
4864    } else {
4865      FieldDecl *field = cast<FieldDecl>(dcl);
4866      if (FD) {
4867        S += '"';
4868        S += field->getNameAsString();
4869        S += '"';
4870      }
4871
4872      if (field->isBitField()) {
4873        EncodeBitField(this, S, field->getType(), field);
4874        CurOffs += field->getBitWidthValue(*this);
4875      } else {
4876        QualType qt = field->getType();
4877        getLegacyIntegralTypeEncoding(qt);
4878        getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4879                                   /*OutermostType*/false,
4880                                   /*EncodingProperty*/false,
4881                                   /*StructField*/true);
4882        CurOffs += getTypeSize(field->getType());
4883      }
4884    }
4885  }
4886}
4887
4888void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
4889                                                 std::string& S) const {
4890  if (QT & Decl::OBJC_TQ_In)
4891    S += 'n';
4892  if (QT & Decl::OBJC_TQ_Inout)
4893    S += 'N';
4894  if (QT & Decl::OBJC_TQ_Out)
4895    S += 'o';
4896  if (QT & Decl::OBJC_TQ_Bycopy)
4897    S += 'O';
4898  if (QT & Decl::OBJC_TQ_Byref)
4899    S += 'R';
4900  if (QT & Decl::OBJC_TQ_Oneway)
4901    S += 'V';
4902}
4903
4904void ASTContext::setBuiltinVaListType(QualType T) {
4905  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
4906
4907  BuiltinVaListType = T;
4908}
4909
4910TypedefDecl *ASTContext::getObjCIdDecl() const {
4911  if (!ObjCIdDecl) {
4912    QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4913    T = getObjCObjectPointerType(T);
4914    TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4915    ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4916                                     getTranslationUnitDecl(),
4917                                     SourceLocation(), SourceLocation(),
4918                                     &Idents.get("id"), IdInfo);
4919  }
4920
4921  return ObjCIdDecl;
4922}
4923
4924TypedefDecl *ASTContext::getObjCSelDecl() const {
4925  if (!ObjCSelDecl) {
4926    QualType SelT = getPointerType(ObjCBuiltinSelTy);
4927    TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4928    ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4929                                      getTranslationUnitDecl(),
4930                                      SourceLocation(), SourceLocation(),
4931                                      &Idents.get("SEL"), SelInfo);
4932  }
4933  return ObjCSelDecl;
4934}
4935
4936TypedefDecl *ASTContext::getObjCClassDecl() const {
4937  if (!ObjCClassDecl) {
4938    QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4939    T = getObjCObjectPointerType(T);
4940    TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4941    ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4942                                        getTranslationUnitDecl(),
4943                                        SourceLocation(), SourceLocation(),
4944                                        &Idents.get("Class"), ClassInfo);
4945  }
4946
4947  return ObjCClassDecl;
4948}
4949
4950ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4951  if (!ObjCProtocolClassDecl) {
4952    ObjCProtocolClassDecl
4953      = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4954                                  SourceLocation(),
4955                                  &Idents.get("Protocol"),
4956                                  /*PrevDecl=*/0,
4957                                  SourceLocation(), true);
4958  }
4959
4960  return ObjCProtocolClassDecl;
4961}
4962
4963void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
4964  assert(ObjCConstantStringType.isNull() &&
4965         "'NSConstantString' type already set!");
4966
4967  ObjCConstantStringType = getObjCInterfaceType(Decl);
4968}
4969
4970/// \brief Retrieve the template name that corresponds to a non-empty
4971/// lookup.
4972TemplateName
4973ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4974                                      UnresolvedSetIterator End) const {
4975  unsigned size = End - Begin;
4976  assert(size > 1 && "set is not overloaded!");
4977
4978  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4979                          size * sizeof(FunctionTemplateDecl*));
4980  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4981
4982  NamedDecl **Storage = OT->getStorage();
4983  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
4984    NamedDecl *D = *I;
4985    assert(isa<FunctionTemplateDecl>(D) ||
4986           (isa<UsingShadowDecl>(D) &&
4987            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4988    *Storage++ = D;
4989  }
4990
4991  return TemplateName(OT);
4992}
4993
4994/// \brief Retrieve the template name that represents a qualified
4995/// template name such as \c std::vector.
4996TemplateName
4997ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4998                                     bool TemplateKeyword,
4999                                     TemplateDecl *Template) const {
5000  assert(NNS && "Missing nested-name-specifier in qualified template name");
5001
5002  // FIXME: Canonicalization?
5003  llvm::FoldingSetNodeID ID;
5004  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5005
5006  void *InsertPos = 0;
5007  QualifiedTemplateName *QTN =
5008    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5009  if (!QTN) {
5010    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5011    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5012  }
5013
5014  return TemplateName(QTN);
5015}
5016
5017/// \brief Retrieve the template name that represents a dependent
5018/// template name such as \c MetaFun::template apply.
5019TemplateName
5020ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5021                                     const IdentifierInfo *Name) const {
5022  assert((!NNS || NNS->isDependent()) &&
5023         "Nested name specifier must be dependent");
5024
5025  llvm::FoldingSetNodeID ID;
5026  DependentTemplateName::Profile(ID, NNS, Name);
5027
5028  void *InsertPos = 0;
5029  DependentTemplateName *QTN =
5030    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5031
5032  if (QTN)
5033    return TemplateName(QTN);
5034
5035  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5036  if (CanonNNS == NNS) {
5037    QTN = new (*this,4) DependentTemplateName(NNS, Name);
5038  } else {
5039    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5040    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
5041    DependentTemplateName *CheckQTN =
5042      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5043    assert(!CheckQTN && "Dependent type name canonicalization broken");
5044    (void)CheckQTN;
5045  }
5046
5047  DependentTemplateNames.InsertNode(QTN, InsertPos);
5048  return TemplateName(QTN);
5049}
5050
5051/// \brief Retrieve the template name that represents a dependent
5052/// template name such as \c MetaFun::template operator+.
5053TemplateName
5054ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5055                                     OverloadedOperatorKind Operator) const {
5056  assert((!NNS || NNS->isDependent()) &&
5057         "Nested name specifier must be dependent");
5058
5059  llvm::FoldingSetNodeID ID;
5060  DependentTemplateName::Profile(ID, NNS, Operator);
5061
5062  void *InsertPos = 0;
5063  DependentTemplateName *QTN
5064    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5065
5066  if (QTN)
5067    return TemplateName(QTN);
5068
5069  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5070  if (CanonNNS == NNS) {
5071    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5072  } else {
5073    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5074    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
5075
5076    DependentTemplateName *CheckQTN
5077      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5078    assert(!CheckQTN && "Dependent template name canonicalization broken");
5079    (void)CheckQTN;
5080  }
5081
5082  DependentTemplateNames.InsertNode(QTN, InsertPos);
5083  return TemplateName(QTN);
5084}
5085
5086TemplateName
5087ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5088                                         TemplateName replacement) const {
5089  llvm::FoldingSetNodeID ID;
5090  SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5091
5092  void *insertPos = 0;
5093  SubstTemplateTemplateParmStorage *subst
5094    = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5095
5096  if (!subst) {
5097    subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5098    SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5099  }
5100
5101  return TemplateName(subst);
5102}
5103
5104TemplateName
5105ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5106                                       const TemplateArgument &ArgPack) const {
5107  ASTContext &Self = const_cast<ASTContext &>(*this);
5108  llvm::FoldingSetNodeID ID;
5109  SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5110
5111  void *InsertPos = 0;
5112  SubstTemplateTemplateParmPackStorage *Subst
5113    = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5114
5115  if (!Subst) {
5116    Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
5117                                                           ArgPack.pack_size(),
5118                                                         ArgPack.pack_begin());
5119    SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5120  }
5121
5122  return TemplateName(Subst);
5123}
5124
5125/// getFromTargetType - Given one of the integer types provided by
5126/// TargetInfo, produce the corresponding type. The unsigned @p Type
5127/// is actually a value of type @c TargetInfo::IntType.
5128CanQualType ASTContext::getFromTargetType(unsigned Type) const {
5129  switch (Type) {
5130  case TargetInfo::NoInt: return CanQualType();
5131  case TargetInfo::SignedShort: return ShortTy;
5132  case TargetInfo::UnsignedShort: return UnsignedShortTy;
5133  case TargetInfo::SignedInt: return IntTy;
5134  case TargetInfo::UnsignedInt: return UnsignedIntTy;
5135  case TargetInfo::SignedLong: return LongTy;
5136  case TargetInfo::UnsignedLong: return UnsignedLongTy;
5137  case TargetInfo::SignedLongLong: return LongLongTy;
5138  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5139  }
5140
5141  llvm_unreachable("Unhandled TargetInfo::IntType value");
5142}
5143
5144//===----------------------------------------------------------------------===//
5145//                        Type Predicates.
5146//===----------------------------------------------------------------------===//
5147
5148/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5149/// garbage collection attribute.
5150///
5151Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
5152  if (getLangOptions().getGC() == LangOptions::NonGC)
5153    return Qualifiers::GCNone;
5154
5155  assert(getLangOptions().ObjC1);
5156  Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5157
5158  // Default behaviour under objective-C's gc is for ObjC pointers
5159  // (or pointers to them) be treated as though they were declared
5160  // as __strong.
5161  if (GCAttrs == Qualifiers::GCNone) {
5162    if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5163      return Qualifiers::Strong;
5164    else if (Ty->isPointerType())
5165      return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5166  } else {
5167    // It's not valid to set GC attributes on anything that isn't a
5168    // pointer.
5169#ifndef NDEBUG
5170    QualType CT = Ty->getCanonicalTypeInternal();
5171    while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5172      CT = AT->getElementType();
5173    assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5174#endif
5175  }
5176  return GCAttrs;
5177}
5178
5179//===----------------------------------------------------------------------===//
5180//                        Type Compatibility Testing
5181//===----------------------------------------------------------------------===//
5182
5183/// areCompatVectorTypes - Return true if the two specified vector types are
5184/// compatible.
5185static bool areCompatVectorTypes(const VectorType *LHS,
5186                                 const VectorType *RHS) {
5187  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
5188  return LHS->getElementType() == RHS->getElementType() &&
5189         LHS->getNumElements() == RHS->getNumElements();
5190}
5191
5192bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5193                                          QualType SecondVec) {
5194  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5195  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5196
5197  if (hasSameUnqualifiedType(FirstVec, SecondVec))
5198    return true;
5199
5200  // Treat Neon vector types and most AltiVec vector types as if they are the
5201  // equivalent GCC vector types.
5202  const VectorType *First = FirstVec->getAs<VectorType>();
5203  const VectorType *Second = SecondVec->getAs<VectorType>();
5204  if (First->getNumElements() == Second->getNumElements() &&
5205      hasSameType(First->getElementType(), Second->getElementType()) &&
5206      First->getVectorKind() != VectorType::AltiVecPixel &&
5207      First->getVectorKind() != VectorType::AltiVecBool &&
5208      Second->getVectorKind() != VectorType::AltiVecPixel &&
5209      Second->getVectorKind() != VectorType::AltiVecBool)
5210    return true;
5211
5212  return false;
5213}
5214
5215//===----------------------------------------------------------------------===//
5216// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5217//===----------------------------------------------------------------------===//
5218
5219/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5220/// inheritance hierarchy of 'rProto'.
5221bool
5222ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5223                                           ObjCProtocolDecl *rProto) const {
5224  if (declaresSameEntity(lProto, rProto))
5225    return true;
5226  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5227       E = rProto->protocol_end(); PI != E; ++PI)
5228    if (ProtocolCompatibleWithProtocol(lProto, *PI))
5229      return true;
5230  return false;
5231}
5232
5233/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5234/// return true if lhs's protocols conform to rhs's protocol; false
5235/// otherwise.
5236bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5237  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5238    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5239  return false;
5240}
5241
5242/// ObjCQualifiedClassTypesAreCompatible - compare  Class<p,...> and
5243/// Class<p1, ...>.
5244bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5245                                                      QualType rhs) {
5246  const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5247  const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5248  assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5249
5250  for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5251       E = lhsQID->qual_end(); I != E; ++I) {
5252    bool match = false;
5253    ObjCProtocolDecl *lhsProto = *I;
5254    for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5255         E = rhsOPT->qual_end(); J != E; ++J) {
5256      ObjCProtocolDecl *rhsProto = *J;
5257      if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5258        match = true;
5259        break;
5260      }
5261    }
5262    if (!match)
5263      return false;
5264  }
5265  return true;
5266}
5267
5268/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5269/// ObjCQualifiedIDType.
5270bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5271                                                   bool compare) {
5272  // Allow id<P..> and an 'id' or void* type in all cases.
5273  if (lhs->isVoidPointerType() ||
5274      lhs->isObjCIdType() || lhs->isObjCClassType())
5275    return true;
5276  else if (rhs->isVoidPointerType() ||
5277           rhs->isObjCIdType() || rhs->isObjCClassType())
5278    return true;
5279
5280  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
5281    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5282
5283    if (!rhsOPT) return false;
5284
5285    if (rhsOPT->qual_empty()) {
5286      // If the RHS is a unqualified interface pointer "NSString*",
5287      // make sure we check the class hierarchy.
5288      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5289        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5290             E = lhsQID->qual_end(); I != E; ++I) {
5291          // when comparing an id<P> on lhs with a static type on rhs,
5292          // see if static class implements all of id's protocols, directly or
5293          // through its super class and categories.
5294          if (!rhsID->ClassImplementsProtocol(*I, true))
5295            return false;
5296        }
5297      }
5298      // If there are no qualifiers and no interface, we have an 'id'.
5299      return true;
5300    }
5301    // Both the right and left sides have qualifiers.
5302    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5303         E = lhsQID->qual_end(); I != E; ++I) {
5304      ObjCProtocolDecl *lhsProto = *I;
5305      bool match = false;
5306
5307      // when comparing an id<P> on lhs with a static type on rhs,
5308      // see if static class implements all of id's protocols, directly or
5309      // through its super class and categories.
5310      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5311           E = rhsOPT->qual_end(); J != E; ++J) {
5312        ObjCProtocolDecl *rhsProto = *J;
5313        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5314            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5315          match = true;
5316          break;
5317        }
5318      }
5319      // If the RHS is a qualified interface pointer "NSString<P>*",
5320      // make sure we check the class hierarchy.
5321      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5322        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5323             E = lhsQID->qual_end(); I != E; ++I) {
5324          // when comparing an id<P> on lhs with a static type on rhs,
5325          // see if static class implements all of id's protocols, directly or
5326          // through its super class and categories.
5327          if (rhsID->ClassImplementsProtocol(*I, true)) {
5328            match = true;
5329            break;
5330          }
5331        }
5332      }
5333      if (!match)
5334        return false;
5335    }
5336
5337    return true;
5338  }
5339
5340  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5341  assert(rhsQID && "One of the LHS/RHS should be id<x>");
5342
5343  if (const ObjCObjectPointerType *lhsOPT =
5344        lhs->getAsObjCInterfacePointerType()) {
5345    // If both the right and left sides have qualifiers.
5346    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5347         E = lhsOPT->qual_end(); I != E; ++I) {
5348      ObjCProtocolDecl *lhsProto = *I;
5349      bool match = false;
5350
5351      // when comparing an id<P> on rhs with a static type on lhs,
5352      // see if static class implements all of id's protocols, directly or
5353      // through its super class and categories.
5354      // First, lhs protocols in the qualifier list must be found, direct
5355      // or indirect in rhs's qualifier list or it is a mismatch.
5356      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5357           E = rhsQID->qual_end(); J != E; ++J) {
5358        ObjCProtocolDecl *rhsProto = *J;
5359        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5360            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5361          match = true;
5362          break;
5363        }
5364      }
5365      if (!match)
5366        return false;
5367    }
5368
5369    // Static class's protocols, or its super class or category protocols
5370    // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5371    if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5372      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5373      CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5374      // This is rather dubious but matches gcc's behavior. If lhs has
5375      // no type qualifier and its class has no static protocol(s)
5376      // assume that it is mismatch.
5377      if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5378        return false;
5379      for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5380           LHSInheritedProtocols.begin(),
5381           E = LHSInheritedProtocols.end(); I != E; ++I) {
5382        bool match = false;
5383        ObjCProtocolDecl *lhsProto = (*I);
5384        for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5385             E = rhsQID->qual_end(); J != E; ++J) {
5386          ObjCProtocolDecl *rhsProto = *J;
5387          if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5388              (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5389            match = true;
5390            break;
5391          }
5392        }
5393        if (!match)
5394          return false;
5395      }
5396    }
5397    return true;
5398  }
5399  return false;
5400}
5401
5402/// canAssignObjCInterfaces - Return true if the two interface types are
5403/// compatible for assignment from RHS to LHS.  This handles validation of any
5404/// protocol qualifiers on the LHS or RHS.
5405///
5406bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5407                                         const ObjCObjectPointerType *RHSOPT) {
5408  const ObjCObjectType* LHS = LHSOPT->getObjectType();
5409  const ObjCObjectType* RHS = RHSOPT->getObjectType();
5410
5411  // If either type represents the built-in 'id' or 'Class' types, return true.
5412  if (LHS->isObjCUnqualifiedIdOrClass() ||
5413      RHS->isObjCUnqualifiedIdOrClass())
5414    return true;
5415
5416  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
5417    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5418                                             QualType(RHSOPT,0),
5419                                             false);
5420
5421  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5422    return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5423                                                QualType(RHSOPT,0));
5424
5425  // If we have 2 user-defined types, fall into that path.
5426  if (LHS->getInterface() && RHS->getInterface())
5427    return canAssignObjCInterfaces(LHS, RHS);
5428
5429  return false;
5430}
5431
5432/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
5433/// for providing type-safety for objective-c pointers used to pass/return
5434/// arguments in block literals. When passed as arguments, passing 'A*' where
5435/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5436/// not OK. For the return type, the opposite is not OK.
5437bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5438                                         const ObjCObjectPointerType *LHSOPT,
5439                                         const ObjCObjectPointerType *RHSOPT,
5440                                         bool BlockReturnType) {
5441  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
5442    return true;
5443
5444  if (LHSOPT->isObjCBuiltinType()) {
5445    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5446  }
5447
5448  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
5449    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5450                                             QualType(RHSOPT,0),
5451                                             false);
5452
5453  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5454  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5455  if (LHS && RHS)  { // We have 2 user-defined types.
5456    if (LHS != RHS) {
5457      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
5458        return BlockReturnType;
5459      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
5460        return !BlockReturnType;
5461    }
5462    else
5463      return true;
5464  }
5465  return false;
5466}
5467
5468/// getIntersectionOfProtocols - This routine finds the intersection of set
5469/// of protocols inherited from two distinct objective-c pointer objects.
5470/// It is used to build composite qualifier list of the composite type of
5471/// the conditional expression involving two objective-c pointer objects.
5472static
5473void getIntersectionOfProtocols(ASTContext &Context,
5474                                const ObjCObjectPointerType *LHSOPT,
5475                                const ObjCObjectPointerType *RHSOPT,
5476      SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5477
5478  const ObjCObjectType* LHS = LHSOPT->getObjectType();
5479  const ObjCObjectType* RHS = RHSOPT->getObjectType();
5480  assert(LHS->getInterface() && "LHS must have an interface base");
5481  assert(RHS->getInterface() && "RHS must have an interface base");
5482
5483  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5484  unsigned LHSNumProtocols = LHS->getNumProtocols();
5485  if (LHSNumProtocols > 0)
5486    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5487  else {
5488    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5489    Context.CollectInheritedProtocols(LHS->getInterface(),
5490                                      LHSInheritedProtocols);
5491    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5492                                LHSInheritedProtocols.end());
5493  }
5494
5495  unsigned RHSNumProtocols = RHS->getNumProtocols();
5496  if (RHSNumProtocols > 0) {
5497    ObjCProtocolDecl **RHSProtocols =
5498      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
5499    for (unsigned i = 0; i < RHSNumProtocols; ++i)
5500      if (InheritedProtocolSet.count(RHSProtocols[i]))
5501        IntersectionOfProtocols.push_back(RHSProtocols[i]);
5502  } else {
5503    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
5504    Context.CollectInheritedProtocols(RHS->getInterface(),
5505                                      RHSInheritedProtocols);
5506    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5507         RHSInheritedProtocols.begin(),
5508         E = RHSInheritedProtocols.end(); I != E; ++I)
5509      if (InheritedProtocolSet.count((*I)))
5510        IntersectionOfProtocols.push_back((*I));
5511  }
5512}
5513
5514/// areCommonBaseCompatible - Returns common base class of the two classes if
5515/// one found. Note that this is O'2 algorithm. But it will be called as the
5516/// last type comparison in a ?-exp of ObjC pointer types before a
5517/// warning is issued. So, its invokation is extremely rare.
5518QualType ASTContext::areCommonBaseCompatible(
5519                                          const ObjCObjectPointerType *Lptr,
5520                                          const ObjCObjectPointerType *Rptr) {
5521  const ObjCObjectType *LHS = Lptr->getObjectType();
5522  const ObjCObjectType *RHS = Rptr->getObjectType();
5523  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5524  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
5525  if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
5526    return QualType();
5527
5528  do {
5529    LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
5530    if (canAssignObjCInterfaces(LHS, RHS)) {
5531      SmallVector<ObjCProtocolDecl *, 8> Protocols;
5532      getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5533
5534      QualType Result = QualType(LHS, 0);
5535      if (!Protocols.empty())
5536        Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5537      Result = getObjCObjectPointerType(Result);
5538      return Result;
5539    }
5540  } while ((LDecl = LDecl->getSuperClass()));
5541
5542  return QualType();
5543}
5544
5545bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5546                                         const ObjCObjectType *RHS) {
5547  assert(LHS->getInterface() && "LHS is not an interface type");
5548  assert(RHS->getInterface() && "RHS is not an interface type");
5549
5550  // Verify that the base decls are compatible: the RHS must be a subclass of
5551  // the LHS.
5552  if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
5553    return false;
5554
5555  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
5556  // protocol qualified at all, then we are good.
5557  if (LHS->getNumProtocols() == 0)
5558    return true;
5559
5560  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't,
5561  // more detailed analysis is required.
5562  if (RHS->getNumProtocols() == 0) {
5563    // OK, if LHS is a superclass of RHS *and*
5564    // this superclass is assignment compatible with LHS.
5565    // false otherwise.
5566    bool IsSuperClass =
5567      LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5568    if (IsSuperClass) {
5569      // OK if conversion of LHS to SuperClass results in narrowing of types
5570      // ; i.e., SuperClass may implement at least one of the protocols
5571      // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5572      // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5573      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
5574      CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
5575      // If super class has no protocols, it is not a match.
5576      if (SuperClassInheritedProtocols.empty())
5577        return false;
5578
5579      for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5580           LHSPE = LHS->qual_end();
5581           LHSPI != LHSPE; LHSPI++) {
5582        bool SuperImplementsProtocol = false;
5583        ObjCProtocolDecl *LHSProto = (*LHSPI);
5584
5585        for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5586             SuperClassInheritedProtocols.begin(),
5587             E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5588          ObjCProtocolDecl *SuperClassProto = (*I);
5589          if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5590            SuperImplementsProtocol = true;
5591            break;
5592          }
5593        }
5594        if (!SuperImplementsProtocol)
5595          return false;
5596      }
5597      return true;
5598    }
5599    return false;
5600  }
5601
5602  for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5603                                     LHSPE = LHS->qual_end();
5604       LHSPI != LHSPE; LHSPI++) {
5605    bool RHSImplementsProtocol = false;
5606
5607    // If the RHS doesn't implement the protocol on the left, the types
5608    // are incompatible.
5609    for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5610                                       RHSPE = RHS->qual_end();
5611         RHSPI != RHSPE; RHSPI++) {
5612      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
5613        RHSImplementsProtocol = true;
5614        break;
5615      }
5616    }
5617    // FIXME: For better diagnostics, consider passing back the protocol name.
5618    if (!RHSImplementsProtocol)
5619      return false;
5620  }
5621  // The RHS implements all protocols listed on the LHS.
5622  return true;
5623}
5624
5625bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5626  // get the "pointed to" types
5627  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5628  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
5629
5630  if (!LHSOPT || !RHSOPT)
5631    return false;
5632
5633  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5634         canAssignObjCInterfaces(RHSOPT, LHSOPT);
5635}
5636
5637bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5638  return canAssignObjCInterfaces(
5639                getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5640                getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5641}
5642
5643/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
5644/// both shall have the identically qualified version of a compatible type.
5645/// C99 6.2.7p1: Two types have compatible types if their types are the
5646/// same. See 6.7.[2,3,5] for additional rules.
5647bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5648                                    bool CompareUnqualified) {
5649  if (getLangOptions().CPlusPlus)
5650    return hasSameType(LHS, RHS);
5651
5652  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
5653}
5654
5655bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
5656  return typesAreCompatible(LHS, RHS);
5657}
5658
5659bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5660  return !mergeTypes(LHS, RHS, true).isNull();
5661}
5662
5663/// mergeTransparentUnionType - if T is a transparent union type and a member
5664/// of T is compatible with SubType, return the merged type, else return
5665/// QualType()
5666QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5667                                               bool OfBlockPointer,
5668                                               bool Unqualified) {
5669  if (const RecordType *UT = T->getAsUnionType()) {
5670    RecordDecl *UD = UT->getDecl();
5671    if (UD->hasAttr<TransparentUnionAttr>()) {
5672      for (RecordDecl::field_iterator it = UD->field_begin(),
5673           itend = UD->field_end(); it != itend; ++it) {
5674        QualType ET = it->getType().getUnqualifiedType();
5675        QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5676        if (!MT.isNull())
5677          return MT;
5678      }
5679    }
5680  }
5681
5682  return QualType();
5683}
5684
5685/// mergeFunctionArgumentTypes - merge two types which appear as function
5686/// argument types
5687QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5688                                                bool OfBlockPointer,
5689                                                bool Unqualified) {
5690  // GNU extension: two types are compatible if they appear as a function
5691  // argument, one of the types is a transparent union type and the other
5692  // type is compatible with a union member
5693  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5694                                              Unqualified);
5695  if (!lmerge.isNull())
5696    return lmerge;
5697
5698  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5699                                              Unqualified);
5700  if (!rmerge.isNull())
5701    return rmerge;
5702
5703  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5704}
5705
5706QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
5707                                        bool OfBlockPointer,
5708                                        bool Unqualified) {
5709  const FunctionType *lbase = lhs->getAs<FunctionType>();
5710  const FunctionType *rbase = rhs->getAs<FunctionType>();
5711  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5712  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
5713  bool allLTypes = true;
5714  bool allRTypes = true;
5715
5716  // Check return type
5717  QualType retType;
5718  if (OfBlockPointer) {
5719    QualType RHS = rbase->getResultType();
5720    QualType LHS = lbase->getResultType();
5721    bool UnqualifiedResult = Unqualified;
5722    if (!UnqualifiedResult)
5723      UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5724    retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
5725  }
5726  else
5727    retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5728                         Unqualified);
5729  if (retType.isNull()) return QualType();
5730
5731  if (Unqualified)
5732    retType = retType.getUnqualifiedType();
5733
5734  CanQualType LRetType = getCanonicalType(lbase->getResultType());
5735  CanQualType RRetType = getCanonicalType(rbase->getResultType());
5736  if (Unqualified) {
5737    LRetType = LRetType.getUnqualifiedType();
5738    RRetType = RRetType.getUnqualifiedType();
5739  }
5740
5741  if (getCanonicalType(retType) != LRetType)
5742    allLTypes = false;
5743  if (getCanonicalType(retType) != RRetType)
5744    allRTypes = false;
5745
5746  // FIXME: double check this
5747  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5748  //                           rbase->getRegParmAttr() != 0 &&
5749  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
5750  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5751  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
5752
5753  // Compatible functions must have compatible calling conventions
5754  if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
5755    return QualType();
5756
5757  // Regparm is part of the calling convention.
5758  if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5759    return QualType();
5760  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5761    return QualType();
5762
5763  if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5764    return QualType();
5765
5766  // functypes which return are preferred over those that do not.
5767  if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5768    allLTypes = false;
5769  else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5770    allRTypes = false;
5771  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5772  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5773
5774  FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
5775
5776  if (lproto && rproto) { // two C99 style function prototypes
5777    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5778           "C++ shouldn't be here");
5779    unsigned lproto_nargs = lproto->getNumArgs();
5780    unsigned rproto_nargs = rproto->getNumArgs();
5781
5782    // Compatible functions must have the same number of arguments
5783    if (lproto_nargs != rproto_nargs)
5784      return QualType();
5785
5786    // Variadic and non-variadic functions aren't compatible
5787    if (lproto->isVariadic() != rproto->isVariadic())
5788      return QualType();
5789
5790    if (lproto->getTypeQuals() != rproto->getTypeQuals())
5791      return QualType();
5792
5793    if (LangOpts.ObjCAutoRefCount &&
5794        !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5795      return QualType();
5796
5797    // Check argument compatibility
5798    SmallVector<QualType, 10> types;
5799    for (unsigned i = 0; i < lproto_nargs; i++) {
5800      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5801      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
5802      QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5803                                                    OfBlockPointer,
5804                                                    Unqualified);
5805      if (argtype.isNull()) return QualType();
5806
5807      if (Unqualified)
5808        argtype = argtype.getUnqualifiedType();
5809
5810      types.push_back(argtype);
5811      if (Unqualified) {
5812        largtype = largtype.getUnqualifiedType();
5813        rargtype = rargtype.getUnqualifiedType();
5814      }
5815
5816      if (getCanonicalType(argtype) != getCanonicalType(largtype))
5817        allLTypes = false;
5818      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5819        allRTypes = false;
5820    }
5821
5822    if (allLTypes) return lhs;
5823    if (allRTypes) return rhs;
5824
5825    FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5826    EPI.ExtInfo = einfo;
5827    return getFunctionType(retType, types.begin(), types.size(), EPI);
5828  }
5829
5830  if (lproto) allRTypes = false;
5831  if (rproto) allLTypes = false;
5832
5833  const FunctionProtoType *proto = lproto ? lproto : rproto;
5834  if (proto) {
5835    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
5836    if (proto->isVariadic()) return QualType();
5837    // Check that the types are compatible with the types that
5838    // would result from default argument promotions (C99 6.7.5.3p15).
5839    // The only types actually affected are promotable integer
5840    // types and floats, which would be passed as a different
5841    // type depending on whether the prototype is visible.
5842    unsigned proto_nargs = proto->getNumArgs();
5843    for (unsigned i = 0; i < proto_nargs; ++i) {
5844      QualType argTy = proto->getArgType(i);
5845
5846      // Look at the promotion type of enum types, since that is the type used
5847      // to pass enum values.
5848      if (const EnumType *Enum = argTy->getAs<EnumType>())
5849        argTy = Enum->getDecl()->getPromotionType();
5850
5851      if (argTy->isPromotableIntegerType() ||
5852          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5853        return QualType();
5854    }
5855
5856    if (allLTypes) return lhs;
5857    if (allRTypes) return rhs;
5858
5859    FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5860    EPI.ExtInfo = einfo;
5861    return getFunctionType(retType, proto->arg_type_begin(),
5862                           proto->getNumArgs(), EPI);
5863  }
5864
5865  if (allLTypes) return lhs;
5866  if (allRTypes) return rhs;
5867  return getFunctionNoProtoType(retType, einfo);
5868}
5869
5870QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
5871                                bool OfBlockPointer,
5872                                bool Unqualified, bool BlockReturnType) {
5873  // C++ [expr]: If an expression initially has the type "reference to T", the
5874  // type is adjusted to "T" prior to any further analysis, the expression
5875  // designates the object or function denoted by the reference, and the
5876  // expression is an lvalue unless the reference is an rvalue reference and
5877  // the expression is a function call (possibly inside parentheses).
5878  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5879  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
5880
5881  if (Unqualified) {
5882    LHS = LHS.getUnqualifiedType();
5883    RHS = RHS.getUnqualifiedType();
5884  }
5885
5886  QualType LHSCan = getCanonicalType(LHS),
5887           RHSCan = getCanonicalType(RHS);
5888
5889  // If two types are identical, they are compatible.
5890  if (LHSCan == RHSCan)
5891    return LHS;
5892
5893  // If the qualifiers are different, the types aren't compatible... mostly.
5894  Qualifiers LQuals = LHSCan.getLocalQualifiers();
5895  Qualifiers RQuals = RHSCan.getLocalQualifiers();
5896  if (LQuals != RQuals) {
5897    // If any of these qualifiers are different, we have a type
5898    // mismatch.
5899    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5900        LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5901        LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
5902      return QualType();
5903
5904    // Exactly one GC qualifier difference is allowed: __strong is
5905    // okay if the other type has no GC qualifier but is an Objective
5906    // C object pointer (i.e. implicitly strong by default).  We fix
5907    // this by pretending that the unqualified type was actually
5908    // qualified __strong.
5909    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5910    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5911    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5912
5913    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5914      return QualType();
5915
5916    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5917      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5918    }
5919    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5920      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5921    }
5922    return QualType();
5923  }
5924
5925  // Okay, qualifiers are equal.
5926
5927  Type::TypeClass LHSClass = LHSCan->getTypeClass();
5928  Type::TypeClass RHSClass = RHSCan->getTypeClass();
5929
5930  // We want to consider the two function types to be the same for these
5931  // comparisons, just force one to the other.
5932  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5933  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
5934
5935  // Same as above for arrays
5936  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5937    LHSClass = Type::ConstantArray;
5938  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5939    RHSClass = Type::ConstantArray;
5940
5941  // ObjCInterfaces are just specialized ObjCObjects.
5942  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5943  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5944
5945  // Canonicalize ExtVector -> Vector.
5946  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5947  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
5948
5949  // If the canonical type classes don't match.
5950  if (LHSClass != RHSClass) {
5951    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
5952    // a signed integer type, or an unsigned integer type.
5953    // Compatibility is based on the underlying type, not the promotion
5954    // type.
5955    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
5956      QualType TINT = ETy->getDecl()->getIntegerType();
5957      if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
5958        return RHS;
5959    }
5960    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
5961      QualType TINT = ETy->getDecl()->getIntegerType();
5962      if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
5963        return LHS;
5964    }
5965    // allow block pointer type to match an 'id' type.
5966    if (OfBlockPointer && !BlockReturnType) {
5967       if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5968         return LHS;
5969      if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5970        return RHS;
5971    }
5972
5973    return QualType();
5974  }
5975
5976  // The canonical type classes match.
5977  switch (LHSClass) {
5978#define TYPE(Class, Base)
5979#define ABSTRACT_TYPE(Class, Base)
5980#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
5981#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5982#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5983#include "clang/AST/TypeNodes.def"
5984    llvm_unreachable("Non-canonical and dependent types shouldn't get here");
5985
5986  case Type::LValueReference:
5987  case Type::RValueReference:
5988  case Type::MemberPointer:
5989    llvm_unreachable("C++ should never be in mergeTypes");
5990
5991  case Type::ObjCInterface:
5992  case Type::IncompleteArray:
5993  case Type::VariableArray:
5994  case Type::FunctionProto:
5995  case Type::ExtVector:
5996    llvm_unreachable("Types are eliminated above");
5997
5998  case Type::Pointer:
5999  {
6000    // Merge two pointer types, while trying to preserve typedef info
6001    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6002    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
6003    if (Unqualified) {
6004      LHSPointee = LHSPointee.getUnqualifiedType();
6005      RHSPointee = RHSPointee.getUnqualifiedType();
6006    }
6007    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6008                                     Unqualified);
6009    if (ResultType.isNull()) return QualType();
6010    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6011      return LHS;
6012    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6013      return RHS;
6014    return getPointerType(ResultType);
6015  }
6016  case Type::BlockPointer:
6017  {
6018    // Merge two block pointer types, while trying to preserve typedef info
6019    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6020    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
6021    if (Unqualified) {
6022      LHSPointee = LHSPointee.getUnqualifiedType();
6023      RHSPointee = RHSPointee.getUnqualifiedType();
6024    }
6025    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6026                                     Unqualified);
6027    if (ResultType.isNull()) return QualType();
6028    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6029      return LHS;
6030    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6031      return RHS;
6032    return getBlockPointerType(ResultType);
6033  }
6034  case Type::Atomic:
6035  {
6036    // Merge two pointer types, while trying to preserve typedef info
6037    QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6038    QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6039    if (Unqualified) {
6040      LHSValue = LHSValue.getUnqualifiedType();
6041      RHSValue = RHSValue.getUnqualifiedType();
6042    }
6043    QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6044                                     Unqualified);
6045    if (ResultType.isNull()) return QualType();
6046    if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6047      return LHS;
6048    if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6049      return RHS;
6050    return getAtomicType(ResultType);
6051  }
6052  case Type::ConstantArray:
6053  {
6054    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6055    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6056    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6057      return QualType();
6058
6059    QualType LHSElem = getAsArrayType(LHS)->getElementType();
6060    QualType RHSElem = getAsArrayType(RHS)->getElementType();
6061    if (Unqualified) {
6062      LHSElem = LHSElem.getUnqualifiedType();
6063      RHSElem = RHSElem.getUnqualifiedType();
6064    }
6065
6066    QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
6067    if (ResultType.isNull()) return QualType();
6068    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6069      return LHS;
6070    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6071      return RHS;
6072    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6073                                          ArrayType::ArraySizeModifier(), 0);
6074    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6075                                          ArrayType::ArraySizeModifier(), 0);
6076    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6077    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
6078    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6079      return LHS;
6080    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6081      return RHS;
6082    if (LVAT) {
6083      // FIXME: This isn't correct! But tricky to implement because
6084      // the array's size has to be the size of LHS, but the type
6085      // has to be different.
6086      return LHS;
6087    }
6088    if (RVAT) {
6089      // FIXME: This isn't correct! But tricky to implement because
6090      // the array's size has to be the size of RHS, but the type
6091      // has to be different.
6092      return RHS;
6093    }
6094    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6095    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
6096    return getIncompleteArrayType(ResultType,
6097                                  ArrayType::ArraySizeModifier(), 0);
6098  }
6099  case Type::FunctionNoProto:
6100    return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
6101  case Type::Record:
6102  case Type::Enum:
6103    return QualType();
6104  case Type::Builtin:
6105    // Only exactly equal builtin types are compatible, which is tested above.
6106    return QualType();
6107  case Type::Complex:
6108    // Distinct complex types are incompatible.
6109    return QualType();
6110  case Type::Vector:
6111    // FIXME: The merged type should be an ExtVector!
6112    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6113                             RHSCan->getAs<VectorType>()))
6114      return LHS;
6115    return QualType();
6116  case Type::ObjCObject: {
6117    // Check if the types are assignment compatible.
6118    // FIXME: This should be type compatibility, e.g. whether
6119    // "LHS x; RHS x;" at global scope is legal.
6120    const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6121    const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6122    if (canAssignObjCInterfaces(LHSIface, RHSIface))
6123      return LHS;
6124
6125    return QualType();
6126  }
6127  case Type::ObjCObjectPointer: {
6128    if (OfBlockPointer) {
6129      if (canAssignObjCInterfacesInBlockPointer(
6130                                          LHS->getAs<ObjCObjectPointerType>(),
6131                                          RHS->getAs<ObjCObjectPointerType>(),
6132                                          BlockReturnType))
6133        return LHS;
6134      return QualType();
6135    }
6136    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6137                                RHS->getAs<ObjCObjectPointerType>()))
6138      return LHS;
6139
6140    return QualType();
6141  }
6142  }
6143
6144  llvm_unreachable("Invalid Type::Class!");
6145}
6146
6147bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6148                   const FunctionProtoType *FromFunctionType,
6149                   const FunctionProtoType *ToFunctionType) {
6150  if (FromFunctionType->hasAnyConsumedArgs() !=
6151      ToFunctionType->hasAnyConsumedArgs())
6152    return false;
6153  FunctionProtoType::ExtProtoInfo FromEPI =
6154    FromFunctionType->getExtProtoInfo();
6155  FunctionProtoType::ExtProtoInfo ToEPI =
6156    ToFunctionType->getExtProtoInfo();
6157  if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6158    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6159         ArgIdx != NumArgs; ++ArgIdx)  {
6160      if (FromEPI.ConsumedArguments[ArgIdx] !=
6161          ToEPI.ConsumedArguments[ArgIdx])
6162        return false;
6163    }
6164  return true;
6165}
6166
6167/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6168/// 'RHS' attributes and returns the merged version; including for function
6169/// return types.
6170QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6171  QualType LHSCan = getCanonicalType(LHS),
6172  RHSCan = getCanonicalType(RHS);
6173  // If two types are identical, they are compatible.
6174  if (LHSCan == RHSCan)
6175    return LHS;
6176  if (RHSCan->isFunctionType()) {
6177    if (!LHSCan->isFunctionType())
6178      return QualType();
6179    QualType OldReturnType =
6180      cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6181    QualType NewReturnType =
6182      cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6183    QualType ResReturnType =
6184      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6185    if (ResReturnType.isNull())
6186      return QualType();
6187    if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6188      // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6189      // In either case, use OldReturnType to build the new function type.
6190      const FunctionType *F = LHS->getAs<FunctionType>();
6191      if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
6192        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6193        EPI.ExtInfo = getFunctionExtInfo(LHS);
6194        QualType ResultType
6195          = getFunctionType(OldReturnType, FPT->arg_type_begin(),
6196                            FPT->getNumArgs(), EPI);
6197        return ResultType;
6198      }
6199    }
6200    return QualType();
6201  }
6202
6203  // If the qualifiers are different, the types can still be merged.
6204  Qualifiers LQuals = LHSCan.getLocalQualifiers();
6205  Qualifiers RQuals = RHSCan.getLocalQualifiers();
6206  if (LQuals != RQuals) {
6207    // If any of these qualifiers are different, we have a type mismatch.
6208    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6209        LQuals.getAddressSpace() != RQuals.getAddressSpace())
6210      return QualType();
6211
6212    // Exactly one GC qualifier difference is allowed: __strong is
6213    // okay if the other type has no GC qualifier but is an Objective
6214    // C object pointer (i.e. implicitly strong by default).  We fix
6215    // this by pretending that the unqualified type was actually
6216    // qualified __strong.
6217    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6218    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6219    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6220
6221    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6222      return QualType();
6223
6224    if (GC_L == Qualifiers::Strong)
6225      return LHS;
6226    if (GC_R == Qualifiers::Strong)
6227      return RHS;
6228    return QualType();
6229  }
6230
6231  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6232    QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6233    QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6234    QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6235    if (ResQT == LHSBaseQT)
6236      return LHS;
6237    if (ResQT == RHSBaseQT)
6238      return RHS;
6239  }
6240  return QualType();
6241}
6242
6243//===----------------------------------------------------------------------===//
6244//                         Integer Predicates
6245//===----------------------------------------------------------------------===//
6246
6247unsigned ASTContext::getIntWidth(QualType T) const {
6248  if (const EnumType *ET = dyn_cast<EnumType>(T))
6249    T = ET->getDecl()->getIntegerType();
6250  if (T->isBooleanType())
6251    return 1;
6252  // For builtin types, just use the standard type sizing method
6253  return (unsigned)getTypeSize(T);
6254}
6255
6256QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
6257  assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
6258
6259  // Turn <4 x signed int> -> <4 x unsigned int>
6260  if (const VectorType *VTy = T->getAs<VectorType>())
6261    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
6262                         VTy->getNumElements(), VTy->getVectorKind());
6263
6264  // For enums, we return the unsigned version of the base type.
6265  if (const EnumType *ETy = T->getAs<EnumType>())
6266    T = ETy->getDecl()->getIntegerType();
6267
6268  const BuiltinType *BTy = T->getAs<BuiltinType>();
6269  assert(BTy && "Unexpected signed integer type");
6270  switch (BTy->getKind()) {
6271  case BuiltinType::Char_S:
6272  case BuiltinType::SChar:
6273    return UnsignedCharTy;
6274  case BuiltinType::Short:
6275    return UnsignedShortTy;
6276  case BuiltinType::Int:
6277    return UnsignedIntTy;
6278  case BuiltinType::Long:
6279    return UnsignedLongTy;
6280  case BuiltinType::LongLong:
6281    return UnsignedLongLongTy;
6282  case BuiltinType::Int128:
6283    return UnsignedInt128Ty;
6284  default:
6285    llvm_unreachable("Unexpected signed integer type");
6286  }
6287}
6288
6289ASTMutationListener::~ASTMutationListener() { }
6290
6291
6292//===----------------------------------------------------------------------===//
6293//                          Builtin Type Computation
6294//===----------------------------------------------------------------------===//
6295
6296/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
6297/// pointer over the consumed characters.  This returns the resultant type.  If
6298/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6299/// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
6300/// a vector of "i*".
6301///
6302/// RequiresICE is filled in on return to indicate whether the value is required
6303/// to be an Integer Constant Expression.
6304static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
6305                                  ASTContext::GetBuiltinTypeError &Error,
6306                                  bool &RequiresICE,
6307                                  bool AllowTypeModifiers) {
6308  // Modifiers.
6309  int HowLong = 0;
6310  bool Signed = false, Unsigned = false;
6311  RequiresICE = false;
6312
6313  // Read the prefixed modifiers first.
6314  bool Done = false;
6315  while (!Done) {
6316    switch (*Str++) {
6317    default: Done = true; --Str; break;
6318    case 'I':
6319      RequiresICE = true;
6320      break;
6321    case 'S':
6322      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6323      assert(!Signed && "Can't use 'S' modifier multiple times!");
6324      Signed = true;
6325      break;
6326    case 'U':
6327      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6328      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6329      Unsigned = true;
6330      break;
6331    case 'L':
6332      assert(HowLong <= 2 && "Can't have LLLL modifier");
6333      ++HowLong;
6334      break;
6335    }
6336  }
6337
6338  QualType Type;
6339
6340  // Read the base type.
6341  switch (*Str++) {
6342  default: llvm_unreachable("Unknown builtin type letter!");
6343  case 'v':
6344    assert(HowLong == 0 && !Signed && !Unsigned &&
6345           "Bad modifiers used with 'v'!");
6346    Type = Context.VoidTy;
6347    break;
6348  case 'f':
6349    assert(HowLong == 0 && !Signed && !Unsigned &&
6350           "Bad modifiers used with 'f'!");
6351    Type = Context.FloatTy;
6352    break;
6353  case 'd':
6354    assert(HowLong < 2 && !Signed && !Unsigned &&
6355           "Bad modifiers used with 'd'!");
6356    if (HowLong)
6357      Type = Context.LongDoubleTy;
6358    else
6359      Type = Context.DoubleTy;
6360    break;
6361  case 's':
6362    assert(HowLong == 0 && "Bad modifiers used with 's'!");
6363    if (Unsigned)
6364      Type = Context.UnsignedShortTy;
6365    else
6366      Type = Context.ShortTy;
6367    break;
6368  case 'i':
6369    if (HowLong == 3)
6370      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6371    else if (HowLong == 2)
6372      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6373    else if (HowLong == 1)
6374      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6375    else
6376      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6377    break;
6378  case 'c':
6379    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6380    if (Signed)
6381      Type = Context.SignedCharTy;
6382    else if (Unsigned)
6383      Type = Context.UnsignedCharTy;
6384    else
6385      Type = Context.CharTy;
6386    break;
6387  case 'b': // boolean
6388    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6389    Type = Context.BoolTy;
6390    break;
6391  case 'z':  // size_t.
6392    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6393    Type = Context.getSizeType();
6394    break;
6395  case 'F':
6396    Type = Context.getCFConstantStringType();
6397    break;
6398  case 'G':
6399    Type = Context.getObjCIdType();
6400    break;
6401  case 'H':
6402    Type = Context.getObjCSelType();
6403    break;
6404  case 'a':
6405    Type = Context.getBuiltinVaListType();
6406    assert(!Type.isNull() && "builtin va list type not initialized!");
6407    break;
6408  case 'A':
6409    // This is a "reference" to a va_list; however, what exactly
6410    // this means depends on how va_list is defined. There are two
6411    // different kinds of va_list: ones passed by value, and ones
6412    // passed by reference.  An example of a by-value va_list is
6413    // x86, where va_list is a char*. An example of by-ref va_list
6414    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6415    // we want this argument to be a char*&; for x86-64, we want
6416    // it to be a __va_list_tag*.
6417    Type = Context.getBuiltinVaListType();
6418    assert(!Type.isNull() && "builtin va list type not initialized!");
6419    if (Type->isArrayType())
6420      Type = Context.getArrayDecayedType(Type);
6421    else
6422      Type = Context.getLValueReferenceType(Type);
6423    break;
6424  case 'V': {
6425    char *End;
6426    unsigned NumElements = strtoul(Str, &End, 10);
6427    assert(End != Str && "Missing vector size");
6428    Str = End;
6429
6430    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6431                                             RequiresICE, false);
6432    assert(!RequiresICE && "Can't require vector ICE");
6433
6434    // TODO: No way to make AltiVec vectors in builtins yet.
6435    Type = Context.getVectorType(ElementType, NumElements,
6436                                 VectorType::GenericVector);
6437    break;
6438  }
6439  case 'X': {
6440    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6441                                             false);
6442    assert(!RequiresICE && "Can't require complex ICE");
6443    Type = Context.getComplexType(ElementType);
6444    break;
6445  }
6446  case 'Y' : {
6447    Type = Context.getPointerDiffType();
6448    break;
6449  }
6450  case 'P':
6451    Type = Context.getFILEType();
6452    if (Type.isNull()) {
6453      Error = ASTContext::GE_Missing_stdio;
6454      return QualType();
6455    }
6456    break;
6457  case 'J':
6458    if (Signed)
6459      Type = Context.getsigjmp_bufType();
6460    else
6461      Type = Context.getjmp_bufType();
6462
6463    if (Type.isNull()) {
6464      Error = ASTContext::GE_Missing_setjmp;
6465      return QualType();
6466    }
6467    break;
6468  case 'K':
6469    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6470    Type = Context.getucontext_tType();
6471
6472    if (Type.isNull()) {
6473      Error = ASTContext::GE_Missing_ucontext;
6474      return QualType();
6475    }
6476    break;
6477  }
6478
6479  // If there are modifiers and if we're allowed to parse them, go for it.
6480  Done = !AllowTypeModifiers;
6481  while (!Done) {
6482    switch (char c = *Str++) {
6483    default: Done = true; --Str; break;
6484    case '*':
6485    case '&': {
6486      // Both pointers and references can have their pointee types
6487      // qualified with an address space.
6488      char *End;
6489      unsigned AddrSpace = strtoul(Str, &End, 10);
6490      if (End != Str && AddrSpace != 0) {
6491        Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6492        Str = End;
6493      }
6494      if (c == '*')
6495        Type = Context.getPointerType(Type);
6496      else
6497        Type = Context.getLValueReferenceType(Type);
6498      break;
6499    }
6500    // FIXME: There's no way to have a built-in with an rvalue ref arg.
6501    case 'C':
6502      Type = Type.withConst();
6503      break;
6504    case 'D':
6505      Type = Context.getVolatileType(Type);
6506      break;
6507    case 'R':
6508      Type = Type.withRestrict();
6509      break;
6510    }
6511  }
6512
6513  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
6514         "Integer constant 'I' type must be an integer");
6515
6516  return Type;
6517}
6518
6519/// GetBuiltinType - Return the type for the specified builtin.
6520QualType ASTContext::GetBuiltinType(unsigned Id,
6521                                    GetBuiltinTypeError &Error,
6522                                    unsigned *IntegerConstantArgs) const {
6523  const char *TypeStr = BuiltinInfo.GetTypeString(Id);
6524
6525  SmallVector<QualType, 8> ArgTypes;
6526
6527  bool RequiresICE = false;
6528  Error = GE_None;
6529  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6530                                       RequiresICE, true);
6531  if (Error != GE_None)
6532    return QualType();
6533
6534  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6535
6536  while (TypeStr[0] && TypeStr[0] != '.') {
6537    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
6538    if (Error != GE_None)
6539      return QualType();
6540
6541    // If this argument is required to be an IntegerConstantExpression and the
6542    // caller cares, fill in the bitmask we return.
6543    if (RequiresICE && IntegerConstantArgs)
6544      *IntegerConstantArgs |= 1 << ArgTypes.size();
6545
6546    // Do array -> pointer decay.  The builtin should use the decayed type.
6547    if (Ty->isArrayType())
6548      Ty = getArrayDecayedType(Ty);
6549
6550    ArgTypes.push_back(Ty);
6551  }
6552
6553  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6554         "'.' should only occur at end of builtin type list!");
6555
6556  FunctionType::ExtInfo EI;
6557  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6558
6559  bool Variadic = (TypeStr[0] == '.');
6560
6561  // We really shouldn't be making a no-proto type here, especially in C++.
6562  if (ArgTypes.empty() && Variadic)
6563    return getFunctionNoProtoType(ResType, EI);
6564
6565  FunctionProtoType::ExtProtoInfo EPI;
6566  EPI.ExtInfo = EI;
6567  EPI.Variadic = Variadic;
6568
6569  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
6570}
6571
6572GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6573  GVALinkage External = GVA_StrongExternal;
6574
6575  Linkage L = FD->getLinkage();
6576  switch (L) {
6577  case NoLinkage:
6578  case InternalLinkage:
6579  case UniqueExternalLinkage:
6580    return GVA_Internal;
6581
6582  case ExternalLinkage:
6583    switch (FD->getTemplateSpecializationKind()) {
6584    case TSK_Undeclared:
6585    case TSK_ExplicitSpecialization:
6586      External = GVA_StrongExternal;
6587      break;
6588
6589    case TSK_ExplicitInstantiationDefinition:
6590      return GVA_ExplicitTemplateInstantiation;
6591
6592    case TSK_ExplicitInstantiationDeclaration:
6593    case TSK_ImplicitInstantiation:
6594      External = GVA_TemplateInstantiation;
6595      break;
6596    }
6597  }
6598
6599  if (!FD->isInlined())
6600    return External;
6601
6602  if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6603    // GNU or C99 inline semantics. Determine whether this symbol should be
6604    // externally visible.
6605    if (FD->isInlineDefinitionExternallyVisible())
6606      return External;
6607
6608    // C99 inline semantics, where the symbol is not externally visible.
6609    return GVA_C99Inline;
6610  }
6611
6612  // C++0x [temp.explicit]p9:
6613  //   [ Note: The intent is that an inline function that is the subject of
6614  //   an explicit instantiation declaration will still be implicitly
6615  //   instantiated when used so that the body can be considered for
6616  //   inlining, but that no out-of-line copy of the inline function would be
6617  //   generated in the translation unit. -- end note ]
6618  if (FD->getTemplateSpecializationKind()
6619                                       == TSK_ExplicitInstantiationDeclaration)
6620    return GVA_C99Inline;
6621
6622  return GVA_CXXInline;
6623}
6624
6625GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6626  // If this is a static data member, compute the kind of template
6627  // specialization. Otherwise, this variable is not part of a
6628  // template.
6629  TemplateSpecializationKind TSK = TSK_Undeclared;
6630  if (VD->isStaticDataMember())
6631    TSK = VD->getTemplateSpecializationKind();
6632
6633  Linkage L = VD->getLinkage();
6634  if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6635      VD->getType()->getLinkage() == UniqueExternalLinkage)
6636    L = UniqueExternalLinkage;
6637
6638  switch (L) {
6639  case NoLinkage:
6640  case InternalLinkage:
6641  case UniqueExternalLinkage:
6642    return GVA_Internal;
6643
6644  case ExternalLinkage:
6645    switch (TSK) {
6646    case TSK_Undeclared:
6647    case TSK_ExplicitSpecialization:
6648      return GVA_StrongExternal;
6649
6650    case TSK_ExplicitInstantiationDeclaration:
6651      llvm_unreachable("Variable should not be instantiated");
6652      // Fall through to treat this like any other instantiation.
6653
6654    case TSK_ExplicitInstantiationDefinition:
6655      return GVA_ExplicitTemplateInstantiation;
6656
6657    case TSK_ImplicitInstantiation:
6658      return GVA_TemplateInstantiation;
6659    }
6660  }
6661
6662  llvm_unreachable("Invalid Linkage!");
6663}
6664
6665bool ASTContext::DeclMustBeEmitted(const Decl *D) {
6666  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6667    if (!VD->isFileVarDecl())
6668      return false;
6669  } else if (!isa<FunctionDecl>(D))
6670    return false;
6671
6672  // Weak references don't produce any output by themselves.
6673  if (D->hasAttr<WeakRefAttr>())
6674    return false;
6675
6676  // Aliases and used decls are required.
6677  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6678    return true;
6679
6680  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6681    // Forward declarations aren't required.
6682    if (!FD->doesThisDeclarationHaveABody())
6683      return FD->doesDeclarationForceExternallyVisibleDefinition();
6684
6685    // Constructors and destructors are required.
6686    if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6687      return true;
6688
6689    // The key function for a class is required.
6690    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6691      const CXXRecordDecl *RD = MD->getParent();
6692      if (MD->isOutOfLine() && RD->isDynamicClass()) {
6693        const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6694        if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6695          return true;
6696      }
6697    }
6698
6699    GVALinkage Linkage = GetGVALinkageForFunction(FD);
6700
6701    // static, static inline, always_inline, and extern inline functions can
6702    // always be deferred.  Normal inline functions can be deferred in C99/C++.
6703    // Implicit template instantiations can also be deferred in C++.
6704    if (Linkage == GVA_Internal  || Linkage == GVA_C99Inline ||
6705        Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6706      return false;
6707    return true;
6708  }
6709
6710  const VarDecl *VD = cast<VarDecl>(D);
6711  assert(VD->isFileVarDecl() && "Expected file scoped var");
6712
6713  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6714    return false;
6715
6716  // Structs that have non-trivial constructors or destructors are required.
6717
6718  // FIXME: Handle references.
6719  // FIXME: Be more selective about which constructors we care about.
6720  if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6721    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
6722      if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6723                                   RD->hasTrivialCopyConstructor() &&
6724                                   RD->hasTrivialMoveConstructor() &&
6725                                   RD->hasTrivialDestructor()))
6726        return true;
6727    }
6728  }
6729
6730  GVALinkage L = GetGVALinkageForVariable(VD);
6731  if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6732    if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6733      return false;
6734  }
6735
6736  return true;
6737}
6738
6739CallingConv ASTContext::getDefaultMethodCallConv() {
6740  // Pass through to the C++ ABI object
6741  return ABI->getDefaultMethodCallConv();
6742}
6743
6744bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
6745  // Pass through to the C++ ABI object
6746  return ABI->isNearlyEmpty(RD);
6747}
6748
6749MangleContext *ASTContext::createMangleContext() {
6750  switch (Target->getCXXABI()) {
6751  case CXXABI_ARM:
6752  case CXXABI_Itanium:
6753    return createItaniumMangleContext(*this, getDiagnostics());
6754  case CXXABI_Microsoft:
6755    return createMicrosoftMangleContext(*this, getDiagnostics());
6756  }
6757  llvm_unreachable("Unsupported ABI");
6758}
6759
6760CXXABI::~CXXABI() {}
6761
6762size_t ASTContext::getSideTableAllocatedMemory() const {
6763  return ASTRecordLayouts.getMemorySize()
6764    + llvm::capacity_in_bytes(ObjCLayouts)
6765    + llvm::capacity_in_bytes(KeyFunctions)
6766    + llvm::capacity_in_bytes(ObjCImpls)
6767    + llvm::capacity_in_bytes(BlockVarCopyInits)
6768    + llvm::capacity_in_bytes(DeclAttrs)
6769    + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6770    + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6771    + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6772    + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6773    + llvm::capacity_in_bytes(OverriddenMethods)
6774    + llvm::capacity_in_bytes(Types)
6775    + llvm::capacity_in_bytes(VariableArrayTypes)
6776    + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
6777}
6778
6779void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6780  ParamIndices[D] = index;
6781}
6782
6783unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6784  ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6785  assert(I != ParamIndices.end() &&
6786         "ParmIndices lacks entry set by ParmVarDecl");
6787  return I->second;
6788}
6789