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