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