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