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