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