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