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