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