ASTContext.cpp revision 12fc4b0624706b474fa10308631fa8daf92f340f
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 =
2136    EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2137    !EPI.HasTrailingReturn;
2138  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2139    if (!ArgArray[i].isCanonicalAsParam())
2140      isCanonical = false;
2141
2142  const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2143  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2144                               CC_X86StdCall : DefaultCC;
2145
2146  // If this type isn't canonical, get the canonical version of it.
2147  // The exception spec is not part of the canonical type.
2148  QualType Canonical;
2149  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
2150    SmallVector<QualType, 16> CanonicalArgs;
2151    CanonicalArgs.reserve(NumArgs);
2152    for (unsigned i = 0; i != NumArgs; ++i)
2153      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2154
2155    FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2156    CanonicalEPI.HasTrailingReturn = false;
2157    CanonicalEPI.ExceptionSpecType = EST_None;
2158    CanonicalEPI.NumExceptions = 0;
2159    CanonicalEPI.ExtInfo
2160      = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2161
2162    Canonical = getFunctionType(getCanonicalType(ResultTy),
2163                                CanonicalArgs.data(), NumArgs,
2164                                CanonicalEPI);
2165
2166    // Get the new insert position for the node we care about.
2167    FunctionProtoType *NewIP =
2168      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2169    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2170  }
2171
2172  // FunctionProtoType objects are allocated with extra bytes after
2173  // them for three variable size arrays at the end:
2174  //  - parameter types
2175  //  - exception types
2176  //  - consumed-arguments flags
2177  // Instead of the exception types, there could be a noexcept
2178  // expression.
2179  size_t Size = sizeof(FunctionProtoType) +
2180                NumArgs * sizeof(QualType);
2181  if (EPI.ExceptionSpecType == EST_Dynamic)
2182    Size += EPI.NumExceptions * sizeof(QualType);
2183  else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2184    Size += sizeof(Expr*);
2185  }
2186  if (EPI.ConsumedArguments)
2187    Size += NumArgs * sizeof(bool);
2188
2189  FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2190  FunctionProtoType::ExtProtoInfo newEPI = EPI;
2191  newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
2192  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
2193  Types.push_back(FTP);
2194  FunctionProtoTypes.InsertNode(FTP, InsertPos);
2195  return QualType(FTP, 0);
2196}
2197
2198#ifndef NDEBUG
2199static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2200  if (!isa<CXXRecordDecl>(D)) return false;
2201  const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2202  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2203    return true;
2204  if (RD->getDescribedClassTemplate() &&
2205      !isa<ClassTemplateSpecializationDecl>(RD))
2206    return true;
2207  return false;
2208}
2209#endif
2210
2211/// getInjectedClassNameType - Return the unique reference to the
2212/// injected class name type for the specified templated declaration.
2213QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2214                                              QualType TST) const {
2215  assert(NeedsInjectedClassNameType(Decl));
2216  if (Decl->TypeForDecl) {
2217    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2218  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2219    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2220    Decl->TypeForDecl = PrevDecl->TypeForDecl;
2221    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2222  } else {
2223    Type *newType =
2224      new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2225    Decl->TypeForDecl = newType;
2226    Types.push_back(newType);
2227  }
2228  return QualType(Decl->TypeForDecl, 0);
2229}
2230
2231/// getTypeDeclType - Return the unique reference to the type for the
2232/// specified type declaration.
2233QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2234  assert(Decl && "Passed null for Decl param");
2235  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2236
2237  if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2238    return getTypedefType(Typedef);
2239
2240  assert(!isa<TemplateTypeParmDecl>(Decl) &&
2241         "Template type parameter types are always available.");
2242
2243  if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2244    assert(!Record->getPreviousDecl() &&
2245           "struct/union has previous declaration");
2246    assert(!NeedsInjectedClassNameType(Record));
2247    return getRecordType(Record);
2248  } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2249    assert(!Enum->getPreviousDecl() &&
2250           "enum has previous declaration");
2251    return getEnumType(Enum);
2252  } else if (const UnresolvedUsingTypenameDecl *Using =
2253               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2254    Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2255    Decl->TypeForDecl = newType;
2256    Types.push_back(newType);
2257  } else
2258    llvm_unreachable("TypeDecl without a type?");
2259
2260  return QualType(Decl->TypeForDecl, 0);
2261}
2262
2263/// getTypedefType - Return the unique reference to the type for the
2264/// specified typedef name decl.
2265QualType
2266ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2267                           QualType Canonical) const {
2268  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2269
2270  if (Canonical.isNull())
2271    Canonical = getCanonicalType(Decl->getUnderlyingType());
2272  TypedefType *newType = new(*this, TypeAlignment)
2273    TypedefType(Type::Typedef, Decl, Canonical);
2274  Decl->TypeForDecl = newType;
2275  Types.push_back(newType);
2276  return QualType(newType, 0);
2277}
2278
2279QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2280  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2281
2282  if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2283    if (PrevDecl->TypeForDecl)
2284      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2285
2286  RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2287  Decl->TypeForDecl = newType;
2288  Types.push_back(newType);
2289  return QualType(newType, 0);
2290}
2291
2292QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2293  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2294
2295  if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
2296    if (PrevDecl->TypeForDecl)
2297      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2298
2299  EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2300  Decl->TypeForDecl = newType;
2301  Types.push_back(newType);
2302  return QualType(newType, 0);
2303}
2304
2305QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2306                                       QualType modifiedType,
2307                                       QualType equivalentType) {
2308  llvm::FoldingSetNodeID id;
2309  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2310
2311  void *insertPos = 0;
2312  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2313  if (type) return QualType(type, 0);
2314
2315  QualType canon = getCanonicalType(equivalentType);
2316  type = new (*this, TypeAlignment)
2317           AttributedType(canon, attrKind, modifiedType, equivalentType);
2318
2319  Types.push_back(type);
2320  AttributedTypes.InsertNode(type, insertPos);
2321
2322  return QualType(type, 0);
2323}
2324
2325
2326/// \brief Retrieve a substitution-result type.
2327QualType
2328ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2329                                         QualType Replacement) const {
2330  assert(Replacement.isCanonical()
2331         && "replacement types must always be canonical");
2332
2333  llvm::FoldingSetNodeID ID;
2334  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2335  void *InsertPos = 0;
2336  SubstTemplateTypeParmType *SubstParm
2337    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2338
2339  if (!SubstParm) {
2340    SubstParm = new (*this, TypeAlignment)
2341      SubstTemplateTypeParmType(Parm, Replacement);
2342    Types.push_back(SubstParm);
2343    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2344  }
2345
2346  return QualType(SubstParm, 0);
2347}
2348
2349/// \brief Retrieve a
2350QualType ASTContext::getSubstTemplateTypeParmPackType(
2351                                          const TemplateTypeParmType *Parm,
2352                                              const TemplateArgument &ArgPack) {
2353#ifndef NDEBUG
2354  for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2355                                    PEnd = ArgPack.pack_end();
2356       P != PEnd; ++P) {
2357    assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2358    assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2359  }
2360#endif
2361
2362  llvm::FoldingSetNodeID ID;
2363  SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2364  void *InsertPos = 0;
2365  if (SubstTemplateTypeParmPackType *SubstParm
2366        = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2367    return QualType(SubstParm, 0);
2368
2369  QualType Canon;
2370  if (!Parm->isCanonicalUnqualified()) {
2371    Canon = getCanonicalType(QualType(Parm, 0));
2372    Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2373                                             ArgPack);
2374    SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2375  }
2376
2377  SubstTemplateTypeParmPackType *SubstParm
2378    = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2379                                                               ArgPack);
2380  Types.push_back(SubstParm);
2381  SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2382  return QualType(SubstParm, 0);
2383}
2384
2385/// \brief Retrieve the template type parameter type for a template
2386/// parameter or parameter pack with the given depth, index, and (optionally)
2387/// name.
2388QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2389                                             bool ParameterPack,
2390                                             TemplateTypeParmDecl *TTPDecl) const {
2391  llvm::FoldingSetNodeID ID;
2392  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
2393  void *InsertPos = 0;
2394  TemplateTypeParmType *TypeParm
2395    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2396
2397  if (TypeParm)
2398    return QualType(TypeParm, 0);
2399
2400  if (TTPDecl) {
2401    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2402    TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
2403
2404    TemplateTypeParmType *TypeCheck
2405      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2406    assert(!TypeCheck && "Template type parameter canonical type broken");
2407    (void)TypeCheck;
2408  } else
2409    TypeParm = new (*this, TypeAlignment)
2410      TemplateTypeParmType(Depth, Index, ParameterPack);
2411
2412  Types.push_back(TypeParm);
2413  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2414
2415  return QualType(TypeParm, 0);
2416}
2417
2418TypeSourceInfo *
2419ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2420                                              SourceLocation NameLoc,
2421                                        const TemplateArgumentListInfo &Args,
2422                                              QualType Underlying) const {
2423  assert(!Name.getAsDependentTemplateName() &&
2424         "No dependent template names here!");
2425  QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
2426
2427  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2428  TemplateSpecializationTypeLoc TL
2429    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2430  TL.setTemplateKeywordLoc(SourceLocation());
2431  TL.setTemplateNameLoc(NameLoc);
2432  TL.setLAngleLoc(Args.getLAngleLoc());
2433  TL.setRAngleLoc(Args.getRAngleLoc());
2434  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2435    TL.setArgLocInfo(i, Args[i].getLocInfo());
2436  return DI;
2437}
2438
2439QualType
2440ASTContext::getTemplateSpecializationType(TemplateName Template,
2441                                          const TemplateArgumentListInfo &Args,
2442                                          QualType Underlying) const {
2443  assert(!Template.getAsDependentTemplateName() &&
2444         "No dependent template names here!");
2445
2446  unsigned NumArgs = Args.size();
2447
2448  SmallVector<TemplateArgument, 4> ArgVec;
2449  ArgVec.reserve(NumArgs);
2450  for (unsigned i = 0; i != NumArgs; ++i)
2451    ArgVec.push_back(Args[i].getArgument());
2452
2453  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2454                                       Underlying);
2455}
2456
2457#ifndef NDEBUG
2458static bool hasAnyPackExpansions(const TemplateArgument *Args,
2459                                 unsigned NumArgs) {
2460  for (unsigned I = 0; I != NumArgs; ++I)
2461    if (Args[I].isPackExpansion())
2462      return true;
2463
2464  return true;
2465}
2466#endif
2467
2468QualType
2469ASTContext::getTemplateSpecializationType(TemplateName Template,
2470                                          const TemplateArgument *Args,
2471                                          unsigned NumArgs,
2472                                          QualType Underlying) const {
2473  assert(!Template.getAsDependentTemplateName() &&
2474         "No dependent template names here!");
2475  // Look through qualified template names.
2476  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2477    Template = TemplateName(QTN->getTemplateDecl());
2478
2479  bool IsTypeAlias =
2480    Template.getAsTemplateDecl() &&
2481    isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2482  QualType CanonType;
2483  if (!Underlying.isNull())
2484    CanonType = getCanonicalType(Underlying);
2485  else {
2486    // We can get here with an alias template when the specialization contains
2487    // a pack expansion that does not match up with a parameter pack.
2488    assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2489           "Caller must compute aliased type");
2490    IsTypeAlias = false;
2491    CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2492                                                       NumArgs);
2493  }
2494
2495  // Allocate the (non-canonical) template specialization type, but don't
2496  // try to unique it: these types typically have location information that
2497  // we don't unique and don't want to lose.
2498  void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2499                       sizeof(TemplateArgument) * NumArgs +
2500                       (IsTypeAlias? sizeof(QualType) : 0),
2501                       TypeAlignment);
2502  TemplateSpecializationType *Spec
2503    = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2504                                         IsTypeAlias ? Underlying : QualType());
2505
2506  Types.push_back(Spec);
2507  return QualType(Spec, 0);
2508}
2509
2510QualType
2511ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2512                                                   const TemplateArgument *Args,
2513                                                   unsigned NumArgs) const {
2514  assert(!Template.getAsDependentTemplateName() &&
2515         "No dependent template names here!");
2516
2517  // Look through qualified template names.
2518  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2519    Template = TemplateName(QTN->getTemplateDecl());
2520
2521  // Build the canonical template specialization type.
2522  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2523  SmallVector<TemplateArgument, 4> CanonArgs;
2524  CanonArgs.reserve(NumArgs);
2525  for (unsigned I = 0; I != NumArgs; ++I)
2526    CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2527
2528  // Determine whether this canonical template specialization type already
2529  // exists.
2530  llvm::FoldingSetNodeID ID;
2531  TemplateSpecializationType::Profile(ID, CanonTemplate,
2532                                      CanonArgs.data(), NumArgs, *this);
2533
2534  void *InsertPos = 0;
2535  TemplateSpecializationType *Spec
2536    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2537
2538  if (!Spec) {
2539    // Allocate a new canonical template specialization type.
2540    void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2541                          sizeof(TemplateArgument) * NumArgs),
2542                         TypeAlignment);
2543    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2544                                                CanonArgs.data(), NumArgs,
2545                                                QualType(), QualType());
2546    Types.push_back(Spec);
2547    TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2548  }
2549
2550  assert(Spec->isDependentType() &&
2551         "Non-dependent template-id type must have a canonical type");
2552  return QualType(Spec, 0);
2553}
2554
2555QualType
2556ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2557                              NestedNameSpecifier *NNS,
2558                              QualType NamedType) const {
2559  llvm::FoldingSetNodeID ID;
2560  ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2561
2562  void *InsertPos = 0;
2563  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2564  if (T)
2565    return QualType(T, 0);
2566
2567  QualType Canon = NamedType;
2568  if (!Canon.isCanonical()) {
2569    Canon = getCanonicalType(NamedType);
2570    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2571    assert(!CheckT && "Elaborated canonical type broken");
2572    (void)CheckT;
2573  }
2574
2575  T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2576  Types.push_back(T);
2577  ElaboratedTypes.InsertNode(T, InsertPos);
2578  return QualType(T, 0);
2579}
2580
2581QualType
2582ASTContext::getParenType(QualType InnerType) const {
2583  llvm::FoldingSetNodeID ID;
2584  ParenType::Profile(ID, InnerType);
2585
2586  void *InsertPos = 0;
2587  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2588  if (T)
2589    return QualType(T, 0);
2590
2591  QualType Canon = InnerType;
2592  if (!Canon.isCanonical()) {
2593    Canon = getCanonicalType(InnerType);
2594    ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2595    assert(!CheckT && "Paren canonical type broken");
2596    (void)CheckT;
2597  }
2598
2599  T = new (*this) ParenType(InnerType, Canon);
2600  Types.push_back(T);
2601  ParenTypes.InsertNode(T, InsertPos);
2602  return QualType(T, 0);
2603}
2604
2605QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2606                                          NestedNameSpecifier *NNS,
2607                                          const IdentifierInfo *Name,
2608                                          QualType Canon) const {
2609  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2610
2611  if (Canon.isNull()) {
2612    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2613    ElaboratedTypeKeyword CanonKeyword = Keyword;
2614    if (Keyword == ETK_None)
2615      CanonKeyword = ETK_Typename;
2616
2617    if (CanonNNS != NNS || CanonKeyword != Keyword)
2618      Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2619  }
2620
2621  llvm::FoldingSetNodeID ID;
2622  DependentNameType::Profile(ID, Keyword, NNS, Name);
2623
2624  void *InsertPos = 0;
2625  DependentNameType *T
2626    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2627  if (T)
2628    return QualType(T, 0);
2629
2630  T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2631  Types.push_back(T);
2632  DependentNameTypes.InsertNode(T, InsertPos);
2633  return QualType(T, 0);
2634}
2635
2636QualType
2637ASTContext::getDependentTemplateSpecializationType(
2638                                 ElaboratedTypeKeyword Keyword,
2639                                 NestedNameSpecifier *NNS,
2640                                 const IdentifierInfo *Name,
2641                                 const TemplateArgumentListInfo &Args) const {
2642  // TODO: avoid this copy
2643  SmallVector<TemplateArgument, 16> ArgCopy;
2644  for (unsigned I = 0, E = Args.size(); I != E; ++I)
2645    ArgCopy.push_back(Args[I].getArgument());
2646  return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2647                                                ArgCopy.size(),
2648                                                ArgCopy.data());
2649}
2650
2651QualType
2652ASTContext::getDependentTemplateSpecializationType(
2653                                 ElaboratedTypeKeyword Keyword,
2654                                 NestedNameSpecifier *NNS,
2655                                 const IdentifierInfo *Name,
2656                                 unsigned NumArgs,
2657                                 const TemplateArgument *Args) const {
2658  assert((!NNS || NNS->isDependent()) &&
2659         "nested-name-specifier must be dependent");
2660
2661  llvm::FoldingSetNodeID ID;
2662  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2663                                               Name, NumArgs, Args);
2664
2665  void *InsertPos = 0;
2666  DependentTemplateSpecializationType *T
2667    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2668  if (T)
2669    return QualType(T, 0);
2670
2671  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2672
2673  ElaboratedTypeKeyword CanonKeyword = Keyword;
2674  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2675
2676  bool AnyNonCanonArgs = false;
2677  SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2678  for (unsigned I = 0; I != NumArgs; ++I) {
2679    CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2680    if (!CanonArgs[I].structurallyEquals(Args[I]))
2681      AnyNonCanonArgs = true;
2682  }
2683
2684  QualType Canon;
2685  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2686    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2687                                                   Name, NumArgs,
2688                                                   CanonArgs.data());
2689
2690    // Find the insert position again.
2691    DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2692  }
2693
2694  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2695                        sizeof(TemplateArgument) * NumArgs),
2696                       TypeAlignment);
2697  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2698                                                    Name, NumArgs, Args, Canon);
2699  Types.push_back(T);
2700  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2701  return QualType(T, 0);
2702}
2703
2704QualType ASTContext::getPackExpansionType(QualType Pattern,
2705                                      llvm::Optional<unsigned> NumExpansions) {
2706  llvm::FoldingSetNodeID ID;
2707  PackExpansionType::Profile(ID, Pattern, NumExpansions);
2708
2709  assert(Pattern->containsUnexpandedParameterPack() &&
2710         "Pack expansions must expand one or more parameter packs");
2711  void *InsertPos = 0;
2712  PackExpansionType *T
2713    = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2714  if (T)
2715    return QualType(T, 0);
2716
2717  QualType Canon;
2718  if (!Pattern.isCanonical()) {
2719    Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
2720
2721    // Find the insert position again.
2722    PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2723  }
2724
2725  T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
2726  Types.push_back(T);
2727  PackExpansionTypes.InsertNode(T, InsertPos);
2728  return QualType(T, 0);
2729}
2730
2731/// CmpProtocolNames - Comparison predicate for sorting protocols
2732/// alphabetically.
2733static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2734                            const ObjCProtocolDecl *RHS) {
2735  return LHS->getDeclName() < RHS->getDeclName();
2736}
2737
2738static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2739                                unsigned NumProtocols) {
2740  if (NumProtocols == 0) return true;
2741
2742  if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2743    return false;
2744
2745  for (unsigned i = 1; i != NumProtocols; ++i)
2746    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2747        Protocols[i]->getCanonicalDecl() != Protocols[i])
2748      return false;
2749  return true;
2750}
2751
2752static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2753                                   unsigned &NumProtocols) {
2754  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2755
2756  // Sort protocols, keyed by name.
2757  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2758
2759  // Canonicalize.
2760  for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2761    Protocols[I] = Protocols[I]->getCanonicalDecl();
2762
2763  // Remove duplicates.
2764  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2765  NumProtocols = ProtocolsEnd-Protocols;
2766}
2767
2768QualType ASTContext::getObjCObjectType(QualType BaseType,
2769                                       ObjCProtocolDecl * const *Protocols,
2770                                       unsigned NumProtocols) const {
2771  // If the base type is an interface and there aren't any protocols
2772  // to add, then the interface type will do just fine.
2773  if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2774    return BaseType;
2775
2776  // Look in the folding set for an existing type.
2777  llvm::FoldingSetNodeID ID;
2778  ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2779  void *InsertPos = 0;
2780  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2781    return QualType(QT, 0);
2782
2783  // Build the canonical type, which has the canonical base type and
2784  // a sorted-and-uniqued list of protocols.
2785  QualType Canonical;
2786  bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2787  if (!ProtocolsSorted || !BaseType.isCanonical()) {
2788    if (!ProtocolsSorted) {
2789      SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2790                                                     Protocols + NumProtocols);
2791      unsigned UniqueCount = NumProtocols;
2792
2793      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2794      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2795                                    &Sorted[0], UniqueCount);
2796    } else {
2797      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2798                                    Protocols, NumProtocols);
2799    }
2800
2801    // Regenerate InsertPos.
2802    ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2803  }
2804
2805  unsigned Size = sizeof(ObjCObjectTypeImpl);
2806  Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2807  void *Mem = Allocate(Size, TypeAlignment);
2808  ObjCObjectTypeImpl *T =
2809    new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2810
2811  Types.push_back(T);
2812  ObjCObjectTypes.InsertNode(T, InsertPos);
2813  return QualType(T, 0);
2814}
2815
2816/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2817/// the given object type.
2818QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
2819  llvm::FoldingSetNodeID ID;
2820  ObjCObjectPointerType::Profile(ID, ObjectT);
2821
2822  void *InsertPos = 0;
2823  if (ObjCObjectPointerType *QT =
2824              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2825    return QualType(QT, 0);
2826
2827  // Find the canonical object type.
2828  QualType Canonical;
2829  if (!ObjectT.isCanonical()) {
2830    Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2831
2832    // Regenerate InsertPos.
2833    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2834  }
2835
2836  // No match.
2837  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2838  ObjCObjectPointerType *QType =
2839    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2840
2841  Types.push_back(QType);
2842  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2843  return QualType(QType, 0);
2844}
2845
2846/// getObjCInterfaceType - Return the unique reference to the type for the
2847/// specified ObjC interface decl. The list of protocols is optional.
2848QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2849                                          ObjCInterfaceDecl *PrevDecl) const {
2850  if (Decl->TypeForDecl)
2851    return QualType(Decl->TypeForDecl, 0);
2852
2853  if (PrevDecl) {
2854    assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2855    Decl->TypeForDecl = PrevDecl->TypeForDecl;
2856    return QualType(PrevDecl->TypeForDecl, 0);
2857  }
2858
2859  // Prefer the definition, if there is one.
2860  if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2861    Decl = Def;
2862
2863  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2864  ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2865  Decl->TypeForDecl = T;
2866  Types.push_back(T);
2867  return QualType(T, 0);
2868}
2869
2870/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2871/// TypeOfExprType AST's (since expression's are never shared). For example,
2872/// multiple declarations that refer to "typeof(x)" all contain different
2873/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2874/// on canonical type's (which are always unique).
2875QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
2876  TypeOfExprType *toe;
2877  if (tofExpr->isTypeDependent()) {
2878    llvm::FoldingSetNodeID ID;
2879    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2880
2881    void *InsertPos = 0;
2882    DependentTypeOfExprType *Canon
2883      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2884    if (Canon) {
2885      // We already have a "canonical" version of an identical, dependent
2886      // typeof(expr) type. Use that as our canonical type.
2887      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2888                                          QualType((TypeOfExprType*)Canon, 0));
2889    } else {
2890      // Build a new, canonical typeof(expr) type.
2891      Canon
2892        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2893      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2894      toe = Canon;
2895    }
2896  } else {
2897    QualType Canonical = getCanonicalType(tofExpr->getType());
2898    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2899  }
2900  Types.push_back(toe);
2901  return QualType(toe, 0);
2902}
2903
2904/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2905/// TypeOfType AST's. The only motivation to unique these nodes would be
2906/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2907/// an issue. This doesn't effect the type checker, since it operates
2908/// on canonical type's (which are always unique).
2909QualType ASTContext::getTypeOfType(QualType tofType) const {
2910  QualType Canonical = getCanonicalType(tofType);
2911  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2912  Types.push_back(tot);
2913  return QualType(tot, 0);
2914}
2915
2916
2917/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2918/// DecltypeType AST's. The only motivation to unique these nodes would be
2919/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2920/// an issue. This doesn't effect the type checker, since it operates
2921/// on canonical types (which are always unique).
2922QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
2923  DecltypeType *dt;
2924
2925  // C++0x [temp.type]p2:
2926  //   If an expression e involves a template parameter, decltype(e) denotes a
2927  //   unique dependent type. Two such decltype-specifiers refer to the same
2928  //   type only if their expressions are equivalent (14.5.6.1).
2929  if (e->isInstantiationDependent()) {
2930    llvm::FoldingSetNodeID ID;
2931    DependentDecltypeType::Profile(ID, *this, e);
2932
2933    void *InsertPos = 0;
2934    DependentDecltypeType *Canon
2935      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2936    if (Canon) {
2937      // We already have a "canonical" version of an equivalent, dependent
2938      // decltype type. Use that as our canonical type.
2939      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2940                                       QualType((DecltypeType*)Canon, 0));
2941    } else {
2942      // Build a new, canonical typeof(expr) type.
2943      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2944      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2945      dt = Canon;
2946    }
2947  } else {
2948    dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
2949                                      getCanonicalType(UnderlyingType));
2950  }
2951  Types.push_back(dt);
2952  return QualType(dt, 0);
2953}
2954
2955/// getUnaryTransformationType - We don't unique these, since the memory
2956/// savings are minimal and these are rare.
2957QualType ASTContext::getUnaryTransformType(QualType BaseType,
2958                                           QualType UnderlyingType,
2959                                           UnaryTransformType::UTTKind Kind)
2960    const {
2961  UnaryTransformType *Ty =
2962    new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
2963                                                   Kind,
2964                                 UnderlyingType->isDependentType() ?
2965                                 QualType() : getCanonicalType(UnderlyingType));
2966  Types.push_back(Ty);
2967  return QualType(Ty, 0);
2968}
2969
2970/// getAutoType - We only unique auto types after they've been deduced.
2971QualType ASTContext::getAutoType(QualType DeducedType) const {
2972  void *InsertPos = 0;
2973  if (!DeducedType.isNull()) {
2974    // Look in the folding set for an existing type.
2975    llvm::FoldingSetNodeID ID;
2976    AutoType::Profile(ID, DeducedType);
2977    if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
2978      return QualType(AT, 0);
2979  }
2980
2981  AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
2982  Types.push_back(AT);
2983  if (InsertPos)
2984    AutoTypes.InsertNode(AT, InsertPos);
2985  return QualType(AT, 0);
2986}
2987
2988/// getAtomicType - Return the uniqued reference to the atomic type for
2989/// the given value type.
2990QualType ASTContext::getAtomicType(QualType T) const {
2991  // Unique pointers, to guarantee there is only one pointer of a particular
2992  // structure.
2993  llvm::FoldingSetNodeID ID;
2994  AtomicType::Profile(ID, T);
2995
2996  void *InsertPos = 0;
2997  if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
2998    return QualType(AT, 0);
2999
3000  // If the atomic value type isn't canonical, this won't be a canonical type
3001  // either, so fill in the canonical type field.
3002  QualType Canonical;
3003  if (!T.isCanonical()) {
3004    Canonical = getAtomicType(getCanonicalType(T));
3005
3006    // Get the new insert position for the node we care about.
3007    AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3008    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3009  }
3010  AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3011  Types.push_back(New);
3012  AtomicTypes.InsertNode(New, InsertPos);
3013  return QualType(New, 0);
3014}
3015
3016/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3017QualType ASTContext::getAutoDeductType() const {
3018  if (AutoDeductTy.isNull())
3019    AutoDeductTy = getAutoType(QualType());
3020  assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3021  return AutoDeductTy;
3022}
3023
3024/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3025QualType ASTContext::getAutoRRefDeductType() const {
3026  if (AutoRRefDeductTy.isNull())
3027    AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3028  assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3029  return AutoRRefDeductTy;
3030}
3031
3032/// getTagDeclType - Return the unique reference to the type for the
3033/// specified TagDecl (struct/union/class/enum) decl.
3034QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3035  assert (Decl);
3036  // FIXME: What is the design on getTagDeclType when it requires casting
3037  // away const?  mutable?
3038  return getTypeDeclType(const_cast<TagDecl*>(Decl));
3039}
3040
3041/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3042/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3043/// needs to agree with the definition in <stddef.h>.
3044CanQualType ASTContext::getSizeType() const {
3045  return getFromTargetType(Target->getSizeType());
3046}
3047
3048/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3049CanQualType ASTContext::getIntMaxType() const {
3050  return getFromTargetType(Target->getIntMaxType());
3051}
3052
3053/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3054CanQualType ASTContext::getUIntMaxType() const {
3055  return getFromTargetType(Target->getUIntMaxType());
3056}
3057
3058/// getSignedWCharType - Return the type of "signed wchar_t".
3059/// Used when in C++, as a GCC extension.
3060QualType ASTContext::getSignedWCharType() const {
3061  // FIXME: derive from "Target" ?
3062  return WCharTy;
3063}
3064
3065/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3066/// Used when in C++, as a GCC extension.
3067QualType ASTContext::getUnsignedWCharType() const {
3068  // FIXME: derive from "Target" ?
3069  return UnsignedIntTy;
3070}
3071
3072/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3073/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3074QualType ASTContext::getPointerDiffType() const {
3075  return getFromTargetType(Target->getPtrDiffType(0));
3076}
3077
3078//===----------------------------------------------------------------------===//
3079//                              Type Operators
3080//===----------------------------------------------------------------------===//
3081
3082CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3083  // Push qualifiers into arrays, and then discard any remaining
3084  // qualifiers.
3085  T = getCanonicalType(T);
3086  T = getVariableArrayDecayedType(T);
3087  const Type *Ty = T.getTypePtr();
3088  QualType Result;
3089  if (isa<ArrayType>(Ty)) {
3090    Result = getArrayDecayedType(QualType(Ty,0));
3091  } else if (isa<FunctionType>(Ty)) {
3092    Result = getPointerType(QualType(Ty, 0));
3093  } else {
3094    Result = QualType(Ty, 0);
3095  }
3096
3097  return CanQualType::CreateUnsafe(Result);
3098}
3099
3100QualType ASTContext::getUnqualifiedArrayType(QualType type,
3101                                             Qualifiers &quals) {
3102  SplitQualType splitType = type.getSplitUnqualifiedType();
3103
3104  // FIXME: getSplitUnqualifiedType() actually walks all the way to
3105  // the unqualified desugared type and then drops it on the floor.
3106  // We then have to strip that sugar back off with
3107  // getUnqualifiedDesugaredType(), which is silly.
3108  const ArrayType *AT =
3109    dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3110
3111  // If we don't have an array, just use the results in splitType.
3112  if (!AT) {
3113    quals = splitType.Quals;
3114    return QualType(splitType.Ty, 0);
3115  }
3116
3117  // Otherwise, recurse on the array's element type.
3118  QualType elementType = AT->getElementType();
3119  QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3120
3121  // If that didn't change the element type, AT has no qualifiers, so we
3122  // can just use the results in splitType.
3123  if (elementType == unqualElementType) {
3124    assert(quals.empty()); // from the recursive call
3125    quals = splitType.Quals;
3126    return QualType(splitType.Ty, 0);
3127  }
3128
3129  // Otherwise, add in the qualifiers from the outermost type, then
3130  // build the type back up.
3131  quals.addConsistentQualifiers(splitType.Quals);
3132
3133  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3134    return getConstantArrayType(unqualElementType, CAT->getSize(),
3135                                CAT->getSizeModifier(), 0);
3136  }
3137
3138  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3139    return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3140  }
3141
3142  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3143    return getVariableArrayType(unqualElementType,
3144                                VAT->getSizeExpr(),
3145                                VAT->getSizeModifier(),
3146                                VAT->getIndexTypeCVRQualifiers(),
3147                                VAT->getBracketsRange());
3148  }
3149
3150  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3151  return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3152                                    DSAT->getSizeModifier(), 0,
3153                                    SourceRange());
3154}
3155
3156/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
3157/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3158/// they point to and return true. If T1 and T2 aren't pointer types
3159/// or pointer-to-member types, or if they are not similar at this
3160/// level, returns false and leaves T1 and T2 unchanged. Top-level
3161/// qualifiers on T1 and T2 are ignored. This function will typically
3162/// be called in a loop that successively "unwraps" pointer and
3163/// pointer-to-member types to compare them at each level.
3164bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3165  const PointerType *T1PtrType = T1->getAs<PointerType>(),
3166                    *T2PtrType = T2->getAs<PointerType>();
3167  if (T1PtrType && T2PtrType) {
3168    T1 = T1PtrType->getPointeeType();
3169    T2 = T2PtrType->getPointeeType();
3170    return true;
3171  }
3172
3173  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3174                          *T2MPType = T2->getAs<MemberPointerType>();
3175  if (T1MPType && T2MPType &&
3176      hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3177                             QualType(T2MPType->getClass(), 0))) {
3178    T1 = T1MPType->getPointeeType();
3179    T2 = T2MPType->getPointeeType();
3180    return true;
3181  }
3182
3183  if (getLangOptions().ObjC1) {
3184    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3185                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
3186    if (T1OPType && T2OPType) {
3187      T1 = T1OPType->getPointeeType();
3188      T2 = T2OPType->getPointeeType();
3189      return true;
3190    }
3191  }
3192
3193  // FIXME: Block pointers, too?
3194
3195  return false;
3196}
3197
3198DeclarationNameInfo
3199ASTContext::getNameForTemplate(TemplateName Name,
3200                               SourceLocation NameLoc) const {
3201  switch (Name.getKind()) {
3202  case TemplateName::QualifiedTemplate:
3203  case TemplateName::Template:
3204    // DNInfo work in progress: CHECKME: what about DNLoc?
3205    return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3206                               NameLoc);
3207
3208  case TemplateName::OverloadedTemplate: {
3209    OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3210    // DNInfo work in progress: CHECKME: what about DNLoc?
3211    return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3212  }
3213
3214  case TemplateName::DependentTemplate: {
3215    DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3216    DeclarationName DName;
3217    if (DTN->isIdentifier()) {
3218      DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3219      return DeclarationNameInfo(DName, NameLoc);
3220    } else {
3221      DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3222      // DNInfo work in progress: FIXME: source locations?
3223      DeclarationNameLoc DNLoc;
3224      DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3225      DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3226      return DeclarationNameInfo(DName, NameLoc, DNLoc);
3227    }
3228  }
3229
3230  case TemplateName::SubstTemplateTemplateParm: {
3231    SubstTemplateTemplateParmStorage *subst
3232      = Name.getAsSubstTemplateTemplateParm();
3233    return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3234                               NameLoc);
3235  }
3236
3237  case TemplateName::SubstTemplateTemplateParmPack: {
3238    SubstTemplateTemplateParmPackStorage *subst
3239      = Name.getAsSubstTemplateTemplateParmPack();
3240    return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3241                               NameLoc);
3242  }
3243  }
3244
3245  llvm_unreachable("bad template name kind!");
3246}
3247
3248TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3249  switch (Name.getKind()) {
3250  case TemplateName::QualifiedTemplate:
3251  case TemplateName::Template: {
3252    TemplateDecl *Template = Name.getAsTemplateDecl();
3253    if (TemplateTemplateParmDecl *TTP
3254          = dyn_cast<TemplateTemplateParmDecl>(Template))
3255      Template = getCanonicalTemplateTemplateParmDecl(TTP);
3256
3257    // The canonical template name is the canonical template declaration.
3258    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3259  }
3260
3261  case TemplateName::OverloadedTemplate:
3262    llvm_unreachable("cannot canonicalize overloaded template");
3263
3264  case TemplateName::DependentTemplate: {
3265    DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3266    assert(DTN && "Non-dependent template names must refer to template decls.");
3267    return DTN->CanonicalTemplateName;
3268  }
3269
3270  case TemplateName::SubstTemplateTemplateParm: {
3271    SubstTemplateTemplateParmStorage *subst
3272      = Name.getAsSubstTemplateTemplateParm();
3273    return getCanonicalTemplateName(subst->getReplacement());
3274  }
3275
3276  case TemplateName::SubstTemplateTemplateParmPack: {
3277    SubstTemplateTemplateParmPackStorage *subst
3278                                  = Name.getAsSubstTemplateTemplateParmPack();
3279    TemplateTemplateParmDecl *canonParameter
3280      = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3281    TemplateArgument canonArgPack
3282      = getCanonicalTemplateArgument(subst->getArgumentPack());
3283    return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3284  }
3285  }
3286
3287  llvm_unreachable("bad template name!");
3288}
3289
3290bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3291  X = getCanonicalTemplateName(X);
3292  Y = getCanonicalTemplateName(Y);
3293  return X.getAsVoidPointer() == Y.getAsVoidPointer();
3294}
3295
3296TemplateArgument
3297ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
3298  switch (Arg.getKind()) {
3299    case TemplateArgument::Null:
3300      return Arg;
3301
3302    case TemplateArgument::Expression:
3303      return Arg;
3304
3305    case TemplateArgument::Declaration:
3306      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
3307
3308    case TemplateArgument::Template:
3309      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
3310
3311    case TemplateArgument::TemplateExpansion:
3312      return TemplateArgument(getCanonicalTemplateName(
3313                                         Arg.getAsTemplateOrTemplatePattern()),
3314                              Arg.getNumTemplateExpansions());
3315
3316    case TemplateArgument::Integral:
3317      return TemplateArgument(*Arg.getAsIntegral(),
3318                              getCanonicalType(Arg.getIntegralType()));
3319
3320    case TemplateArgument::Type:
3321      return TemplateArgument(getCanonicalType(Arg.getAsType()));
3322
3323    case TemplateArgument::Pack: {
3324      if (Arg.pack_size() == 0)
3325        return Arg;
3326
3327      TemplateArgument *CanonArgs
3328        = new (*this) TemplateArgument[Arg.pack_size()];
3329      unsigned Idx = 0;
3330      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
3331                                        AEnd = Arg.pack_end();
3332           A != AEnd; (void)++A, ++Idx)
3333        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
3334
3335      return TemplateArgument(CanonArgs, Arg.pack_size());
3336    }
3337  }
3338
3339  // Silence GCC warning
3340  llvm_unreachable("Unhandled template argument kind");
3341}
3342
3343NestedNameSpecifier *
3344ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
3345  if (!NNS)
3346    return 0;
3347
3348  switch (NNS->getKind()) {
3349  case NestedNameSpecifier::Identifier:
3350    // Canonicalize the prefix but keep the identifier the same.
3351    return NestedNameSpecifier::Create(*this,
3352                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3353                                       NNS->getAsIdentifier());
3354
3355  case NestedNameSpecifier::Namespace:
3356    // A namespace is canonical; build a nested-name-specifier with
3357    // this namespace and no prefix.
3358    return NestedNameSpecifier::Create(*this, 0,
3359                                 NNS->getAsNamespace()->getOriginalNamespace());
3360
3361  case NestedNameSpecifier::NamespaceAlias:
3362    // A namespace is canonical; build a nested-name-specifier with
3363    // this namespace and no prefix.
3364    return NestedNameSpecifier::Create(*this, 0,
3365                                    NNS->getAsNamespaceAlias()->getNamespace()
3366                                                      ->getOriginalNamespace());
3367
3368  case NestedNameSpecifier::TypeSpec:
3369  case NestedNameSpecifier::TypeSpecWithTemplate: {
3370    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
3371
3372    // If we have some kind of dependent-named type (e.g., "typename T::type"),
3373    // break it apart into its prefix and identifier, then reconsititute those
3374    // as the canonical nested-name-specifier. This is required to canonicalize
3375    // a dependent nested-name-specifier involving typedefs of dependent-name
3376    // types, e.g.,
3377    //   typedef typename T::type T1;
3378    //   typedef typename T1::type T2;
3379    if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3380      return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
3381                           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3382
3383    // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3384    // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3385    // first place?
3386    return NestedNameSpecifier::Create(*this, 0, false,
3387                                       const_cast<Type*>(T.getTypePtr()));
3388  }
3389
3390  case NestedNameSpecifier::Global:
3391    // The global specifier is canonical and unique.
3392    return NNS;
3393  }
3394
3395  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
3396}
3397
3398
3399const ArrayType *ASTContext::getAsArrayType(QualType T) const {
3400  // Handle the non-qualified case efficiently.
3401  if (!T.hasLocalQualifiers()) {
3402    // Handle the common positive case fast.
3403    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3404      return AT;
3405  }
3406
3407  // Handle the common negative case fast.
3408  if (!isa<ArrayType>(T.getCanonicalType()))
3409    return 0;
3410
3411  // Apply any qualifiers from the array type to the element type.  This
3412  // implements C99 6.7.3p8: "If the specification of an array type includes
3413  // any type qualifiers, the element type is so qualified, not the array type."
3414
3415  // If we get here, we either have type qualifiers on the type, or we have
3416  // sugar such as a typedef in the way.  If we have type qualifiers on the type
3417  // we must propagate them down into the element type.
3418
3419  SplitQualType split = T.getSplitDesugaredType();
3420  Qualifiers qs = split.Quals;
3421
3422  // If we have a simple case, just return now.
3423  const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
3424  if (ATy == 0 || qs.empty())
3425    return ATy;
3426
3427  // Otherwise, we have an array and we have qualifiers on it.  Push the
3428  // qualifiers into the array element type and return a new array type.
3429  QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
3430
3431  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3432    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3433                                                CAT->getSizeModifier(),
3434                                           CAT->getIndexTypeCVRQualifiers()));
3435  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3436    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3437                                                  IAT->getSizeModifier(),
3438                                           IAT->getIndexTypeCVRQualifiers()));
3439
3440  if (const DependentSizedArrayType *DSAT
3441        = dyn_cast<DependentSizedArrayType>(ATy))
3442    return cast<ArrayType>(
3443                     getDependentSizedArrayType(NewEltTy,
3444                                                DSAT->getSizeExpr(),
3445                                                DSAT->getSizeModifier(),
3446                                              DSAT->getIndexTypeCVRQualifiers(),
3447                                                DSAT->getBracketsRange()));
3448
3449  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
3450  return cast<ArrayType>(getVariableArrayType(NewEltTy,
3451                                              VAT->getSizeExpr(),
3452                                              VAT->getSizeModifier(),
3453                                              VAT->getIndexTypeCVRQualifiers(),
3454                                              VAT->getBracketsRange()));
3455}
3456
3457QualType ASTContext::getAdjustedParameterType(QualType T) {
3458  // C99 6.7.5.3p7:
3459  //   A declaration of a parameter as "array of type" shall be
3460  //   adjusted to "qualified pointer to type", where the type
3461  //   qualifiers (if any) are those specified within the [ and ] of
3462  //   the array type derivation.
3463  if (T->isArrayType())
3464    return getArrayDecayedType(T);
3465
3466  // C99 6.7.5.3p8:
3467  //   A declaration of a parameter as "function returning type"
3468  //   shall be adjusted to "pointer to function returning type", as
3469  //   in 6.3.2.1.
3470  if (T->isFunctionType())
3471    return getPointerType(T);
3472
3473  return T;
3474}
3475
3476QualType ASTContext::getSignatureParameterType(QualType T) {
3477  T = getVariableArrayDecayedType(T);
3478  T = getAdjustedParameterType(T);
3479  return T.getUnqualifiedType();
3480}
3481
3482/// getArrayDecayedType - Return the properly qualified result of decaying the
3483/// specified array type to a pointer.  This operation is non-trivial when
3484/// handling typedefs etc.  The canonical type of "T" must be an array type,
3485/// this returns a pointer to a properly qualified element of the array.
3486///
3487/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
3488QualType ASTContext::getArrayDecayedType(QualType Ty) const {
3489  // Get the element type with 'getAsArrayType' so that we don't lose any
3490  // typedefs in the element type of the array.  This also handles propagation
3491  // of type qualifiers from the array type into the element type if present
3492  // (C99 6.7.3p8).
3493  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3494  assert(PrettyArrayType && "Not an array type!");
3495
3496  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
3497
3498  // int x[restrict 4] ->  int *restrict
3499  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
3500}
3501
3502QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3503  return getBaseElementType(array->getElementType());
3504}
3505
3506QualType ASTContext::getBaseElementType(QualType type) const {
3507  Qualifiers qs;
3508  while (true) {
3509    SplitQualType split = type.getSplitDesugaredType();
3510    const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
3511    if (!array) break;
3512
3513    type = array->getElementType();
3514    qs.addConsistentQualifiers(split.Quals);
3515  }
3516
3517  return getQualifiedType(type, qs);
3518}
3519
3520/// getConstantArrayElementCount - Returns number of constant array elements.
3521uint64_t
3522ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
3523  uint64_t ElementCount = 1;
3524  do {
3525    ElementCount *= CA->getSize().getZExtValue();
3526    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3527  } while (CA);
3528  return ElementCount;
3529}
3530
3531/// getFloatingRank - Return a relative rank for floating point types.
3532/// This routine will assert if passed a built-in type that isn't a float.
3533static FloatingRank getFloatingRank(QualType T) {
3534  if (const ComplexType *CT = T->getAs<ComplexType>())
3535    return getFloatingRank(CT->getElementType());
3536
3537  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3538  switch (T->getAs<BuiltinType>()->getKind()) {
3539  default: llvm_unreachable("getFloatingRank(): not a floating type");
3540  case BuiltinType::Half:       return HalfRank;
3541  case BuiltinType::Float:      return FloatRank;
3542  case BuiltinType::Double:     return DoubleRank;
3543  case BuiltinType::LongDouble: return LongDoubleRank;
3544  }
3545}
3546
3547/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3548/// point or a complex type (based on typeDomain/typeSize).
3549/// 'typeDomain' is a real floating point or complex type.
3550/// 'typeSize' is a real floating point or complex type.
3551QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3552                                                       QualType Domain) const {
3553  FloatingRank EltRank = getFloatingRank(Size);
3554  if (Domain->isComplexType()) {
3555    switch (EltRank) {
3556    case HalfRank: llvm_unreachable("Complex half is not supported");
3557    case FloatRank:      return FloatComplexTy;
3558    case DoubleRank:     return DoubleComplexTy;
3559    case LongDoubleRank: return LongDoubleComplexTy;
3560    }
3561  }
3562
3563  assert(Domain->isRealFloatingType() && "Unknown domain!");
3564  switch (EltRank) {
3565  case HalfRank: llvm_unreachable("Half ranks are not valid here");
3566  case FloatRank:      return FloatTy;
3567  case DoubleRank:     return DoubleTy;
3568  case LongDoubleRank: return LongDoubleTy;
3569  }
3570  llvm_unreachable("getFloatingRank(): illegal value for rank");
3571}
3572
3573/// getFloatingTypeOrder - Compare the rank of the two specified floating
3574/// point types, ignoring the domain of the type (i.e. 'double' ==
3575/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3576/// LHS < RHS, return -1.
3577int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
3578  FloatingRank LHSR = getFloatingRank(LHS);
3579  FloatingRank RHSR = getFloatingRank(RHS);
3580
3581  if (LHSR == RHSR)
3582    return 0;
3583  if (LHSR > RHSR)
3584    return 1;
3585  return -1;
3586}
3587
3588/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3589/// routine will assert if passed a built-in type that isn't an integer or enum,
3590/// or if it is not canonicalized.
3591unsigned ASTContext::getIntegerRank(const Type *T) const {
3592  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
3593
3594  switch (cast<BuiltinType>(T)->getKind()) {
3595  default: llvm_unreachable("getIntegerRank(): not a built-in integer");
3596  case BuiltinType::Bool:
3597    return 1 + (getIntWidth(BoolTy) << 3);
3598  case BuiltinType::Char_S:
3599  case BuiltinType::Char_U:
3600  case BuiltinType::SChar:
3601  case BuiltinType::UChar:
3602    return 2 + (getIntWidth(CharTy) << 3);
3603  case BuiltinType::Short:
3604  case BuiltinType::UShort:
3605    return 3 + (getIntWidth(ShortTy) << 3);
3606  case BuiltinType::Int:
3607  case BuiltinType::UInt:
3608    return 4 + (getIntWidth(IntTy) << 3);
3609  case BuiltinType::Long:
3610  case BuiltinType::ULong:
3611    return 5 + (getIntWidth(LongTy) << 3);
3612  case BuiltinType::LongLong:
3613  case BuiltinType::ULongLong:
3614    return 6 + (getIntWidth(LongLongTy) << 3);
3615  case BuiltinType::Int128:
3616  case BuiltinType::UInt128:
3617    return 7 + (getIntWidth(Int128Ty) << 3);
3618  }
3619}
3620
3621/// \brief Whether this is a promotable bitfield reference according
3622/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3623///
3624/// \returns the type this bit-field will promote to, or NULL if no
3625/// promotion occurs.
3626QualType ASTContext::isPromotableBitField(Expr *E) const {
3627  if (E->isTypeDependent() || E->isValueDependent())
3628    return QualType();
3629
3630  FieldDecl *Field = E->getBitField();
3631  if (!Field)
3632    return QualType();
3633
3634  QualType FT = Field->getType();
3635
3636  uint64_t BitWidth = Field->getBitWidthValue(*this);
3637  uint64_t IntSize = getTypeSize(IntTy);
3638  // GCC extension compatibility: if the bit-field size is less than or equal
3639  // to the size of int, it gets promoted no matter what its type is.
3640  // For instance, unsigned long bf : 4 gets promoted to signed int.
3641  if (BitWidth < IntSize)
3642    return IntTy;
3643
3644  if (BitWidth == IntSize)
3645    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3646
3647  // Types bigger than int are not subject to promotions, and therefore act
3648  // like the base type.
3649  // FIXME: This doesn't quite match what gcc does, but what gcc does here
3650  // is ridiculous.
3651  return QualType();
3652}
3653
3654/// getPromotedIntegerType - Returns the type that Promotable will
3655/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3656/// integer type.
3657QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
3658  assert(!Promotable.isNull());
3659  assert(Promotable->isPromotableIntegerType());
3660  if (const EnumType *ET = Promotable->getAs<EnumType>())
3661    return ET->getDecl()->getPromotionType();
3662
3663  if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3664    // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3665    // (3.9.1) can be converted to a prvalue of the first of the following
3666    // types that can represent all the values of its underlying type:
3667    // int, unsigned int, long int, unsigned long int, long long int, or
3668    // unsigned long long int [...]
3669    // FIXME: Is there some better way to compute this?
3670    if (BT->getKind() == BuiltinType::WChar_S ||
3671        BT->getKind() == BuiltinType::WChar_U ||
3672        BT->getKind() == BuiltinType::Char16 ||
3673        BT->getKind() == BuiltinType::Char32) {
3674      bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3675      uint64_t FromSize = getTypeSize(BT);
3676      QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3677                                  LongLongTy, UnsignedLongLongTy };
3678      for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3679        uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3680        if (FromSize < ToSize ||
3681            (FromSize == ToSize &&
3682             FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3683          return PromoteTypes[Idx];
3684      }
3685      llvm_unreachable("char type should fit into long long");
3686    }
3687  }
3688
3689  // At this point, we should have a signed or unsigned integer type.
3690  if (Promotable->isSignedIntegerType())
3691    return IntTy;
3692  uint64_t PromotableSize = getTypeSize(Promotable);
3693  uint64_t IntSize = getTypeSize(IntTy);
3694  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3695  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3696}
3697
3698/// \brief Recurses in pointer/array types until it finds an objc retainable
3699/// type and returns its ownership.
3700Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3701  while (!T.isNull()) {
3702    if (T.getObjCLifetime() != Qualifiers::OCL_None)
3703      return T.getObjCLifetime();
3704    if (T->isArrayType())
3705      T = getBaseElementType(T);
3706    else if (const PointerType *PT = T->getAs<PointerType>())
3707      T = PT->getPointeeType();
3708    else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3709      T = RT->getPointeeType();
3710    else
3711      break;
3712  }
3713
3714  return Qualifiers::OCL_None;
3715}
3716
3717/// getIntegerTypeOrder - Returns the highest ranked integer type:
3718/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3719/// LHS < RHS, return -1.
3720int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
3721  const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3722  const Type *RHSC = getCanonicalType(RHS).getTypePtr();
3723  if (LHSC == RHSC) return 0;
3724
3725  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3726  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3727
3728  unsigned LHSRank = getIntegerRank(LHSC);
3729  unsigned RHSRank = getIntegerRank(RHSC);
3730
3731  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
3732    if (LHSRank == RHSRank) return 0;
3733    return LHSRank > RHSRank ? 1 : -1;
3734  }
3735
3736  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3737  if (LHSUnsigned) {
3738    // If the unsigned [LHS] type is larger, return it.
3739    if (LHSRank >= RHSRank)
3740      return 1;
3741
3742    // If the signed type can represent all values of the unsigned type, it
3743    // wins.  Because we are dealing with 2's complement and types that are
3744    // powers of two larger than each other, this is always safe.
3745    return -1;
3746  }
3747
3748  // If the unsigned [RHS] type is larger, return it.
3749  if (RHSRank >= LHSRank)
3750    return -1;
3751
3752  // If the signed type can represent all values of the unsigned type, it
3753  // wins.  Because we are dealing with 2's complement and types that are
3754  // powers of two larger than each other, this is always safe.
3755  return 1;
3756}
3757
3758static RecordDecl *
3759CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3760                 DeclContext *DC, IdentifierInfo *Id) {
3761  SourceLocation Loc;
3762  if (Ctx.getLangOptions().CPlusPlus)
3763    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3764  else
3765    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3766}
3767
3768// getCFConstantStringType - Return the type used for constant CFStrings.
3769QualType ASTContext::getCFConstantStringType() const {
3770  if (!CFConstantStringTypeDecl) {
3771    CFConstantStringTypeDecl =
3772      CreateRecordDecl(*this, TTK_Struct, TUDecl,
3773                       &Idents.get("NSConstantString"));
3774    CFConstantStringTypeDecl->startDefinition();
3775
3776    QualType FieldTypes[4];
3777
3778    // const int *isa;
3779    FieldTypes[0] = getPointerType(IntTy.withConst());
3780    // int flags;
3781    FieldTypes[1] = IntTy;
3782    // const char *str;
3783    FieldTypes[2] = getPointerType(CharTy.withConst());
3784    // long length;
3785    FieldTypes[3] = LongTy;
3786
3787    // Create fields
3788    for (unsigned i = 0; i < 4; ++i) {
3789      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3790                                           SourceLocation(),
3791                                           SourceLocation(), 0,
3792                                           FieldTypes[i], /*TInfo=*/0,
3793                                           /*BitWidth=*/0,
3794                                           /*Mutable=*/false,
3795                                           /*HasInit=*/false);
3796      Field->setAccess(AS_public);
3797      CFConstantStringTypeDecl->addDecl(Field);
3798    }
3799
3800    CFConstantStringTypeDecl->completeDefinition();
3801  }
3802
3803  return getTagDeclType(CFConstantStringTypeDecl);
3804}
3805
3806void ASTContext::setCFConstantStringType(QualType T) {
3807  const RecordType *Rec = T->getAs<RecordType>();
3808  assert(Rec && "Invalid CFConstantStringType");
3809  CFConstantStringTypeDecl = Rec->getDecl();
3810}
3811
3812QualType ASTContext::getBlockDescriptorType() const {
3813  if (BlockDescriptorType)
3814    return getTagDeclType(BlockDescriptorType);
3815
3816  RecordDecl *T;
3817  // FIXME: Needs the FlagAppleBlock bit.
3818  T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3819                       &Idents.get("__block_descriptor"));
3820  T->startDefinition();
3821
3822  QualType FieldTypes[] = {
3823    UnsignedLongTy,
3824    UnsignedLongTy,
3825  };
3826
3827  const char *FieldNames[] = {
3828    "reserved",
3829    "Size"
3830  };
3831
3832  for (size_t i = 0; i < 2; ++i) {
3833    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3834                                         SourceLocation(),
3835                                         &Idents.get(FieldNames[i]),
3836                                         FieldTypes[i], /*TInfo=*/0,
3837                                         /*BitWidth=*/0,
3838                                         /*Mutable=*/false,
3839                                         /*HasInit=*/false);
3840    Field->setAccess(AS_public);
3841    T->addDecl(Field);
3842  }
3843
3844  T->completeDefinition();
3845
3846  BlockDescriptorType = T;
3847
3848  return getTagDeclType(BlockDescriptorType);
3849}
3850
3851QualType ASTContext::getBlockDescriptorExtendedType() const {
3852  if (BlockDescriptorExtendedType)
3853    return getTagDeclType(BlockDescriptorExtendedType);
3854
3855  RecordDecl *T;
3856  // FIXME: Needs the FlagAppleBlock bit.
3857  T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3858                       &Idents.get("__block_descriptor_withcopydispose"));
3859  T->startDefinition();
3860
3861  QualType FieldTypes[] = {
3862    UnsignedLongTy,
3863    UnsignedLongTy,
3864    getPointerType(VoidPtrTy),
3865    getPointerType(VoidPtrTy)
3866  };
3867
3868  const char *FieldNames[] = {
3869    "reserved",
3870    "Size",
3871    "CopyFuncPtr",
3872    "DestroyFuncPtr"
3873  };
3874
3875  for (size_t i = 0; i < 4; ++i) {
3876    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3877                                         SourceLocation(),
3878                                         &Idents.get(FieldNames[i]),
3879                                         FieldTypes[i], /*TInfo=*/0,
3880                                         /*BitWidth=*/0,
3881                                         /*Mutable=*/false,
3882                                         /*HasInit=*/false);
3883    Field->setAccess(AS_public);
3884    T->addDecl(Field);
3885  }
3886
3887  T->completeDefinition();
3888
3889  BlockDescriptorExtendedType = T;
3890
3891  return getTagDeclType(BlockDescriptorExtendedType);
3892}
3893
3894bool ASTContext::BlockRequiresCopying(QualType Ty) const {
3895  if (Ty->isObjCRetainableType())
3896    return true;
3897  if (getLangOptions().CPlusPlus) {
3898    if (const RecordType *RT = Ty->getAs<RecordType>()) {
3899      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3900      return RD->hasConstCopyConstructor();
3901
3902    }
3903  }
3904  return false;
3905}
3906
3907QualType
3908ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
3909  //  type = struct __Block_byref_1_X {
3910  //    void *__isa;
3911  //    struct __Block_byref_1_X *__forwarding;
3912  //    unsigned int __flags;
3913  //    unsigned int __size;
3914  //    void *__copy_helper;            // as needed
3915  //    void *__destroy_help            // as needed
3916  //    int X;
3917  //  } *
3918
3919  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3920
3921  // FIXME: Move up
3922  SmallString<36> Name;
3923  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3924                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3925  RecordDecl *T;
3926  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
3927  T->startDefinition();
3928  QualType Int32Ty = IntTy;
3929  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3930  QualType FieldTypes[] = {
3931    getPointerType(VoidPtrTy),
3932    getPointerType(getTagDeclType(T)),
3933    Int32Ty,
3934    Int32Ty,
3935    getPointerType(VoidPtrTy),
3936    getPointerType(VoidPtrTy),
3937    Ty
3938  };
3939
3940  StringRef FieldNames[] = {
3941    "__isa",
3942    "__forwarding",
3943    "__flags",
3944    "__size",
3945    "__copy_helper",
3946    "__destroy_helper",
3947    DeclName,
3948  };
3949
3950  for (size_t i = 0; i < 7; ++i) {
3951    if (!HasCopyAndDispose && i >=4 && i <= 5)
3952      continue;
3953    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3954                                         SourceLocation(),
3955                                         &Idents.get(FieldNames[i]),
3956                                         FieldTypes[i], /*TInfo=*/0,
3957                                         /*BitWidth=*/0, /*Mutable=*/false,
3958                                         /*HasInit=*/false);
3959    Field->setAccess(AS_public);
3960    T->addDecl(Field);
3961  }
3962
3963  T->completeDefinition();
3964
3965  return getPointerType(getTagDeclType(T));
3966}
3967
3968TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
3969  if (!ObjCInstanceTypeDecl)
3970    ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
3971                                               getTranslationUnitDecl(),
3972                                               SourceLocation(),
3973                                               SourceLocation(),
3974                                               &Idents.get("instancetype"),
3975                                     getTrivialTypeSourceInfo(getObjCIdType()));
3976  return ObjCInstanceTypeDecl;
3977}
3978
3979// This returns true if a type has been typedefed to BOOL:
3980// typedef <type> BOOL;
3981static bool isTypeTypedefedAsBOOL(QualType T) {
3982  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3983    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3984      return II->isStr("BOOL");
3985
3986  return false;
3987}
3988
3989/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3990/// purpose.
3991CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
3992  if (!type->isIncompleteArrayType() && type->isIncompleteType())
3993    return CharUnits::Zero();
3994
3995  CharUnits sz = getTypeSizeInChars(type);
3996
3997  // Make all integer and enum types at least as large as an int
3998  if (sz.isPositive() && type->isIntegralOrEnumerationType())
3999    sz = std::max(sz, getTypeSizeInChars(IntTy));
4000  // Treat arrays as pointers, since that's how they're passed in.
4001  else if (type->isArrayType())
4002    sz = getTypeSizeInChars(VoidPtrTy);
4003  return sz;
4004}
4005
4006static inline
4007std::string charUnitsToString(const CharUnits &CU) {
4008  return llvm::itostr(CU.getQuantity());
4009}
4010
4011/// getObjCEncodingForBlock - Return the encoded type for this block
4012/// declaration.
4013std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4014  std::string S;
4015
4016  const BlockDecl *Decl = Expr->getBlockDecl();
4017  QualType BlockTy =
4018      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4019  // Encode result type.
4020  getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
4021  // Compute size of all parameters.
4022  // Start with computing size of a pointer in number of bytes.
4023  // FIXME: There might(should) be a better way of doing this computation!
4024  SourceLocation Loc;
4025  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4026  CharUnits ParmOffset = PtrSize;
4027  for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
4028       E = Decl->param_end(); PI != E; ++PI) {
4029    QualType PType = (*PI)->getType();
4030    CharUnits sz = getObjCEncodingTypeSize(PType);
4031    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4032    ParmOffset += sz;
4033  }
4034  // Size of the argument frame
4035  S += charUnitsToString(ParmOffset);
4036  // Block pointer and offset.
4037  S += "@?0";
4038
4039  // Argument types.
4040  ParmOffset = PtrSize;
4041  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4042       Decl->param_end(); PI != E; ++PI) {
4043    ParmVarDecl *PVDecl = *PI;
4044    QualType PType = PVDecl->getOriginalType();
4045    if (const ArrayType *AT =
4046          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4047      // Use array's original type only if it has known number of
4048      // elements.
4049      if (!isa<ConstantArrayType>(AT))
4050        PType = PVDecl->getType();
4051    } else if (PType->isFunctionType())
4052      PType = PVDecl->getType();
4053    getObjCEncodingForType(PType, S);
4054    S += charUnitsToString(ParmOffset);
4055    ParmOffset += getObjCEncodingTypeSize(PType);
4056  }
4057
4058  return S;
4059}
4060
4061bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4062                                                std::string& S) {
4063  // Encode result type.
4064  getObjCEncodingForType(Decl->getResultType(), S);
4065  CharUnits ParmOffset;
4066  // Compute size of all parameters.
4067  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4068       E = Decl->param_end(); PI != E; ++PI) {
4069    QualType PType = (*PI)->getType();
4070    CharUnits sz = getObjCEncodingTypeSize(PType);
4071    if (sz.isZero())
4072      return true;
4073
4074    assert (sz.isPositive() &&
4075        "getObjCEncodingForFunctionDecl - Incomplete param type");
4076    ParmOffset += sz;
4077  }
4078  S += charUnitsToString(ParmOffset);
4079  ParmOffset = CharUnits::Zero();
4080
4081  // Argument types.
4082  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4083       E = 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 false;
4100}
4101
4102/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4103/// method parameter or return type. If Extended, include class names and
4104/// block object types.
4105void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4106                                                   QualType T, std::string& S,
4107                                                   bool Extended) const {
4108  // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4109  getObjCEncodingForTypeQualifier(QT, S);
4110  // Encode parameter type.
4111  getObjCEncodingForTypeImpl(T, S, true, true, 0,
4112                             true     /*OutermostType*/,
4113                             false    /*EncodingProperty*/,
4114                             false    /*StructField*/,
4115                             Extended /*EncodeBlockParameters*/,
4116                             Extended /*EncodeClassNames*/);
4117}
4118
4119/// getObjCEncodingForMethodDecl - Return the encoded type for this method
4120/// declaration.
4121bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4122                                              std::string& S,
4123                                              bool Extended) const {
4124  // FIXME: This is not very efficient.
4125  // Encode return type.
4126  getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4127                                    Decl->getResultType(), S, Extended);
4128  // Compute size of all parameters.
4129  // Start with computing size of a pointer in number of bytes.
4130  // FIXME: There might(should) be a better way of doing this computation!
4131  SourceLocation Loc;
4132  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4133  // The first two arguments (self and _cmd) are pointers; account for
4134  // their size.
4135  CharUnits ParmOffset = 2 * PtrSize;
4136  for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4137       E = Decl->sel_param_end(); PI != E; ++PI) {
4138    QualType PType = (*PI)->getType();
4139    CharUnits sz = getObjCEncodingTypeSize(PType);
4140    if (sz.isZero())
4141      return true;
4142
4143    assert (sz.isPositive() &&
4144        "getObjCEncodingForMethodDecl - Incomplete param type");
4145    ParmOffset += sz;
4146  }
4147  S += charUnitsToString(ParmOffset);
4148  S += "@0:";
4149  S += charUnitsToString(PtrSize);
4150
4151  // Argument types.
4152  ParmOffset = 2 * PtrSize;
4153  for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4154       E = Decl->sel_param_end(); PI != E; ++PI) {
4155    const ParmVarDecl *PVDecl = *PI;
4156    QualType PType = PVDecl->getOriginalType();
4157    if (const ArrayType *AT =
4158          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4159      // Use array's original type only if it has known number of
4160      // elements.
4161      if (!isa<ConstantArrayType>(AT))
4162        PType = PVDecl->getType();
4163    } else if (PType->isFunctionType())
4164      PType = PVDecl->getType();
4165    getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4166                                      PType, S, Extended);
4167    S += charUnitsToString(ParmOffset);
4168    ParmOffset += getObjCEncodingTypeSize(PType);
4169  }
4170
4171  return false;
4172}
4173
4174/// getObjCEncodingForPropertyDecl - Return the encoded type for this
4175/// property declaration. If non-NULL, Container must be either an
4176/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4177/// NULL when getting encodings for protocol properties.
4178/// Property attributes are stored as a comma-delimited C string. The simple
4179/// attributes readonly and bycopy are encoded as single characters. The
4180/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4181/// encoded as single characters, followed by an identifier. Property types
4182/// are also encoded as a parametrized attribute. The characters used to encode
4183/// these attributes are defined by the following enumeration:
4184/// @code
4185/// enum PropertyAttributes {
4186/// kPropertyReadOnly = 'R',   // property is read-only.
4187/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
4188/// kPropertyByref = '&',  // property is a reference to the value last assigned
4189/// kPropertyDynamic = 'D',    // property is dynamic
4190/// kPropertyGetter = 'G',     // followed by getter selector name
4191/// kPropertySetter = 'S',     // followed by setter selector name
4192/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
4193/// kPropertyType = 't'              // followed by old-style type encoding.
4194/// kPropertyWeak = 'W'              // 'weak' property
4195/// kPropertyStrong = 'P'            // property GC'able
4196/// kPropertyNonAtomic = 'N'         // property non-atomic
4197/// };
4198/// @endcode
4199void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4200                                                const Decl *Container,
4201                                                std::string& S) const {
4202  // Collect information from the property implementation decl(s).
4203  bool Dynamic = false;
4204  ObjCPropertyImplDecl *SynthesizePID = 0;
4205
4206  // FIXME: Duplicated code due to poor abstraction.
4207  if (Container) {
4208    if (const ObjCCategoryImplDecl *CID =
4209        dyn_cast<ObjCCategoryImplDecl>(Container)) {
4210      for (ObjCCategoryImplDecl::propimpl_iterator
4211             i = CID->propimpl_begin(), e = CID->propimpl_end();
4212           i != e; ++i) {
4213        ObjCPropertyImplDecl *PID = *i;
4214        if (PID->getPropertyDecl() == PD) {
4215          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4216            Dynamic = true;
4217          } else {
4218            SynthesizePID = PID;
4219          }
4220        }
4221      }
4222    } else {
4223      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4224      for (ObjCCategoryImplDecl::propimpl_iterator
4225             i = OID->propimpl_begin(), e = OID->propimpl_end();
4226           i != e; ++i) {
4227        ObjCPropertyImplDecl *PID = *i;
4228        if (PID->getPropertyDecl() == PD) {
4229          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4230            Dynamic = true;
4231          } else {
4232            SynthesizePID = PID;
4233          }
4234        }
4235      }
4236    }
4237  }
4238
4239  // FIXME: This is not very efficient.
4240  S = "T";
4241
4242  // Encode result type.
4243  // GCC has some special rules regarding encoding of properties which
4244  // closely resembles encoding of ivars.
4245  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4246                             true /* outermost type */,
4247                             true /* encoding for property */);
4248
4249  if (PD->isReadOnly()) {
4250    S += ",R";
4251  } else {
4252    switch (PD->getSetterKind()) {
4253    case ObjCPropertyDecl::Assign: break;
4254    case ObjCPropertyDecl::Copy:   S += ",C"; break;
4255    case ObjCPropertyDecl::Retain: S += ",&"; break;
4256    case ObjCPropertyDecl::Weak:   S += ",W"; break;
4257    }
4258  }
4259
4260  // It really isn't clear at all what this means, since properties
4261  // are "dynamic by default".
4262  if (Dynamic)
4263    S += ",D";
4264
4265  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4266    S += ",N";
4267
4268  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4269    S += ",G";
4270    S += PD->getGetterName().getAsString();
4271  }
4272
4273  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4274    S += ",S";
4275    S += PD->getSetterName().getAsString();
4276  }
4277
4278  if (SynthesizePID) {
4279    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4280    S += ",V";
4281    S += OID->getNameAsString();
4282  }
4283
4284  // FIXME: OBJCGC: weak & strong
4285}
4286
4287/// getLegacyIntegralTypeEncoding -
4288/// Another legacy compatibility encoding: 32-bit longs are encoded as
4289/// 'l' or 'L' , but not always.  For typedefs, we need to use
4290/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4291///
4292void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
4293  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
4294    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
4295      if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
4296        PointeeTy = UnsignedIntTy;
4297      else
4298        if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
4299          PointeeTy = IntTy;
4300    }
4301  }
4302}
4303
4304void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
4305                                        const FieldDecl *Field) const {
4306  // We follow the behavior of gcc, expanding structures which are
4307  // directly pointed to, and expanding embedded structures. Note that
4308  // these rules are sufficient to prevent recursive encoding of the
4309  // same type.
4310  getObjCEncodingForTypeImpl(T, S, true, true, Field,
4311                             true /* outermost type */);
4312}
4313
4314static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4315    switch (T->getAs<BuiltinType>()->getKind()) {
4316    default: llvm_unreachable("Unhandled builtin type kind");
4317    case BuiltinType::Void:       return 'v';
4318    case BuiltinType::Bool:       return 'B';
4319    case BuiltinType::Char_U:
4320    case BuiltinType::UChar:      return 'C';
4321    case BuiltinType::UShort:     return 'S';
4322    case BuiltinType::UInt:       return 'I';
4323    case BuiltinType::ULong:
4324        return C->getIntWidth(T) == 32 ? 'L' : 'Q';
4325    case BuiltinType::UInt128:    return 'T';
4326    case BuiltinType::ULongLong:  return 'Q';
4327    case BuiltinType::Char_S:
4328    case BuiltinType::SChar:      return 'c';
4329    case BuiltinType::Short:      return 's';
4330    case BuiltinType::WChar_S:
4331    case BuiltinType::WChar_U:
4332    case BuiltinType::Int:        return 'i';
4333    case BuiltinType::Long:
4334      return C->getIntWidth(T) == 32 ? 'l' : 'q';
4335    case BuiltinType::LongLong:   return 'q';
4336    case BuiltinType::Int128:     return 't';
4337    case BuiltinType::Float:      return 'f';
4338    case BuiltinType::Double:     return 'd';
4339    case BuiltinType::LongDouble: return 'D';
4340    }
4341}
4342
4343static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4344  EnumDecl *Enum = ET->getDecl();
4345
4346  // The encoding of an non-fixed enum type is always 'i', regardless of size.
4347  if (!Enum->isFixed())
4348    return 'i';
4349
4350  // The encoding of a fixed enum type matches its fixed underlying type.
4351  return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4352}
4353
4354static void EncodeBitField(const ASTContext *Ctx, std::string& S,
4355                           QualType T, const FieldDecl *FD) {
4356  assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
4357  S += 'b';
4358  // The NeXT runtime encodes bit fields as b followed by the number of bits.
4359  // The GNU runtime requires more information; bitfields are encoded as b,
4360  // then the offset (in bits) of the first element, then the type of the
4361  // bitfield, then the size in bits.  For example, in this structure:
4362  //
4363  // struct
4364  // {
4365  //    int integer;
4366  //    int flags:2;
4367  // };
4368  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4369  // runtime, but b32i2 for the GNU runtime.  The reason for this extra
4370  // information is not especially sensible, but we're stuck with it for
4371  // compatibility with GCC, although providing it breaks anything that
4372  // actually uses runtime introspection and wants to work on both runtimes...
4373  if (!Ctx->getLangOptions().NeXTRuntime) {
4374    const RecordDecl *RD = FD->getParent();
4375    const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4376    S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
4377    if (const EnumType *ET = T->getAs<EnumType>())
4378      S += ObjCEncodingForEnumType(Ctx, ET);
4379    else
4380      S += ObjCEncodingForPrimitiveKind(Ctx, T);
4381  }
4382  S += llvm::utostr(FD->getBitWidthValue(*Ctx));
4383}
4384
4385// FIXME: Use SmallString for accumulating string.
4386void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4387                                            bool ExpandPointedToStructures,
4388                                            bool ExpandStructures,
4389                                            const FieldDecl *FD,
4390                                            bool OutermostType,
4391                                            bool EncodingProperty,
4392                                            bool StructField,
4393                                            bool EncodeBlockParameters,
4394                                            bool EncodeClassNames) const {
4395  if (T->getAs<BuiltinType>()) {
4396    if (FD && FD->isBitField())
4397      return EncodeBitField(this, S, T, FD);
4398    S += ObjCEncodingForPrimitiveKind(this, T);
4399    return;
4400  }
4401
4402  if (const ComplexType *CT = T->getAs<ComplexType>()) {
4403    S += 'j';
4404    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
4405                               false);
4406    return;
4407  }
4408
4409  // encoding for pointer or r3eference types.
4410  QualType PointeeTy;
4411  if (const PointerType *PT = T->getAs<PointerType>()) {
4412    if (PT->isObjCSelType()) {
4413      S += ':';
4414      return;
4415    }
4416    PointeeTy = PT->getPointeeType();
4417  }
4418  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4419    PointeeTy = RT->getPointeeType();
4420  if (!PointeeTy.isNull()) {
4421    bool isReadOnly = false;
4422    // For historical/compatibility reasons, the read-only qualifier of the
4423    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
4424    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
4425    // Also, do not emit the 'r' for anything but the outermost type!
4426    if (isa<TypedefType>(T.getTypePtr())) {
4427      if (OutermostType && T.isConstQualified()) {
4428        isReadOnly = true;
4429        S += 'r';
4430      }
4431    } else if (OutermostType) {
4432      QualType P = PointeeTy;
4433      while (P->getAs<PointerType>())
4434        P = P->getAs<PointerType>()->getPointeeType();
4435      if (P.isConstQualified()) {
4436        isReadOnly = true;
4437        S += 'r';
4438      }
4439    }
4440    if (isReadOnly) {
4441      // Another legacy compatibility encoding. Some ObjC qualifier and type
4442      // combinations need to be rearranged.
4443      // Rewrite "in const" from "nr" to "rn"
4444      if (StringRef(S).endswith("nr"))
4445        S.replace(S.end()-2, S.end(), "rn");
4446    }
4447
4448    if (PointeeTy->isCharType()) {
4449      // char pointer types should be encoded as '*' unless it is a
4450      // type that has been typedef'd to 'BOOL'.
4451      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
4452        S += '*';
4453        return;
4454      }
4455    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
4456      // GCC binary compat: Need to convert "struct objc_class *" to "#".
4457      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4458        S += '#';
4459        return;
4460      }
4461      // GCC binary compat: Need to convert "struct objc_object *" to "@".
4462      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4463        S += '@';
4464        return;
4465      }
4466      // fall through...
4467    }
4468    S += '^';
4469    getLegacyIntegralTypeEncoding(PointeeTy);
4470
4471    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
4472                               NULL);
4473    return;
4474  }
4475
4476  if (const ArrayType *AT =
4477      // Ignore type qualifiers etc.
4478        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
4479    if (isa<IncompleteArrayType>(AT) && !StructField) {
4480      // Incomplete arrays are encoded as a pointer to the array element.
4481      S += '^';
4482
4483      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4484                                 false, ExpandStructures, FD);
4485    } else {
4486      S += '[';
4487
4488      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4489        if (getTypeSize(CAT->getElementType()) == 0)
4490          S += '0';
4491        else
4492          S += llvm::utostr(CAT->getSize().getZExtValue());
4493      } else {
4494        //Variable length arrays are encoded as a regular array with 0 elements.
4495        assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4496               "Unknown array type!");
4497        S += '0';
4498      }
4499
4500      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4501                                 false, ExpandStructures, FD);
4502      S += ']';
4503    }
4504    return;
4505  }
4506
4507  if (T->getAs<FunctionType>()) {
4508    S += '?';
4509    return;
4510  }
4511
4512  if (const RecordType *RTy = T->getAs<RecordType>()) {
4513    RecordDecl *RDecl = RTy->getDecl();
4514    S += RDecl->isUnion() ? '(' : '{';
4515    // Anonymous structures print as '?'
4516    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4517      S += II->getName();
4518      if (ClassTemplateSpecializationDecl *Spec
4519          = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4520        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4521        std::string TemplateArgsStr
4522          = TemplateSpecializationType::PrintTemplateArgumentList(
4523                                            TemplateArgs.data(),
4524                                            TemplateArgs.size(),
4525                                            (*this).getPrintingPolicy());
4526
4527        S += TemplateArgsStr;
4528      }
4529    } else {
4530      S += '?';
4531    }
4532    if (ExpandStructures) {
4533      S += '=';
4534      if (!RDecl->isUnion()) {
4535        getObjCEncodingForStructureImpl(RDecl, S, FD);
4536      } else {
4537        for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4538                                     FieldEnd = RDecl->field_end();
4539             Field != FieldEnd; ++Field) {
4540          if (FD) {
4541            S += '"';
4542            S += Field->getNameAsString();
4543            S += '"';
4544          }
4545
4546          // Special case bit-fields.
4547          if (Field->isBitField()) {
4548            getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4549                                       (*Field));
4550          } else {
4551            QualType qt = Field->getType();
4552            getLegacyIntegralTypeEncoding(qt);
4553            getObjCEncodingForTypeImpl(qt, S, false, true,
4554                                       FD, /*OutermostType*/false,
4555                                       /*EncodingProperty*/false,
4556                                       /*StructField*/true);
4557          }
4558        }
4559      }
4560    }
4561    S += RDecl->isUnion() ? ')' : '}';
4562    return;
4563  }
4564
4565  if (const EnumType *ET = T->getAs<EnumType>()) {
4566    if (FD && FD->isBitField())
4567      EncodeBitField(this, S, T, FD);
4568    else
4569      S += ObjCEncodingForEnumType(this, ET);
4570    return;
4571  }
4572
4573  if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
4574    S += "@?"; // Unlike a pointer-to-function, which is "^?".
4575    if (EncodeBlockParameters) {
4576      const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4577
4578      S += '<';
4579      // Block return type
4580      getObjCEncodingForTypeImpl(FT->getResultType(), S,
4581                                 ExpandPointedToStructures, ExpandStructures,
4582                                 FD,
4583                                 false /* OutermostType */,
4584                                 EncodingProperty,
4585                                 false /* StructField */,
4586                                 EncodeBlockParameters,
4587                                 EncodeClassNames);
4588      // Block self
4589      S += "@?";
4590      // Block parameters
4591      if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4592        for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4593               E = FPT->arg_type_end(); I && (I != E); ++I) {
4594          getObjCEncodingForTypeImpl(*I, S,
4595                                     ExpandPointedToStructures,
4596                                     ExpandStructures,
4597                                     FD,
4598                                     false /* OutermostType */,
4599                                     EncodingProperty,
4600                                     false /* StructField */,
4601                                     EncodeBlockParameters,
4602                                     EncodeClassNames);
4603        }
4604      }
4605      S += '>';
4606    }
4607    return;
4608  }
4609
4610  // Ignore protocol qualifiers when mangling at this level.
4611  if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4612    T = OT->getBaseType();
4613
4614  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
4615    // @encode(class_name)
4616    ObjCInterfaceDecl *OI = OIT->getDecl();
4617    S += '{';
4618    const IdentifierInfo *II = OI->getIdentifier();
4619    S += II->getName();
4620    S += '=';
4621    SmallVector<const ObjCIvarDecl*, 32> Ivars;
4622    DeepCollectObjCIvars(OI, true, Ivars);
4623    for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4624      const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4625      if (Field->isBitField())
4626        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
4627      else
4628        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
4629    }
4630    S += '}';
4631    return;
4632  }
4633
4634  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
4635    if (OPT->isObjCIdType()) {
4636      S += '@';
4637      return;
4638    }
4639
4640    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4641      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4642      // Since this is a binary compatibility issue, need to consult with runtime
4643      // folks. Fortunately, this is a *very* obsure construct.
4644      S += '#';
4645      return;
4646    }
4647
4648    if (OPT->isObjCQualifiedIdType()) {
4649      getObjCEncodingForTypeImpl(getObjCIdType(), S,
4650                                 ExpandPointedToStructures,
4651                                 ExpandStructures, FD);
4652      if (FD || EncodingProperty || EncodeClassNames) {
4653        // Note that we do extended encoding of protocol qualifer list
4654        // Only when doing ivar or property encoding.
4655        S += '"';
4656        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4657             E = OPT->qual_end(); I != E; ++I) {
4658          S += '<';
4659          S += (*I)->getNameAsString();
4660          S += '>';
4661        }
4662        S += '"';
4663      }
4664      return;
4665    }
4666
4667    QualType PointeeTy = OPT->getPointeeType();
4668    if (!EncodingProperty &&
4669        isa<TypedefType>(PointeeTy.getTypePtr())) {
4670      // Another historical/compatibility reason.
4671      // We encode the underlying type which comes out as
4672      // {...};
4673      S += '^';
4674      getObjCEncodingForTypeImpl(PointeeTy, S,
4675                                 false, ExpandPointedToStructures,
4676                                 NULL);
4677      return;
4678    }
4679
4680    S += '@';
4681    if (OPT->getInterfaceDecl() &&
4682        (FD || EncodingProperty || EncodeClassNames)) {
4683      S += '"';
4684      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
4685      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4686           E = OPT->qual_end(); I != E; ++I) {
4687        S += '<';
4688        S += (*I)->getNameAsString();
4689        S += '>';
4690      }
4691      S += '"';
4692    }
4693    return;
4694  }
4695
4696  // gcc just blithely ignores member pointers.
4697  // TODO: maybe there should be a mangling for these
4698  if (T->getAs<MemberPointerType>())
4699    return;
4700
4701  if (T->isVectorType()) {
4702    // This matches gcc's encoding, even though technically it is
4703    // insufficient.
4704    // FIXME. We should do a better job than gcc.
4705    return;
4706  }
4707
4708  llvm_unreachable("@encode for type not implemented!");
4709}
4710
4711void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4712                                                 std::string &S,
4713                                                 const FieldDecl *FD,
4714                                                 bool includeVBases) const {
4715  assert(RDecl && "Expected non-null RecordDecl");
4716  assert(!RDecl->isUnion() && "Should not be called for unions");
4717  if (!RDecl->getDefinition())
4718    return;
4719
4720  CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4721  std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4722  const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4723
4724  if (CXXRec) {
4725    for (CXXRecordDecl::base_class_iterator
4726           BI = CXXRec->bases_begin(),
4727           BE = CXXRec->bases_end(); BI != BE; ++BI) {
4728      if (!BI->isVirtual()) {
4729        CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4730        if (base->isEmpty())
4731          continue;
4732        uint64_t offs = layout.getBaseClassOffsetInBits(base);
4733        FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4734                                  std::make_pair(offs, base));
4735      }
4736    }
4737  }
4738
4739  unsigned i = 0;
4740  for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4741                               FieldEnd = RDecl->field_end();
4742       Field != FieldEnd; ++Field, ++i) {
4743    uint64_t offs = layout.getFieldOffset(i);
4744    FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4745                              std::make_pair(offs, *Field));
4746  }
4747
4748  if (CXXRec && includeVBases) {
4749    for (CXXRecordDecl::base_class_iterator
4750           BI = CXXRec->vbases_begin(),
4751           BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4752      CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4753      if (base->isEmpty())
4754        continue;
4755      uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4756      if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4757        FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4758                                  std::make_pair(offs, base));
4759    }
4760  }
4761
4762  CharUnits size;
4763  if (CXXRec) {
4764    size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4765  } else {
4766    size = layout.getSize();
4767  }
4768
4769  uint64_t CurOffs = 0;
4770  std::multimap<uint64_t, NamedDecl *>::iterator
4771    CurLayObj = FieldOrBaseOffsets.begin();
4772
4773  if ((CurLayObj != FieldOrBaseOffsets.end() && CurLayObj->first != 0) ||
4774      (CurLayObj == FieldOrBaseOffsets.end() &&
4775         CXXRec && CXXRec->isDynamicClass())) {
4776    assert(CXXRec && CXXRec->isDynamicClass() &&
4777           "Offset 0 was empty but no VTable ?");
4778    if (FD) {
4779      S += "\"_vptr$";
4780      std::string recname = CXXRec->getNameAsString();
4781      if (recname.empty()) recname = "?";
4782      S += recname;
4783      S += '"';
4784    }
4785    S += "^^?";
4786    CurOffs += getTypeSize(VoidPtrTy);
4787  }
4788
4789  if (!RDecl->hasFlexibleArrayMember()) {
4790    // Mark the end of the structure.
4791    uint64_t offs = toBits(size);
4792    FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4793                              std::make_pair(offs, (NamedDecl*)0));
4794  }
4795
4796  for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4797    assert(CurOffs <= CurLayObj->first);
4798
4799    if (CurOffs < CurLayObj->first) {
4800      uint64_t padding = CurLayObj->first - CurOffs;
4801      // FIXME: There doesn't seem to be a way to indicate in the encoding that
4802      // packing/alignment of members is different that normal, in which case
4803      // the encoding will be out-of-sync with the real layout.
4804      // If the runtime switches to just consider the size of types without
4805      // taking into account alignment, we could make padding explicit in the
4806      // encoding (e.g. using arrays of chars). The encoding strings would be
4807      // longer then though.
4808      CurOffs += padding;
4809    }
4810
4811    NamedDecl *dcl = CurLayObj->second;
4812    if (dcl == 0)
4813      break; // reached end of structure.
4814
4815    if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4816      // We expand the bases without their virtual bases since those are going
4817      // in the initial structure. Note that this differs from gcc which
4818      // expands virtual bases each time one is encountered in the hierarchy,
4819      // making the encoding type bigger than it really is.
4820      getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
4821      assert(!base->isEmpty());
4822      CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
4823    } else {
4824      FieldDecl *field = cast<FieldDecl>(dcl);
4825      if (FD) {
4826        S += '"';
4827        S += field->getNameAsString();
4828        S += '"';
4829      }
4830
4831      if (field->isBitField()) {
4832        EncodeBitField(this, S, field->getType(), field);
4833        CurOffs += field->getBitWidthValue(*this);
4834      } else {
4835        QualType qt = field->getType();
4836        getLegacyIntegralTypeEncoding(qt);
4837        getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4838                                   /*OutermostType*/false,
4839                                   /*EncodingProperty*/false,
4840                                   /*StructField*/true);
4841        CurOffs += getTypeSize(field->getType());
4842      }
4843    }
4844  }
4845}
4846
4847void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
4848                                                 std::string& S) const {
4849  if (QT & Decl::OBJC_TQ_In)
4850    S += 'n';
4851  if (QT & Decl::OBJC_TQ_Inout)
4852    S += 'N';
4853  if (QT & Decl::OBJC_TQ_Out)
4854    S += 'o';
4855  if (QT & Decl::OBJC_TQ_Bycopy)
4856    S += 'O';
4857  if (QT & Decl::OBJC_TQ_Byref)
4858    S += 'R';
4859  if (QT & Decl::OBJC_TQ_Oneway)
4860    S += 'V';
4861}
4862
4863void ASTContext::setBuiltinVaListType(QualType T) {
4864  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
4865
4866  BuiltinVaListType = T;
4867}
4868
4869TypedefDecl *ASTContext::getObjCIdDecl() const {
4870  if (!ObjCIdDecl) {
4871    QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4872    T = getObjCObjectPointerType(T);
4873    TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4874    ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4875                                     getTranslationUnitDecl(),
4876                                     SourceLocation(), SourceLocation(),
4877                                     &Idents.get("id"), IdInfo);
4878  }
4879
4880  return ObjCIdDecl;
4881}
4882
4883TypedefDecl *ASTContext::getObjCSelDecl() const {
4884  if (!ObjCSelDecl) {
4885    QualType SelT = getPointerType(ObjCBuiltinSelTy);
4886    TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4887    ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4888                                      getTranslationUnitDecl(),
4889                                      SourceLocation(), SourceLocation(),
4890                                      &Idents.get("SEL"), SelInfo);
4891  }
4892  return ObjCSelDecl;
4893}
4894
4895TypedefDecl *ASTContext::getObjCClassDecl() const {
4896  if (!ObjCClassDecl) {
4897    QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
4898    T = getObjCObjectPointerType(T);
4899    TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
4900    ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4901                                        getTranslationUnitDecl(),
4902                                        SourceLocation(), SourceLocation(),
4903                                        &Idents.get("Class"), ClassInfo);
4904  }
4905
4906  return ObjCClassDecl;
4907}
4908
4909ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
4910  if (!ObjCProtocolClassDecl) {
4911    ObjCProtocolClassDecl
4912      = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
4913                                  SourceLocation(),
4914                                  &Idents.get("Protocol"),
4915                                  /*PrevDecl=*/0,
4916                                  SourceLocation(), true);
4917  }
4918
4919  return ObjCProtocolClassDecl;
4920}
4921
4922void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
4923  assert(ObjCConstantStringType.isNull() &&
4924         "'NSConstantString' type already set!");
4925
4926  ObjCConstantStringType = getObjCInterfaceType(Decl);
4927}
4928
4929/// \brief Retrieve the template name that corresponds to a non-empty
4930/// lookup.
4931TemplateName
4932ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
4933                                      UnresolvedSetIterator End) const {
4934  unsigned size = End - Begin;
4935  assert(size > 1 && "set is not overloaded!");
4936
4937  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
4938                          size * sizeof(FunctionTemplateDecl*));
4939  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
4940
4941  NamedDecl **Storage = OT->getStorage();
4942  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
4943    NamedDecl *D = *I;
4944    assert(isa<FunctionTemplateDecl>(D) ||
4945           (isa<UsingShadowDecl>(D) &&
4946            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
4947    *Storage++ = D;
4948  }
4949
4950  return TemplateName(OT);
4951}
4952
4953/// \brief Retrieve the template name that represents a qualified
4954/// template name such as \c std::vector.
4955TemplateName
4956ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
4957                                     bool TemplateKeyword,
4958                                     TemplateDecl *Template) const {
4959  assert(NNS && "Missing nested-name-specifier in qualified template name");
4960
4961  // FIXME: Canonicalization?
4962  llvm::FoldingSetNodeID ID;
4963  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
4964
4965  void *InsertPos = 0;
4966  QualifiedTemplateName *QTN =
4967    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4968  if (!QTN) {
4969    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
4970    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
4971  }
4972
4973  return TemplateName(QTN);
4974}
4975
4976/// \brief Retrieve the template name that represents a dependent
4977/// template name such as \c MetaFun::template apply.
4978TemplateName
4979ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4980                                     const IdentifierInfo *Name) const {
4981  assert((!NNS || NNS->isDependent()) &&
4982         "Nested name specifier must be dependent");
4983
4984  llvm::FoldingSetNodeID ID;
4985  DependentTemplateName::Profile(ID, NNS, Name);
4986
4987  void *InsertPos = 0;
4988  DependentTemplateName *QTN =
4989    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4990
4991  if (QTN)
4992    return TemplateName(QTN);
4993
4994  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4995  if (CanonNNS == NNS) {
4996    QTN = new (*this,4) DependentTemplateName(NNS, Name);
4997  } else {
4998    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4999    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
5000    DependentTemplateName *CheckQTN =
5001      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5002    assert(!CheckQTN && "Dependent type name canonicalization broken");
5003    (void)CheckQTN;
5004  }
5005
5006  DependentTemplateNames.InsertNode(QTN, InsertPos);
5007  return TemplateName(QTN);
5008}
5009
5010/// \brief Retrieve the template name that represents a dependent
5011/// template name such as \c MetaFun::template operator+.
5012TemplateName
5013ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5014                                     OverloadedOperatorKind Operator) const {
5015  assert((!NNS || NNS->isDependent()) &&
5016         "Nested name specifier must be dependent");
5017
5018  llvm::FoldingSetNodeID ID;
5019  DependentTemplateName::Profile(ID, NNS, Operator);
5020
5021  void *InsertPos = 0;
5022  DependentTemplateName *QTN
5023    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5024
5025  if (QTN)
5026    return TemplateName(QTN);
5027
5028  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5029  if (CanonNNS == NNS) {
5030    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5031  } else {
5032    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5033    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
5034
5035    DependentTemplateName *CheckQTN
5036      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5037    assert(!CheckQTN && "Dependent template name canonicalization broken");
5038    (void)CheckQTN;
5039  }
5040
5041  DependentTemplateNames.InsertNode(QTN, InsertPos);
5042  return TemplateName(QTN);
5043}
5044
5045TemplateName
5046ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5047                                         TemplateName replacement) const {
5048  llvm::FoldingSetNodeID ID;
5049  SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5050
5051  void *insertPos = 0;
5052  SubstTemplateTemplateParmStorage *subst
5053    = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5054
5055  if (!subst) {
5056    subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5057    SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5058  }
5059
5060  return TemplateName(subst);
5061}
5062
5063TemplateName
5064ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5065                                       const TemplateArgument &ArgPack) const {
5066  ASTContext &Self = const_cast<ASTContext &>(*this);
5067  llvm::FoldingSetNodeID ID;
5068  SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5069
5070  void *InsertPos = 0;
5071  SubstTemplateTemplateParmPackStorage *Subst
5072    = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5073
5074  if (!Subst) {
5075    Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
5076                                                           ArgPack.pack_size(),
5077                                                         ArgPack.pack_begin());
5078    SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5079  }
5080
5081  return TemplateName(Subst);
5082}
5083
5084/// getFromTargetType - Given one of the integer types provided by
5085/// TargetInfo, produce the corresponding type. The unsigned @p Type
5086/// is actually a value of type @c TargetInfo::IntType.
5087CanQualType ASTContext::getFromTargetType(unsigned Type) const {
5088  switch (Type) {
5089  case TargetInfo::NoInt: return CanQualType();
5090  case TargetInfo::SignedShort: return ShortTy;
5091  case TargetInfo::UnsignedShort: return UnsignedShortTy;
5092  case TargetInfo::SignedInt: return IntTy;
5093  case TargetInfo::UnsignedInt: return UnsignedIntTy;
5094  case TargetInfo::SignedLong: return LongTy;
5095  case TargetInfo::UnsignedLong: return UnsignedLongTy;
5096  case TargetInfo::SignedLongLong: return LongLongTy;
5097  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5098  }
5099
5100  llvm_unreachable("Unhandled TargetInfo::IntType value");
5101}
5102
5103//===----------------------------------------------------------------------===//
5104//                        Type Predicates.
5105//===----------------------------------------------------------------------===//
5106
5107/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5108/// garbage collection attribute.
5109///
5110Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
5111  if (getLangOptions().getGC() == LangOptions::NonGC)
5112    return Qualifiers::GCNone;
5113
5114  assert(getLangOptions().ObjC1);
5115  Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5116
5117  // Default behaviour under objective-C's gc is for ObjC pointers
5118  // (or pointers to them) be treated as though they were declared
5119  // as __strong.
5120  if (GCAttrs == Qualifiers::GCNone) {
5121    if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5122      return Qualifiers::Strong;
5123    else if (Ty->isPointerType())
5124      return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5125  } else {
5126    // It's not valid to set GC attributes on anything that isn't a
5127    // pointer.
5128#ifndef NDEBUG
5129    QualType CT = Ty->getCanonicalTypeInternal();
5130    while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5131      CT = AT->getElementType();
5132    assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5133#endif
5134  }
5135  return GCAttrs;
5136}
5137
5138//===----------------------------------------------------------------------===//
5139//                        Type Compatibility Testing
5140//===----------------------------------------------------------------------===//
5141
5142/// areCompatVectorTypes - Return true if the two specified vector types are
5143/// compatible.
5144static bool areCompatVectorTypes(const VectorType *LHS,
5145                                 const VectorType *RHS) {
5146  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
5147  return LHS->getElementType() == RHS->getElementType() &&
5148         LHS->getNumElements() == RHS->getNumElements();
5149}
5150
5151bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5152                                          QualType SecondVec) {
5153  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5154  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5155
5156  if (hasSameUnqualifiedType(FirstVec, SecondVec))
5157    return true;
5158
5159  // Treat Neon vector types and most AltiVec vector types as if they are the
5160  // equivalent GCC vector types.
5161  const VectorType *First = FirstVec->getAs<VectorType>();
5162  const VectorType *Second = SecondVec->getAs<VectorType>();
5163  if (First->getNumElements() == Second->getNumElements() &&
5164      hasSameType(First->getElementType(), Second->getElementType()) &&
5165      First->getVectorKind() != VectorType::AltiVecPixel &&
5166      First->getVectorKind() != VectorType::AltiVecBool &&
5167      Second->getVectorKind() != VectorType::AltiVecPixel &&
5168      Second->getVectorKind() != VectorType::AltiVecBool)
5169    return true;
5170
5171  return false;
5172}
5173
5174//===----------------------------------------------------------------------===//
5175// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5176//===----------------------------------------------------------------------===//
5177
5178/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5179/// inheritance hierarchy of 'rProto'.
5180bool
5181ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5182                                           ObjCProtocolDecl *rProto) const {
5183  if (declaresSameEntity(lProto, rProto))
5184    return true;
5185  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5186       E = rProto->protocol_end(); PI != E; ++PI)
5187    if (ProtocolCompatibleWithProtocol(lProto, *PI))
5188      return true;
5189  return false;
5190}
5191
5192/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5193/// return true if lhs's protocols conform to rhs's protocol; false
5194/// otherwise.
5195bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5196  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5197    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5198  return false;
5199}
5200
5201/// ObjCQualifiedClassTypesAreCompatible - compare  Class<p,...> and
5202/// Class<p1, ...>.
5203bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5204                                                      QualType rhs) {
5205  const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5206  const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5207  assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5208
5209  for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5210       E = lhsQID->qual_end(); I != E; ++I) {
5211    bool match = false;
5212    ObjCProtocolDecl *lhsProto = *I;
5213    for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5214         E = rhsOPT->qual_end(); J != E; ++J) {
5215      ObjCProtocolDecl *rhsProto = *J;
5216      if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5217        match = true;
5218        break;
5219      }
5220    }
5221    if (!match)
5222      return false;
5223  }
5224  return true;
5225}
5226
5227/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5228/// ObjCQualifiedIDType.
5229bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5230                                                   bool compare) {
5231  // Allow id<P..> and an 'id' or void* type in all cases.
5232  if (lhs->isVoidPointerType() ||
5233      lhs->isObjCIdType() || lhs->isObjCClassType())
5234    return true;
5235  else if (rhs->isVoidPointerType() ||
5236           rhs->isObjCIdType() || rhs->isObjCClassType())
5237    return true;
5238
5239  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
5240    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5241
5242    if (!rhsOPT) return false;
5243
5244    if (rhsOPT->qual_empty()) {
5245      // If the RHS is a unqualified interface pointer "NSString*",
5246      // make sure we check the class hierarchy.
5247      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5248        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5249             E = lhsQID->qual_end(); I != E; ++I) {
5250          // when comparing an id<P> on lhs with a static type on rhs,
5251          // see if static class implements all of id's protocols, directly or
5252          // through its super class and categories.
5253          if (!rhsID->ClassImplementsProtocol(*I, true))
5254            return false;
5255        }
5256      }
5257      // If there are no qualifiers and no interface, we have an 'id'.
5258      return true;
5259    }
5260    // Both the right and left sides have qualifiers.
5261    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5262         E = lhsQID->qual_end(); I != E; ++I) {
5263      ObjCProtocolDecl *lhsProto = *I;
5264      bool match = false;
5265
5266      // when comparing an id<P> on lhs with a static type on rhs,
5267      // see if static class implements all of id's protocols, directly or
5268      // through its super class and categories.
5269      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5270           E = rhsOPT->qual_end(); J != E; ++J) {
5271        ObjCProtocolDecl *rhsProto = *J;
5272        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5273            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5274          match = true;
5275          break;
5276        }
5277      }
5278      // If the RHS is a qualified interface pointer "NSString<P>*",
5279      // make sure we check the class hierarchy.
5280      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5281        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5282             E = lhsQID->qual_end(); I != E; ++I) {
5283          // when comparing an id<P> on lhs with a static type on rhs,
5284          // see if static class implements all of id's protocols, directly or
5285          // through its super class and categories.
5286          if (rhsID->ClassImplementsProtocol(*I, true)) {
5287            match = true;
5288            break;
5289          }
5290        }
5291      }
5292      if (!match)
5293        return false;
5294    }
5295
5296    return true;
5297  }
5298
5299  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5300  assert(rhsQID && "One of the LHS/RHS should be id<x>");
5301
5302  if (const ObjCObjectPointerType *lhsOPT =
5303        lhs->getAsObjCInterfacePointerType()) {
5304    // If both the right and left sides have qualifiers.
5305    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5306         E = lhsOPT->qual_end(); I != E; ++I) {
5307      ObjCProtocolDecl *lhsProto = *I;
5308      bool match = false;
5309
5310      // when comparing an id<P> on rhs with a static type on lhs,
5311      // see if static class implements all of id's protocols, directly or
5312      // through its super class and categories.
5313      // First, lhs protocols in the qualifier list must be found, direct
5314      // or indirect in rhs's qualifier list or it is a mismatch.
5315      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5316           E = rhsQID->qual_end(); J != E; ++J) {
5317        ObjCProtocolDecl *rhsProto = *J;
5318        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5319            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5320          match = true;
5321          break;
5322        }
5323      }
5324      if (!match)
5325        return false;
5326    }
5327
5328    // Static class's protocols, or its super class or category protocols
5329    // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5330    if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5331      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5332      CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5333      // This is rather dubious but matches gcc's behavior. If lhs has
5334      // no type qualifier and its class has no static protocol(s)
5335      // assume that it is mismatch.
5336      if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5337        return false;
5338      for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5339           LHSInheritedProtocols.begin(),
5340           E = LHSInheritedProtocols.end(); I != E; ++I) {
5341        bool match = false;
5342        ObjCProtocolDecl *lhsProto = (*I);
5343        for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5344             E = rhsQID->qual_end(); J != E; ++J) {
5345          ObjCProtocolDecl *rhsProto = *J;
5346          if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5347              (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5348            match = true;
5349            break;
5350          }
5351        }
5352        if (!match)
5353          return false;
5354      }
5355    }
5356    return true;
5357  }
5358  return false;
5359}
5360
5361/// canAssignObjCInterfaces - Return true if the two interface types are
5362/// compatible for assignment from RHS to LHS.  This handles validation of any
5363/// protocol qualifiers on the LHS or RHS.
5364///
5365bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5366                                         const ObjCObjectPointerType *RHSOPT) {
5367  const ObjCObjectType* LHS = LHSOPT->getObjectType();
5368  const ObjCObjectType* RHS = RHSOPT->getObjectType();
5369
5370  // If either type represents the built-in 'id' or 'Class' types, return true.
5371  if (LHS->isObjCUnqualifiedIdOrClass() ||
5372      RHS->isObjCUnqualifiedIdOrClass())
5373    return true;
5374
5375  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
5376    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5377                                             QualType(RHSOPT,0),
5378                                             false);
5379
5380  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5381    return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5382                                                QualType(RHSOPT,0));
5383
5384  // If we have 2 user-defined types, fall into that path.
5385  if (LHS->getInterface() && RHS->getInterface())
5386    return canAssignObjCInterfaces(LHS, RHS);
5387
5388  return false;
5389}
5390
5391/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
5392/// for providing type-safety for objective-c pointers used to pass/return
5393/// arguments in block literals. When passed as arguments, passing 'A*' where
5394/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5395/// not OK. For the return type, the opposite is not OK.
5396bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5397                                         const ObjCObjectPointerType *LHSOPT,
5398                                         const ObjCObjectPointerType *RHSOPT,
5399                                         bool BlockReturnType) {
5400  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
5401    return true;
5402
5403  if (LHSOPT->isObjCBuiltinType()) {
5404    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5405  }
5406
5407  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
5408    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5409                                             QualType(RHSOPT,0),
5410                                             false);
5411
5412  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5413  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5414  if (LHS && RHS)  { // We have 2 user-defined types.
5415    if (LHS != RHS) {
5416      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
5417        return BlockReturnType;
5418      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
5419        return !BlockReturnType;
5420    }
5421    else
5422      return true;
5423  }
5424  return false;
5425}
5426
5427/// getIntersectionOfProtocols - This routine finds the intersection of set
5428/// of protocols inherited from two distinct objective-c pointer objects.
5429/// It is used to build composite qualifier list of the composite type of
5430/// the conditional expression involving two objective-c pointer objects.
5431static
5432void getIntersectionOfProtocols(ASTContext &Context,
5433                                const ObjCObjectPointerType *LHSOPT,
5434                                const ObjCObjectPointerType *RHSOPT,
5435      SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5436
5437  const ObjCObjectType* LHS = LHSOPT->getObjectType();
5438  const ObjCObjectType* RHS = RHSOPT->getObjectType();
5439  assert(LHS->getInterface() && "LHS must have an interface base");
5440  assert(RHS->getInterface() && "RHS must have an interface base");
5441
5442  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5443  unsigned LHSNumProtocols = LHS->getNumProtocols();
5444  if (LHSNumProtocols > 0)
5445    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5446  else {
5447    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5448    Context.CollectInheritedProtocols(LHS->getInterface(),
5449                                      LHSInheritedProtocols);
5450    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5451                                LHSInheritedProtocols.end());
5452  }
5453
5454  unsigned RHSNumProtocols = RHS->getNumProtocols();
5455  if (RHSNumProtocols > 0) {
5456    ObjCProtocolDecl **RHSProtocols =
5457      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
5458    for (unsigned i = 0; i < RHSNumProtocols; ++i)
5459      if (InheritedProtocolSet.count(RHSProtocols[i]))
5460        IntersectionOfProtocols.push_back(RHSProtocols[i]);
5461  } else {
5462    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
5463    Context.CollectInheritedProtocols(RHS->getInterface(),
5464                                      RHSInheritedProtocols);
5465    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5466         RHSInheritedProtocols.begin(),
5467         E = RHSInheritedProtocols.end(); I != E; ++I)
5468      if (InheritedProtocolSet.count((*I)))
5469        IntersectionOfProtocols.push_back((*I));
5470  }
5471}
5472
5473/// areCommonBaseCompatible - Returns common base class of the two classes if
5474/// one found. Note that this is O'2 algorithm. But it will be called as the
5475/// last type comparison in a ?-exp of ObjC pointer types before a
5476/// warning is issued. So, its invokation is extremely rare.
5477QualType ASTContext::areCommonBaseCompatible(
5478                                          const ObjCObjectPointerType *Lptr,
5479                                          const ObjCObjectPointerType *Rptr) {
5480  const ObjCObjectType *LHS = Lptr->getObjectType();
5481  const ObjCObjectType *RHS = Rptr->getObjectType();
5482  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5483  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
5484  if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
5485    return QualType();
5486
5487  do {
5488    LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
5489    if (canAssignObjCInterfaces(LHS, RHS)) {
5490      SmallVector<ObjCProtocolDecl *, 8> Protocols;
5491      getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5492
5493      QualType Result = QualType(LHS, 0);
5494      if (!Protocols.empty())
5495        Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5496      Result = getObjCObjectPointerType(Result);
5497      return Result;
5498    }
5499  } while ((LDecl = LDecl->getSuperClass()));
5500
5501  return QualType();
5502}
5503
5504bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5505                                         const ObjCObjectType *RHS) {
5506  assert(LHS->getInterface() && "LHS is not an interface type");
5507  assert(RHS->getInterface() && "RHS is not an interface type");
5508
5509  // Verify that the base decls are compatible: the RHS must be a subclass of
5510  // the LHS.
5511  if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
5512    return false;
5513
5514  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
5515  // protocol qualified at all, then we are good.
5516  if (LHS->getNumProtocols() == 0)
5517    return true;
5518
5519  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't,
5520  // more detailed analysis is required.
5521  if (RHS->getNumProtocols() == 0) {
5522    // OK, if LHS is a superclass of RHS *and*
5523    // this superclass is assignment compatible with LHS.
5524    // false otherwise.
5525    bool IsSuperClass =
5526      LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5527    if (IsSuperClass) {
5528      // OK if conversion of LHS to SuperClass results in narrowing of types
5529      // ; i.e., SuperClass may implement at least one of the protocols
5530      // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5531      // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5532      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
5533      CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
5534      // If super class has no protocols, it is not a match.
5535      if (SuperClassInheritedProtocols.empty())
5536        return false;
5537
5538      for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5539           LHSPE = LHS->qual_end();
5540           LHSPI != LHSPE; LHSPI++) {
5541        bool SuperImplementsProtocol = false;
5542        ObjCProtocolDecl *LHSProto = (*LHSPI);
5543
5544        for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5545             SuperClassInheritedProtocols.begin(),
5546             E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5547          ObjCProtocolDecl *SuperClassProto = (*I);
5548          if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5549            SuperImplementsProtocol = true;
5550            break;
5551          }
5552        }
5553        if (!SuperImplementsProtocol)
5554          return false;
5555      }
5556      return true;
5557    }
5558    return false;
5559  }
5560
5561  for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5562                                     LHSPE = LHS->qual_end();
5563       LHSPI != LHSPE; LHSPI++) {
5564    bool RHSImplementsProtocol = false;
5565
5566    // If the RHS doesn't implement the protocol on the left, the types
5567    // are incompatible.
5568    for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5569                                       RHSPE = RHS->qual_end();
5570         RHSPI != RHSPE; RHSPI++) {
5571      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
5572        RHSImplementsProtocol = true;
5573        break;
5574      }
5575    }
5576    // FIXME: For better diagnostics, consider passing back the protocol name.
5577    if (!RHSImplementsProtocol)
5578      return false;
5579  }
5580  // The RHS implements all protocols listed on the LHS.
5581  return true;
5582}
5583
5584bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5585  // get the "pointed to" types
5586  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5587  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
5588
5589  if (!LHSOPT || !RHSOPT)
5590    return false;
5591
5592  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5593         canAssignObjCInterfaces(RHSOPT, LHSOPT);
5594}
5595
5596bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5597  return canAssignObjCInterfaces(
5598                getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5599                getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5600}
5601
5602/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
5603/// both shall have the identically qualified version of a compatible type.
5604/// C99 6.2.7p1: Two types have compatible types if their types are the
5605/// same. See 6.7.[2,3,5] for additional rules.
5606bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5607                                    bool CompareUnqualified) {
5608  if (getLangOptions().CPlusPlus)
5609    return hasSameType(LHS, RHS);
5610
5611  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
5612}
5613
5614bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
5615  return typesAreCompatible(LHS, RHS);
5616}
5617
5618bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5619  return !mergeTypes(LHS, RHS, true).isNull();
5620}
5621
5622/// mergeTransparentUnionType - if T is a transparent union type and a member
5623/// of T is compatible with SubType, return the merged type, else return
5624/// QualType()
5625QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5626                                               bool OfBlockPointer,
5627                                               bool Unqualified) {
5628  if (const RecordType *UT = T->getAsUnionType()) {
5629    RecordDecl *UD = UT->getDecl();
5630    if (UD->hasAttr<TransparentUnionAttr>()) {
5631      for (RecordDecl::field_iterator it = UD->field_begin(),
5632           itend = UD->field_end(); it != itend; ++it) {
5633        QualType ET = it->getType().getUnqualifiedType();
5634        QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5635        if (!MT.isNull())
5636          return MT;
5637      }
5638    }
5639  }
5640
5641  return QualType();
5642}
5643
5644/// mergeFunctionArgumentTypes - merge two types which appear as function
5645/// argument types
5646QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5647                                                bool OfBlockPointer,
5648                                                bool Unqualified) {
5649  // GNU extension: two types are compatible if they appear as a function
5650  // argument, one of the types is a transparent union type and the other
5651  // type is compatible with a union member
5652  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5653                                              Unqualified);
5654  if (!lmerge.isNull())
5655    return lmerge;
5656
5657  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5658                                              Unqualified);
5659  if (!rmerge.isNull())
5660    return rmerge;
5661
5662  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5663}
5664
5665QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
5666                                        bool OfBlockPointer,
5667                                        bool Unqualified) {
5668  const FunctionType *lbase = lhs->getAs<FunctionType>();
5669  const FunctionType *rbase = rhs->getAs<FunctionType>();
5670  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
5671  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
5672  bool allLTypes = true;
5673  bool allRTypes = true;
5674
5675  // Check return type
5676  QualType retType;
5677  if (OfBlockPointer) {
5678    QualType RHS = rbase->getResultType();
5679    QualType LHS = lbase->getResultType();
5680    bool UnqualifiedResult = Unqualified;
5681    if (!UnqualifiedResult)
5682      UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
5683    retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
5684  }
5685  else
5686    retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
5687                         Unqualified);
5688  if (retType.isNull()) return QualType();
5689
5690  if (Unqualified)
5691    retType = retType.getUnqualifiedType();
5692
5693  CanQualType LRetType = getCanonicalType(lbase->getResultType());
5694  CanQualType RRetType = getCanonicalType(rbase->getResultType());
5695  if (Unqualified) {
5696    LRetType = LRetType.getUnqualifiedType();
5697    RRetType = RRetType.getUnqualifiedType();
5698  }
5699
5700  if (getCanonicalType(retType) != LRetType)
5701    allLTypes = false;
5702  if (getCanonicalType(retType) != RRetType)
5703    allRTypes = false;
5704
5705  // FIXME: double check this
5706  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
5707  //                           rbase->getRegParmAttr() != 0 &&
5708  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
5709  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
5710  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
5711
5712  // Compatible functions must have compatible calling conventions
5713  if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
5714    return QualType();
5715
5716  // Regparm is part of the calling convention.
5717  if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
5718    return QualType();
5719  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
5720    return QualType();
5721
5722  if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
5723    return QualType();
5724
5725  // functypes which return are preferred over those that do not.
5726  if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
5727    allLTypes = false;
5728  else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
5729    allRTypes = false;
5730  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
5731  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
5732
5733  FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
5734
5735  if (lproto && rproto) { // two C99 style function prototypes
5736    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
5737           "C++ shouldn't be here");
5738    unsigned lproto_nargs = lproto->getNumArgs();
5739    unsigned rproto_nargs = rproto->getNumArgs();
5740
5741    // Compatible functions must have the same number of arguments
5742    if (lproto_nargs != rproto_nargs)
5743      return QualType();
5744
5745    // Variadic and non-variadic functions aren't compatible
5746    if (lproto->isVariadic() != rproto->isVariadic())
5747      return QualType();
5748
5749    if (lproto->getTypeQuals() != rproto->getTypeQuals())
5750      return QualType();
5751
5752    if (LangOpts.ObjCAutoRefCount &&
5753        !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
5754      return QualType();
5755
5756    // Check argument compatibility
5757    SmallVector<QualType, 10> types;
5758    for (unsigned i = 0; i < lproto_nargs; i++) {
5759      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
5760      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
5761      QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
5762                                                    OfBlockPointer,
5763                                                    Unqualified);
5764      if (argtype.isNull()) return QualType();
5765
5766      if (Unqualified)
5767        argtype = argtype.getUnqualifiedType();
5768
5769      types.push_back(argtype);
5770      if (Unqualified) {
5771        largtype = largtype.getUnqualifiedType();
5772        rargtype = rargtype.getUnqualifiedType();
5773      }
5774
5775      if (getCanonicalType(argtype) != getCanonicalType(largtype))
5776        allLTypes = false;
5777      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
5778        allRTypes = false;
5779    }
5780
5781    if (allLTypes) return lhs;
5782    if (allRTypes) return rhs;
5783
5784    FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
5785    EPI.ExtInfo = einfo;
5786    return getFunctionType(retType, types.begin(), types.size(), EPI);
5787  }
5788
5789  if (lproto) allRTypes = false;
5790  if (rproto) allLTypes = false;
5791
5792  const FunctionProtoType *proto = lproto ? lproto : rproto;
5793  if (proto) {
5794    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
5795    if (proto->isVariadic()) return QualType();
5796    // Check that the types are compatible with the types that
5797    // would result from default argument promotions (C99 6.7.5.3p15).
5798    // The only types actually affected are promotable integer
5799    // types and floats, which would be passed as a different
5800    // type depending on whether the prototype is visible.
5801    unsigned proto_nargs = proto->getNumArgs();
5802    for (unsigned i = 0; i < proto_nargs; ++i) {
5803      QualType argTy = proto->getArgType(i);
5804
5805      // Look at the promotion type of enum types, since that is the type used
5806      // to pass enum values.
5807      if (const EnumType *Enum = argTy->getAs<EnumType>())
5808        argTy = Enum->getDecl()->getPromotionType();
5809
5810      if (argTy->isPromotableIntegerType() ||
5811          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
5812        return QualType();
5813    }
5814
5815    if (allLTypes) return lhs;
5816    if (allRTypes) return rhs;
5817
5818    FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
5819    EPI.ExtInfo = einfo;
5820    return getFunctionType(retType, proto->arg_type_begin(),
5821                           proto->getNumArgs(), EPI);
5822  }
5823
5824  if (allLTypes) return lhs;
5825  if (allRTypes) return rhs;
5826  return getFunctionNoProtoType(retType, einfo);
5827}
5828
5829QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
5830                                bool OfBlockPointer,
5831                                bool Unqualified, bool BlockReturnType) {
5832  // C++ [expr]: If an expression initially has the type "reference to T", the
5833  // type is adjusted to "T" prior to any further analysis, the expression
5834  // designates the object or function denoted by the reference, and the
5835  // expression is an lvalue unless the reference is an rvalue reference and
5836  // the expression is a function call (possibly inside parentheses).
5837  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
5838  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
5839
5840  if (Unqualified) {
5841    LHS = LHS.getUnqualifiedType();
5842    RHS = RHS.getUnqualifiedType();
5843  }
5844
5845  QualType LHSCan = getCanonicalType(LHS),
5846           RHSCan = getCanonicalType(RHS);
5847
5848  // If two types are identical, they are compatible.
5849  if (LHSCan == RHSCan)
5850    return LHS;
5851
5852  // If the qualifiers are different, the types aren't compatible... mostly.
5853  Qualifiers LQuals = LHSCan.getLocalQualifiers();
5854  Qualifiers RQuals = RHSCan.getLocalQualifiers();
5855  if (LQuals != RQuals) {
5856    // If any of these qualifiers are different, we have a type
5857    // mismatch.
5858    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
5859        LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
5860        LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
5861      return QualType();
5862
5863    // Exactly one GC qualifier difference is allowed: __strong is
5864    // okay if the other type has no GC qualifier but is an Objective
5865    // C object pointer (i.e. implicitly strong by default).  We fix
5866    // this by pretending that the unqualified type was actually
5867    // qualified __strong.
5868    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
5869    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
5870    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
5871
5872    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
5873      return QualType();
5874
5875    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
5876      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
5877    }
5878    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
5879      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
5880    }
5881    return QualType();
5882  }
5883
5884  // Okay, qualifiers are equal.
5885
5886  Type::TypeClass LHSClass = LHSCan->getTypeClass();
5887  Type::TypeClass RHSClass = RHSCan->getTypeClass();
5888
5889  // We want to consider the two function types to be the same for these
5890  // comparisons, just force one to the other.
5891  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
5892  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
5893
5894  // Same as above for arrays
5895  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
5896    LHSClass = Type::ConstantArray;
5897  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
5898    RHSClass = Type::ConstantArray;
5899
5900  // ObjCInterfaces are just specialized ObjCObjects.
5901  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
5902  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
5903
5904  // Canonicalize ExtVector -> Vector.
5905  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
5906  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
5907
5908  // If the canonical type classes don't match.
5909  if (LHSClass != RHSClass) {
5910    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
5911    // a signed integer type, or an unsigned integer type.
5912    // Compatibility is based on the underlying type, not the promotion
5913    // type.
5914    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
5915      QualType TINT = ETy->getDecl()->getIntegerType();
5916      if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
5917        return RHS;
5918    }
5919    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
5920      QualType TINT = ETy->getDecl()->getIntegerType();
5921      if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
5922        return LHS;
5923    }
5924    // allow block pointer type to match an 'id' type.
5925    if (OfBlockPointer && !BlockReturnType) {
5926       if (LHS->isObjCIdType() && RHS->isBlockPointerType())
5927         return LHS;
5928      if (RHS->isObjCIdType() && LHS->isBlockPointerType())
5929        return RHS;
5930    }
5931
5932    return QualType();
5933  }
5934
5935  // The canonical type classes match.
5936  switch (LHSClass) {
5937#define TYPE(Class, Base)
5938#define ABSTRACT_TYPE(Class, Base)
5939#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
5940#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
5941#define DEPENDENT_TYPE(Class, Base) case Type::Class:
5942#include "clang/AST/TypeNodes.def"
5943    llvm_unreachable("Non-canonical and dependent types shouldn't get here");
5944
5945  case Type::LValueReference:
5946  case Type::RValueReference:
5947  case Type::MemberPointer:
5948    llvm_unreachable("C++ should never be in mergeTypes");
5949
5950  case Type::ObjCInterface:
5951  case Type::IncompleteArray:
5952  case Type::VariableArray:
5953  case Type::FunctionProto:
5954  case Type::ExtVector:
5955    llvm_unreachable("Types are eliminated above");
5956
5957  case Type::Pointer:
5958  {
5959    // Merge two pointer types, while trying to preserve typedef info
5960    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
5961    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
5962    if (Unqualified) {
5963      LHSPointee = LHSPointee.getUnqualifiedType();
5964      RHSPointee = RHSPointee.getUnqualifiedType();
5965    }
5966    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
5967                                     Unqualified);
5968    if (ResultType.isNull()) return QualType();
5969    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5970      return LHS;
5971    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5972      return RHS;
5973    return getPointerType(ResultType);
5974  }
5975  case Type::BlockPointer:
5976  {
5977    // Merge two block pointer types, while trying to preserve typedef info
5978    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
5979    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
5980    if (Unqualified) {
5981      LHSPointee = LHSPointee.getUnqualifiedType();
5982      RHSPointee = RHSPointee.getUnqualifiedType();
5983    }
5984    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
5985                                     Unqualified);
5986    if (ResultType.isNull()) return QualType();
5987    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
5988      return LHS;
5989    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
5990      return RHS;
5991    return getBlockPointerType(ResultType);
5992  }
5993  case Type::Atomic:
5994  {
5995    // Merge two pointer types, while trying to preserve typedef info
5996    QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
5997    QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
5998    if (Unqualified) {
5999      LHSValue = LHSValue.getUnqualifiedType();
6000      RHSValue = RHSValue.getUnqualifiedType();
6001    }
6002    QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6003                                     Unqualified);
6004    if (ResultType.isNull()) return QualType();
6005    if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6006      return LHS;
6007    if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6008      return RHS;
6009    return getAtomicType(ResultType);
6010  }
6011  case Type::ConstantArray:
6012  {
6013    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6014    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6015    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6016      return QualType();
6017
6018    QualType LHSElem = getAsArrayType(LHS)->getElementType();
6019    QualType RHSElem = getAsArrayType(RHS)->getElementType();
6020    if (Unqualified) {
6021      LHSElem = LHSElem.getUnqualifiedType();
6022      RHSElem = RHSElem.getUnqualifiedType();
6023    }
6024
6025    QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
6026    if (ResultType.isNull()) return QualType();
6027    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6028      return LHS;
6029    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6030      return RHS;
6031    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6032                                          ArrayType::ArraySizeModifier(), 0);
6033    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6034                                          ArrayType::ArraySizeModifier(), 0);
6035    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6036    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
6037    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6038      return LHS;
6039    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6040      return RHS;
6041    if (LVAT) {
6042      // FIXME: This isn't correct! But tricky to implement because
6043      // the array's size has to be the size of LHS, but the type
6044      // has to be different.
6045      return LHS;
6046    }
6047    if (RVAT) {
6048      // FIXME: This isn't correct! But tricky to implement because
6049      // the array's size has to be the size of RHS, but the type
6050      // has to be different.
6051      return RHS;
6052    }
6053    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6054    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
6055    return getIncompleteArrayType(ResultType,
6056                                  ArrayType::ArraySizeModifier(), 0);
6057  }
6058  case Type::FunctionNoProto:
6059    return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
6060  case Type::Record:
6061  case Type::Enum:
6062    return QualType();
6063  case Type::Builtin:
6064    // Only exactly equal builtin types are compatible, which is tested above.
6065    return QualType();
6066  case Type::Complex:
6067    // Distinct complex types are incompatible.
6068    return QualType();
6069  case Type::Vector:
6070    // FIXME: The merged type should be an ExtVector!
6071    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6072                             RHSCan->getAs<VectorType>()))
6073      return LHS;
6074    return QualType();
6075  case Type::ObjCObject: {
6076    // Check if the types are assignment compatible.
6077    // FIXME: This should be type compatibility, e.g. whether
6078    // "LHS x; RHS x;" at global scope is legal.
6079    const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6080    const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6081    if (canAssignObjCInterfaces(LHSIface, RHSIface))
6082      return LHS;
6083
6084    return QualType();
6085  }
6086  case Type::ObjCObjectPointer: {
6087    if (OfBlockPointer) {
6088      if (canAssignObjCInterfacesInBlockPointer(
6089                                          LHS->getAs<ObjCObjectPointerType>(),
6090                                          RHS->getAs<ObjCObjectPointerType>(),
6091                                          BlockReturnType))
6092        return LHS;
6093      return QualType();
6094    }
6095    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6096                                RHS->getAs<ObjCObjectPointerType>()))
6097      return LHS;
6098
6099    return QualType();
6100  }
6101  }
6102
6103  llvm_unreachable("Invalid Type::Class!");
6104}
6105
6106bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6107                   const FunctionProtoType *FromFunctionType,
6108                   const FunctionProtoType *ToFunctionType) {
6109  if (FromFunctionType->hasAnyConsumedArgs() !=
6110      ToFunctionType->hasAnyConsumedArgs())
6111    return false;
6112  FunctionProtoType::ExtProtoInfo FromEPI =
6113    FromFunctionType->getExtProtoInfo();
6114  FunctionProtoType::ExtProtoInfo ToEPI =
6115    ToFunctionType->getExtProtoInfo();
6116  if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6117    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6118         ArgIdx != NumArgs; ++ArgIdx)  {
6119      if (FromEPI.ConsumedArguments[ArgIdx] !=
6120          ToEPI.ConsumedArguments[ArgIdx])
6121        return false;
6122    }
6123  return true;
6124}
6125
6126/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6127/// 'RHS' attributes and returns the merged version; including for function
6128/// return types.
6129QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6130  QualType LHSCan = getCanonicalType(LHS),
6131  RHSCan = getCanonicalType(RHS);
6132  // If two types are identical, they are compatible.
6133  if (LHSCan == RHSCan)
6134    return LHS;
6135  if (RHSCan->isFunctionType()) {
6136    if (!LHSCan->isFunctionType())
6137      return QualType();
6138    QualType OldReturnType =
6139      cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6140    QualType NewReturnType =
6141      cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6142    QualType ResReturnType =
6143      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6144    if (ResReturnType.isNull())
6145      return QualType();
6146    if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6147      // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6148      // In either case, use OldReturnType to build the new function type.
6149      const FunctionType *F = LHS->getAs<FunctionType>();
6150      if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
6151        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6152        EPI.ExtInfo = getFunctionExtInfo(LHS);
6153        QualType ResultType
6154          = getFunctionType(OldReturnType, FPT->arg_type_begin(),
6155                            FPT->getNumArgs(), EPI);
6156        return ResultType;
6157      }
6158    }
6159    return QualType();
6160  }
6161
6162  // If the qualifiers are different, the types can still be merged.
6163  Qualifiers LQuals = LHSCan.getLocalQualifiers();
6164  Qualifiers RQuals = RHSCan.getLocalQualifiers();
6165  if (LQuals != RQuals) {
6166    // If any of these qualifiers are different, we have a type mismatch.
6167    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6168        LQuals.getAddressSpace() != RQuals.getAddressSpace())
6169      return QualType();
6170
6171    // Exactly one GC qualifier difference is allowed: __strong is
6172    // okay if the other type has no GC qualifier but is an Objective
6173    // C object pointer (i.e. implicitly strong by default).  We fix
6174    // this by pretending that the unqualified type was actually
6175    // qualified __strong.
6176    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6177    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6178    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6179
6180    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6181      return QualType();
6182
6183    if (GC_L == Qualifiers::Strong)
6184      return LHS;
6185    if (GC_R == Qualifiers::Strong)
6186      return RHS;
6187    return QualType();
6188  }
6189
6190  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6191    QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6192    QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6193    QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6194    if (ResQT == LHSBaseQT)
6195      return LHS;
6196    if (ResQT == RHSBaseQT)
6197      return RHS;
6198  }
6199  return QualType();
6200}
6201
6202//===----------------------------------------------------------------------===//
6203//                         Integer Predicates
6204//===----------------------------------------------------------------------===//
6205
6206unsigned ASTContext::getIntWidth(QualType T) const {
6207  if (const EnumType *ET = dyn_cast<EnumType>(T))
6208    T = ET->getDecl()->getIntegerType();
6209  if (T->isBooleanType())
6210    return 1;
6211  // For builtin types, just use the standard type sizing method
6212  return (unsigned)getTypeSize(T);
6213}
6214
6215QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
6216  assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
6217
6218  // Turn <4 x signed int> -> <4 x unsigned int>
6219  if (const VectorType *VTy = T->getAs<VectorType>())
6220    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
6221                         VTy->getNumElements(), VTy->getVectorKind());
6222
6223  // For enums, we return the unsigned version of the base type.
6224  if (const EnumType *ETy = T->getAs<EnumType>())
6225    T = ETy->getDecl()->getIntegerType();
6226
6227  const BuiltinType *BTy = T->getAs<BuiltinType>();
6228  assert(BTy && "Unexpected signed integer type");
6229  switch (BTy->getKind()) {
6230  case BuiltinType::Char_S:
6231  case BuiltinType::SChar:
6232    return UnsignedCharTy;
6233  case BuiltinType::Short:
6234    return UnsignedShortTy;
6235  case BuiltinType::Int:
6236    return UnsignedIntTy;
6237  case BuiltinType::Long:
6238    return UnsignedLongTy;
6239  case BuiltinType::LongLong:
6240    return UnsignedLongLongTy;
6241  case BuiltinType::Int128:
6242    return UnsignedInt128Ty;
6243  default:
6244    llvm_unreachable("Unexpected signed integer type");
6245  }
6246}
6247
6248ASTMutationListener::~ASTMutationListener() { }
6249
6250
6251//===----------------------------------------------------------------------===//
6252//                          Builtin Type Computation
6253//===----------------------------------------------------------------------===//
6254
6255/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
6256/// pointer over the consumed characters.  This returns the resultant type.  If
6257/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6258/// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
6259/// a vector of "i*".
6260///
6261/// RequiresICE is filled in on return to indicate whether the value is required
6262/// to be an Integer Constant Expression.
6263static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
6264                                  ASTContext::GetBuiltinTypeError &Error,
6265                                  bool &RequiresICE,
6266                                  bool AllowTypeModifiers) {
6267  // Modifiers.
6268  int HowLong = 0;
6269  bool Signed = false, Unsigned = false;
6270  RequiresICE = false;
6271
6272  // Read the prefixed modifiers first.
6273  bool Done = false;
6274  while (!Done) {
6275    switch (*Str++) {
6276    default: Done = true; --Str; break;
6277    case 'I':
6278      RequiresICE = true;
6279      break;
6280    case 'S':
6281      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6282      assert(!Signed && "Can't use 'S' modifier multiple times!");
6283      Signed = true;
6284      break;
6285    case 'U':
6286      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6287      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6288      Unsigned = true;
6289      break;
6290    case 'L':
6291      assert(HowLong <= 2 && "Can't have LLLL modifier");
6292      ++HowLong;
6293      break;
6294    }
6295  }
6296
6297  QualType Type;
6298
6299  // Read the base type.
6300  switch (*Str++) {
6301  default: llvm_unreachable("Unknown builtin type letter!");
6302  case 'v':
6303    assert(HowLong == 0 && !Signed && !Unsigned &&
6304           "Bad modifiers used with 'v'!");
6305    Type = Context.VoidTy;
6306    break;
6307  case 'f':
6308    assert(HowLong == 0 && !Signed && !Unsigned &&
6309           "Bad modifiers used with 'f'!");
6310    Type = Context.FloatTy;
6311    break;
6312  case 'd':
6313    assert(HowLong < 2 && !Signed && !Unsigned &&
6314           "Bad modifiers used with 'd'!");
6315    if (HowLong)
6316      Type = Context.LongDoubleTy;
6317    else
6318      Type = Context.DoubleTy;
6319    break;
6320  case 's':
6321    assert(HowLong == 0 && "Bad modifiers used with 's'!");
6322    if (Unsigned)
6323      Type = Context.UnsignedShortTy;
6324    else
6325      Type = Context.ShortTy;
6326    break;
6327  case 'i':
6328    if (HowLong == 3)
6329      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6330    else if (HowLong == 2)
6331      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6332    else if (HowLong == 1)
6333      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6334    else
6335      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6336    break;
6337  case 'c':
6338    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6339    if (Signed)
6340      Type = Context.SignedCharTy;
6341    else if (Unsigned)
6342      Type = Context.UnsignedCharTy;
6343    else
6344      Type = Context.CharTy;
6345    break;
6346  case 'b': // boolean
6347    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6348    Type = Context.BoolTy;
6349    break;
6350  case 'z':  // size_t.
6351    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6352    Type = Context.getSizeType();
6353    break;
6354  case 'F':
6355    Type = Context.getCFConstantStringType();
6356    break;
6357  case 'G':
6358    Type = Context.getObjCIdType();
6359    break;
6360  case 'H':
6361    Type = Context.getObjCSelType();
6362    break;
6363  case 'a':
6364    Type = Context.getBuiltinVaListType();
6365    assert(!Type.isNull() && "builtin va list type not initialized!");
6366    break;
6367  case 'A':
6368    // This is a "reference" to a va_list; however, what exactly
6369    // this means depends on how va_list is defined. There are two
6370    // different kinds of va_list: ones passed by value, and ones
6371    // passed by reference.  An example of a by-value va_list is
6372    // x86, where va_list is a char*. An example of by-ref va_list
6373    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6374    // we want this argument to be a char*&; for x86-64, we want
6375    // it to be a __va_list_tag*.
6376    Type = Context.getBuiltinVaListType();
6377    assert(!Type.isNull() && "builtin va list type not initialized!");
6378    if (Type->isArrayType())
6379      Type = Context.getArrayDecayedType(Type);
6380    else
6381      Type = Context.getLValueReferenceType(Type);
6382    break;
6383  case 'V': {
6384    char *End;
6385    unsigned NumElements = strtoul(Str, &End, 10);
6386    assert(End != Str && "Missing vector size");
6387    Str = End;
6388
6389    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6390                                             RequiresICE, false);
6391    assert(!RequiresICE && "Can't require vector ICE");
6392
6393    // TODO: No way to make AltiVec vectors in builtins yet.
6394    Type = Context.getVectorType(ElementType, NumElements,
6395                                 VectorType::GenericVector);
6396    break;
6397  }
6398  case 'X': {
6399    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6400                                             false);
6401    assert(!RequiresICE && "Can't require complex ICE");
6402    Type = Context.getComplexType(ElementType);
6403    break;
6404  }
6405  case 'Y' : {
6406    Type = Context.getPointerDiffType();
6407    break;
6408  }
6409  case 'P':
6410    Type = Context.getFILEType();
6411    if (Type.isNull()) {
6412      Error = ASTContext::GE_Missing_stdio;
6413      return QualType();
6414    }
6415    break;
6416  case 'J':
6417    if (Signed)
6418      Type = Context.getsigjmp_bufType();
6419    else
6420      Type = Context.getjmp_bufType();
6421
6422    if (Type.isNull()) {
6423      Error = ASTContext::GE_Missing_setjmp;
6424      return QualType();
6425    }
6426    break;
6427  case 'K':
6428    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6429    Type = Context.getucontext_tType();
6430
6431    if (Type.isNull()) {
6432      Error = ASTContext::GE_Missing_ucontext;
6433      return QualType();
6434    }
6435    break;
6436  }
6437
6438  // If there are modifiers and if we're allowed to parse them, go for it.
6439  Done = !AllowTypeModifiers;
6440  while (!Done) {
6441    switch (char c = *Str++) {
6442    default: Done = true; --Str; break;
6443    case '*':
6444    case '&': {
6445      // Both pointers and references can have their pointee types
6446      // qualified with an address space.
6447      char *End;
6448      unsigned AddrSpace = strtoul(Str, &End, 10);
6449      if (End != Str && AddrSpace != 0) {
6450        Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6451        Str = End;
6452      }
6453      if (c == '*')
6454        Type = Context.getPointerType(Type);
6455      else
6456        Type = Context.getLValueReferenceType(Type);
6457      break;
6458    }
6459    // FIXME: There's no way to have a built-in with an rvalue ref arg.
6460    case 'C':
6461      Type = Type.withConst();
6462      break;
6463    case 'D':
6464      Type = Context.getVolatileType(Type);
6465      break;
6466    case 'R':
6467      Type = Type.withRestrict();
6468      break;
6469    }
6470  }
6471
6472  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
6473         "Integer constant 'I' type must be an integer");
6474
6475  return Type;
6476}
6477
6478/// GetBuiltinType - Return the type for the specified builtin.
6479QualType ASTContext::GetBuiltinType(unsigned Id,
6480                                    GetBuiltinTypeError &Error,
6481                                    unsigned *IntegerConstantArgs) const {
6482  const char *TypeStr = BuiltinInfo.GetTypeString(Id);
6483
6484  SmallVector<QualType, 8> ArgTypes;
6485
6486  bool RequiresICE = false;
6487  Error = GE_None;
6488  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6489                                       RequiresICE, true);
6490  if (Error != GE_None)
6491    return QualType();
6492
6493  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6494
6495  while (TypeStr[0] && TypeStr[0] != '.') {
6496    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
6497    if (Error != GE_None)
6498      return QualType();
6499
6500    // If this argument is required to be an IntegerConstantExpression and the
6501    // caller cares, fill in the bitmask we return.
6502    if (RequiresICE && IntegerConstantArgs)
6503      *IntegerConstantArgs |= 1 << ArgTypes.size();
6504
6505    // Do array -> pointer decay.  The builtin should use the decayed type.
6506    if (Ty->isArrayType())
6507      Ty = getArrayDecayedType(Ty);
6508
6509    ArgTypes.push_back(Ty);
6510  }
6511
6512  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6513         "'.' should only occur at end of builtin type list!");
6514
6515  FunctionType::ExtInfo EI;
6516  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6517
6518  bool Variadic = (TypeStr[0] == '.');
6519
6520  // We really shouldn't be making a no-proto type here, especially in C++.
6521  if (ArgTypes.empty() && Variadic)
6522    return getFunctionNoProtoType(ResType, EI);
6523
6524  FunctionProtoType::ExtProtoInfo EPI;
6525  EPI.ExtInfo = EI;
6526  EPI.Variadic = Variadic;
6527
6528  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
6529}
6530
6531GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6532  GVALinkage External = GVA_StrongExternal;
6533
6534  Linkage L = FD->getLinkage();
6535  switch (L) {
6536  case NoLinkage:
6537  case InternalLinkage:
6538  case UniqueExternalLinkage:
6539    return GVA_Internal;
6540
6541  case ExternalLinkage:
6542    switch (FD->getTemplateSpecializationKind()) {
6543    case TSK_Undeclared:
6544    case TSK_ExplicitSpecialization:
6545      External = GVA_StrongExternal;
6546      break;
6547
6548    case TSK_ExplicitInstantiationDefinition:
6549      return GVA_ExplicitTemplateInstantiation;
6550
6551    case TSK_ExplicitInstantiationDeclaration:
6552    case TSK_ImplicitInstantiation:
6553      External = GVA_TemplateInstantiation;
6554      break;
6555    }
6556  }
6557
6558  if (!FD->isInlined())
6559    return External;
6560
6561  if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6562    // GNU or C99 inline semantics. Determine whether this symbol should be
6563    // externally visible.
6564    if (FD->isInlineDefinitionExternallyVisible())
6565      return External;
6566
6567    // C99 inline semantics, where the symbol is not externally visible.
6568    return GVA_C99Inline;
6569  }
6570
6571  // C++0x [temp.explicit]p9:
6572  //   [ Note: The intent is that an inline function that is the subject of
6573  //   an explicit instantiation declaration will still be implicitly
6574  //   instantiated when used so that the body can be considered for
6575  //   inlining, but that no out-of-line copy of the inline function would be
6576  //   generated in the translation unit. -- end note ]
6577  if (FD->getTemplateSpecializationKind()
6578                                       == TSK_ExplicitInstantiationDeclaration)
6579    return GVA_C99Inline;
6580
6581  return GVA_CXXInline;
6582}
6583
6584GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6585  // If this is a static data member, compute the kind of template
6586  // specialization. Otherwise, this variable is not part of a
6587  // template.
6588  TemplateSpecializationKind TSK = TSK_Undeclared;
6589  if (VD->isStaticDataMember())
6590    TSK = VD->getTemplateSpecializationKind();
6591
6592  Linkage L = VD->getLinkage();
6593  if (L == ExternalLinkage && getLangOptions().CPlusPlus &&
6594      VD->getType()->getLinkage() == UniqueExternalLinkage)
6595    L = UniqueExternalLinkage;
6596
6597  switch (L) {
6598  case NoLinkage:
6599  case InternalLinkage:
6600  case UniqueExternalLinkage:
6601    return GVA_Internal;
6602
6603  case ExternalLinkage:
6604    switch (TSK) {
6605    case TSK_Undeclared:
6606    case TSK_ExplicitSpecialization:
6607      return GVA_StrongExternal;
6608
6609    case TSK_ExplicitInstantiationDeclaration:
6610      llvm_unreachable("Variable should not be instantiated");
6611      // Fall through to treat this like any other instantiation.
6612
6613    case TSK_ExplicitInstantiationDefinition:
6614      return GVA_ExplicitTemplateInstantiation;
6615
6616    case TSK_ImplicitInstantiation:
6617      return GVA_TemplateInstantiation;
6618    }
6619  }
6620
6621  llvm_unreachable("Invalid Linkage!");
6622}
6623
6624bool ASTContext::DeclMustBeEmitted(const Decl *D) {
6625  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6626    if (!VD->isFileVarDecl())
6627      return false;
6628  } else if (!isa<FunctionDecl>(D))
6629    return false;
6630
6631  // Weak references don't produce any output by themselves.
6632  if (D->hasAttr<WeakRefAttr>())
6633    return false;
6634
6635  // Aliases and used decls are required.
6636  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6637    return true;
6638
6639  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6640    // Forward declarations aren't required.
6641    if (!FD->doesThisDeclarationHaveABody())
6642      return FD->doesDeclarationForceExternallyVisibleDefinition();
6643
6644    // Constructors and destructors are required.
6645    if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6646      return true;
6647
6648    // The key function for a class is required.
6649    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6650      const CXXRecordDecl *RD = MD->getParent();
6651      if (MD->isOutOfLine() && RD->isDynamicClass()) {
6652        const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
6653        if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
6654          return true;
6655      }
6656    }
6657
6658    GVALinkage Linkage = GetGVALinkageForFunction(FD);
6659
6660    // static, static inline, always_inline, and extern inline functions can
6661    // always be deferred.  Normal inline functions can be deferred in C99/C++.
6662    // Implicit template instantiations can also be deferred in C++.
6663    if (Linkage == GVA_Internal  || Linkage == GVA_C99Inline ||
6664        Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
6665      return false;
6666    return true;
6667  }
6668
6669  const VarDecl *VD = cast<VarDecl>(D);
6670  assert(VD->isFileVarDecl() && "Expected file scoped var");
6671
6672  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
6673    return false;
6674
6675  // Structs that have non-trivial constructors or destructors are required.
6676
6677  // FIXME: Handle references.
6678  // FIXME: Be more selective about which constructors we care about.
6679  if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
6680    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
6681      if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
6682                                   RD->hasTrivialCopyConstructor() &&
6683                                   RD->hasTrivialMoveConstructor() &&
6684                                   RD->hasTrivialDestructor()))
6685        return true;
6686    }
6687  }
6688
6689  GVALinkage L = GetGVALinkageForVariable(VD);
6690  if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
6691    if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
6692      return false;
6693  }
6694
6695  return true;
6696}
6697
6698CallingConv ASTContext::getDefaultMethodCallConv() {
6699  // Pass through to the C++ ABI object
6700  return ABI->getDefaultMethodCallConv();
6701}
6702
6703bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
6704  // Pass through to the C++ ABI object
6705  return ABI->isNearlyEmpty(RD);
6706}
6707
6708MangleContext *ASTContext::createMangleContext() {
6709  switch (Target->getCXXABI()) {
6710  case CXXABI_ARM:
6711  case CXXABI_Itanium:
6712    return createItaniumMangleContext(*this, getDiagnostics());
6713  case CXXABI_Microsoft:
6714    return createMicrosoftMangleContext(*this, getDiagnostics());
6715  }
6716  llvm_unreachable("Unsupported ABI");
6717}
6718
6719CXXABI::~CXXABI() {}
6720
6721size_t ASTContext::getSideTableAllocatedMemory() const {
6722  return ASTRecordLayouts.getMemorySize()
6723    + llvm::capacity_in_bytes(ObjCLayouts)
6724    + llvm::capacity_in_bytes(KeyFunctions)
6725    + llvm::capacity_in_bytes(ObjCImpls)
6726    + llvm::capacity_in_bytes(BlockVarCopyInits)
6727    + llvm::capacity_in_bytes(DeclAttrs)
6728    + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
6729    + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
6730    + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
6731    + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
6732    + llvm::capacity_in_bytes(OverriddenMethods)
6733    + llvm::capacity_in_bytes(Types)
6734    + llvm::capacity_in_bytes(VariableArrayTypes)
6735    + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
6736}
6737
6738unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
6739  CXXRecordDecl *Lambda = CallOperator->getParent();
6740  return LambdaMangleContexts[Lambda->getDeclContext()]
6741           .getManglingNumber(CallOperator);
6742}
6743
6744
6745void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
6746  ParamIndices[D] = index;
6747}
6748
6749unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
6750  ParameterIndexTable::const_iterator I = ParamIndices.find(D);
6751  assert(I != ParamIndices.end() &&
6752         "ParmIndices lacks entry set by ParmVarDecl");
6753  return I->second;
6754}
6755