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