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