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