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