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