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