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