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