ASTContext.cpp revision e4f2142d00fa5fdb580c4e2413da91882d955381
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/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExternalASTSource.h"
20#include "clang/AST/RecordLayout.h"
21#include "clang/Basic/Builtins.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/Support/MathExtras.h"
26#include "llvm/Support/MemoryBuffer.h"
27using namespace clang;
28
29enum FloatingRank {
30  FloatRank, DoubleRank, LongDoubleRank
31};
32
33ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
34                       TargetInfo &t,
35                       IdentifierTable &idents, SelectorTable &sels,
36                       Builtin::Context &builtins,
37                       bool FreeMem, unsigned size_reserve) :
38  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
39  ObjCFastEnumerationStateTypeDecl(0), SourceMgr(SM), LangOpts(LOpts),
40  FreeMemory(FreeMem), Target(t), Idents(idents), Selectors(sels),
41  BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts) {
42  if (size_reserve > 0) Types.reserve(size_reserve);
43  InitBuiltinTypes();
44  TUDecl = TranslationUnitDecl::Create(*this);
45}
46
47ASTContext::~ASTContext() {
48  // Deallocate all the types.
49  while (!Types.empty()) {
50    Types.back()->Destroy(*this);
51    Types.pop_back();
52  }
53
54  {
55    llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
56      I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end();
57    while (I != E) {
58      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
59      delete R;
60    }
61  }
62
63  {
64    llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>::iterator
65      I = ObjCLayouts.begin(), E = ObjCLayouts.end();
66    while (I != E) {
67      ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second);
68      delete R;
69    }
70  }
71
72  // Destroy nested-name-specifiers.
73  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
74         NNS = NestedNameSpecifiers.begin(),
75         NNSEnd = NestedNameSpecifiers.end();
76       NNS != NNSEnd;
77       /* Increment in loop */)
78    (*NNS++).Destroy(*this);
79
80  if (GlobalNestedNameSpecifier)
81    GlobalNestedNameSpecifier->Destroy(*this);
82
83  TUDecl->Destroy(*this);
84}
85
86void
87ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
88  ExternalSource.reset(Source.take());
89}
90
91void ASTContext::PrintStats() const {
92  fprintf(stderr, "*** AST Context Stats:\n");
93  fprintf(stderr, "  %d types total.\n", (int)Types.size());
94
95  unsigned counts[] = {
96#define TYPE(Name, Parent) 0,
97#define ABSTRACT_TYPE(Name, Parent)
98#include "clang/AST/TypeNodes.def"
99    0 // Extra
100  };
101
102  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
103    Type *T = Types[i];
104    counts[(unsigned)T->getTypeClass()]++;
105  }
106
107  unsigned Idx = 0;
108  unsigned TotalBytes = 0;
109#define TYPE(Name, Parent)                                              \
110  if (counts[Idx])                                                      \
111    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
112  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
113  ++Idx;
114#define ABSTRACT_TYPE(Name, Parent)
115#include "clang/AST/TypeNodes.def"
116
117  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
118
119  if (ExternalSource.get()) {
120    fprintf(stderr, "\n");
121    ExternalSource->PrintStats();
122  }
123}
124
125
126void ASTContext::InitBuiltinType(QualType &R, BuiltinType::Kind K) {
127  Types.push_back((R = QualType(new (*this,8) BuiltinType(K),0)).getTypePtr());
128}
129
130void ASTContext::InitBuiltinTypes() {
131  assert(VoidTy.isNull() && "Context reinitialized?");
132
133  // C99 6.2.5p19.
134  InitBuiltinType(VoidTy,              BuiltinType::Void);
135
136  // C99 6.2.5p2.
137  InitBuiltinType(BoolTy,              BuiltinType::Bool);
138  // C99 6.2.5p3.
139  if (LangOpts.CharIsSigned)
140    InitBuiltinType(CharTy,            BuiltinType::Char_S);
141  else
142    InitBuiltinType(CharTy,            BuiltinType::Char_U);
143  // C99 6.2.5p4.
144  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
145  InitBuiltinType(ShortTy,             BuiltinType::Short);
146  InitBuiltinType(IntTy,               BuiltinType::Int);
147  InitBuiltinType(LongTy,              BuiltinType::Long);
148  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
149
150  // C99 6.2.5p6.
151  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
152  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
153  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
154  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
155  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
156
157  // C99 6.2.5p10.
158  InitBuiltinType(FloatTy,             BuiltinType::Float);
159  InitBuiltinType(DoubleTy,            BuiltinType::Double);
160  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
161
162  // GNU extension, 128-bit integers.
163  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
164  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
165
166  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
167    InitBuiltinType(WCharTy,           BuiltinType::WChar);
168  else // C99
169    WCharTy = getFromTargetType(Target.getWCharType());
170
171  // Placeholder type for functions.
172  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
173
174  // Placeholder type for type-dependent expressions whose type is
175  // completely unknown. No code should ever check a type against
176  // DependentTy and users should never see it; however, it is here to
177  // help diagnose failures to properly check for type-dependent
178  // expressions.
179  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
180
181  // Placeholder type for C++0x auto declarations whose real type has
182  // not yet been deduced.
183  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
184
185  // C99 6.2.5p11.
186  FloatComplexTy      = getComplexType(FloatTy);
187  DoubleComplexTy     = getComplexType(DoubleTy);
188  LongDoubleComplexTy = getComplexType(LongDoubleTy);
189
190  BuiltinVaListType = QualType();
191  ObjCIdType = QualType();
192  IdStructType = 0;
193  ObjCClassType = QualType();
194  ClassStructType = 0;
195
196  ObjCConstantStringType = QualType();
197
198  // void * type
199  VoidPtrTy = getPointerType(VoidTy);
200
201  // nullptr type (C++0x 2.14.7)
202  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
203}
204
205//===----------------------------------------------------------------------===//
206//                         Type Sizing and Analysis
207//===----------------------------------------------------------------------===//
208
209/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
210/// scalar floating point type.
211const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
212  const BuiltinType *BT = T->getAsBuiltinType();
213  assert(BT && "Not a floating point type!");
214  switch (BT->getKind()) {
215  default: assert(0 && "Not a floating point type!");
216  case BuiltinType::Float:      return Target.getFloatFormat();
217  case BuiltinType::Double:     return Target.getDoubleFormat();
218  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
219  }
220}
221
222/// getDeclAlign - Return a conservative estimate of the alignment of the
223/// specified decl.  Note that bitfields do not have a valid alignment, so
224/// this method will assert on them.
225unsigned ASTContext::getDeclAlignInBytes(const Decl *D) {
226  unsigned Align = Target.getCharWidth();
227
228  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>(*this))
229    Align = std::max(Align, AA->getAlignment());
230
231  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
232    QualType T = VD->getType();
233    if (const ReferenceType* RT = T->getAsReferenceType()) {
234      unsigned AS = RT->getPointeeType().getAddressSpace();
235      Align = Target.getPointerAlign(AS);
236    } else if (!T->isIncompleteType() && !T->isFunctionType()) {
237      // Incomplete or function types default to 1.
238      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
239        T = cast<ArrayType>(T)->getElementType();
240
241      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
242    }
243  }
244
245  return Align / Target.getCharWidth();
246}
247
248/// getTypeSize - Return the size of the specified type, in bits.  This method
249/// does not work on incomplete types.
250std::pair<uint64_t, unsigned>
251ASTContext::getTypeInfo(const Type *T) {
252  uint64_t Width=0;
253  unsigned Align=8;
254  switch (T->getTypeClass()) {
255#define TYPE(Class, Base)
256#define ABSTRACT_TYPE(Class, Base)
257#define NON_CANONICAL_TYPE(Class, Base)
258#define DEPENDENT_TYPE(Class, Base) case Type::Class:
259#include "clang/AST/TypeNodes.def"
260    assert(false && "Should not see dependent types");
261    break;
262
263  case Type::FunctionNoProto:
264  case Type::FunctionProto:
265    // GCC extension: alignof(function) = 32 bits
266    Width = 0;
267    Align = 32;
268    break;
269
270  case Type::IncompleteArray:
271  case Type::VariableArray:
272    Width = 0;
273    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
274    break;
275
276  case Type::ConstantArray: {
277    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
278
279    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
280    Width = EltInfo.first*CAT->getSize().getZExtValue();
281    Align = EltInfo.second;
282    break;
283  }
284  case Type::ExtVector:
285  case Type::Vector: {
286    std::pair<uint64_t, unsigned> EltInfo =
287      getTypeInfo(cast<VectorType>(T)->getElementType());
288    Width = EltInfo.first*cast<VectorType>(T)->getNumElements();
289    Align = Width;
290    // If the alignment is not a power of 2, round up to the next power of 2.
291    // This happens for non-power-of-2 length vectors.
292    // FIXME: this should probably be a target property.
293    Align = 1 << llvm::Log2_32_Ceil(Align);
294    break;
295  }
296
297  case Type::Builtin:
298    switch (cast<BuiltinType>(T)->getKind()) {
299    default: assert(0 && "Unknown builtin type!");
300    case BuiltinType::Void:
301      // GCC extension: alignof(void) = 8 bits.
302      Width = 0;
303      Align = 8;
304      break;
305
306    case BuiltinType::Bool:
307      Width = Target.getBoolWidth();
308      Align = Target.getBoolAlign();
309      break;
310    case BuiltinType::Char_S:
311    case BuiltinType::Char_U:
312    case BuiltinType::UChar:
313    case BuiltinType::SChar:
314      Width = Target.getCharWidth();
315      Align = Target.getCharAlign();
316      break;
317    case BuiltinType::WChar:
318      Width = Target.getWCharWidth();
319      Align = Target.getWCharAlign();
320      break;
321    case BuiltinType::UShort:
322    case BuiltinType::Short:
323      Width = Target.getShortWidth();
324      Align = Target.getShortAlign();
325      break;
326    case BuiltinType::UInt:
327    case BuiltinType::Int:
328      Width = Target.getIntWidth();
329      Align = Target.getIntAlign();
330      break;
331    case BuiltinType::ULong:
332    case BuiltinType::Long:
333      Width = Target.getLongWidth();
334      Align = Target.getLongAlign();
335      break;
336    case BuiltinType::ULongLong:
337    case BuiltinType::LongLong:
338      Width = Target.getLongLongWidth();
339      Align = Target.getLongLongAlign();
340      break;
341    case BuiltinType::Int128:
342    case BuiltinType::UInt128:
343      Width = 128;
344      Align = 128; // int128_t is 128-bit aligned on all targets.
345      break;
346    case BuiltinType::Float:
347      Width = Target.getFloatWidth();
348      Align = Target.getFloatAlign();
349      break;
350    case BuiltinType::Double:
351      Width = Target.getDoubleWidth();
352      Align = Target.getDoubleAlign();
353      break;
354    case BuiltinType::LongDouble:
355      Width = Target.getLongDoubleWidth();
356      Align = Target.getLongDoubleAlign();
357      break;
358    case BuiltinType::NullPtr:
359      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
360      Align = Target.getPointerAlign(0); //   == sizeof(void*)
361      break;
362    }
363    break;
364  case Type::FixedWidthInt:
365    // FIXME: This isn't precisely correct; the width/alignment should depend
366    // on the available types for the target
367    Width = cast<FixedWidthIntType>(T)->getWidth();
368    Width = std::max(llvm::NextPowerOf2(Width - 1), (uint64_t)8);
369    Align = Width;
370    break;
371  case Type::ExtQual:
372    // FIXME: Pointers into different addr spaces could have different sizes and
373    // alignment requirements: getPointerInfo should take an AddrSpace.
374    return getTypeInfo(QualType(cast<ExtQualType>(T)->getBaseType(), 0));
375  case Type::ObjCObjectPointer:
376  case Type::ObjCQualifiedInterface:
377    Width = Target.getPointerWidth(0);
378    Align = Target.getPointerAlign(0);
379    break;
380  case Type::BlockPointer: {
381    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
382    Width = Target.getPointerWidth(AS);
383    Align = Target.getPointerAlign(AS);
384    break;
385  }
386  case Type::Pointer: {
387    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
388    Width = Target.getPointerWidth(AS);
389    Align = Target.getPointerAlign(AS);
390    break;
391  }
392  case Type::LValueReference:
393  case Type::RValueReference:
394    // "When applied to a reference or a reference type, the result is the size
395    // of the referenced type." C++98 5.3.3p2: expr.sizeof.
396    // FIXME: This is wrong for struct layout: a reference in a struct has
397    // pointer size.
398    return getTypeInfo(cast<ReferenceType>(T)->getPointeeType());
399  case Type::MemberPointer: {
400    // FIXME: This is ABI dependent. We use the Itanium C++ ABI.
401    // http://www.codesourcery.com/public/cxx-abi/abi.html#member-pointers
402    // If we ever want to support other ABIs this needs to be abstracted.
403
404    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
405    std::pair<uint64_t, unsigned> PtrDiffInfo =
406      getTypeInfo(getPointerDiffType());
407    Width = PtrDiffInfo.first;
408    if (Pointee->isFunctionType())
409      Width *= 2;
410    Align = PtrDiffInfo.second;
411    break;
412  }
413  case Type::Complex: {
414    // Complex types have the same alignment as their elements, but twice the
415    // size.
416    std::pair<uint64_t, unsigned> EltInfo =
417      getTypeInfo(cast<ComplexType>(T)->getElementType());
418    Width = EltInfo.first*2;
419    Align = EltInfo.second;
420    break;
421  }
422  case Type::ObjCInterface: {
423    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
424    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
425    Width = Layout.getSize();
426    Align = Layout.getAlignment();
427    break;
428  }
429  case Type::Record:
430  case Type::Enum: {
431    const TagType *TT = cast<TagType>(T);
432
433    if (TT->getDecl()->isInvalidDecl()) {
434      Width = 1;
435      Align = 1;
436      break;
437    }
438
439    if (const EnumType *ET = dyn_cast<EnumType>(TT))
440      return getTypeInfo(ET->getDecl()->getIntegerType());
441
442    const RecordType *RT = cast<RecordType>(TT);
443    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
444    Width = Layout.getSize();
445    Align = Layout.getAlignment();
446    break;
447  }
448
449  case Type::Typedef: {
450    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
451    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>(*this)) {
452      Align = Aligned->getAlignment();
453      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
454    } else
455      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
456    break;
457  }
458
459  case Type::TypeOfExpr:
460    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
461                         .getTypePtr());
462
463  case Type::TypeOf:
464    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
465
466  case Type::Decltype:
467    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
468                        .getTypePtr());
469
470  case Type::QualifiedName:
471    return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr());
472
473  case Type::TemplateSpecialization:
474    assert(getCanonicalType(T) != T &&
475           "Cannot request the size of a dependent type");
476    // FIXME: this is likely to be wrong once we support template
477    // aliases, since a template alias could refer to a typedef that
478    // has an __aligned__ attribute on it.
479    return getTypeInfo(getCanonicalType(T));
480  }
481
482  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
483  return std::make_pair(Width, Align);
484}
485
486/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
487/// type for the current target in bits.  This can be different than the ABI
488/// alignment in cases where it is beneficial for performance to overalign
489/// a data type.
490unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
491  unsigned ABIAlign = getTypeAlign(T);
492
493  // Double and long long should be naturally aligned if possible.
494  if (const ComplexType* CT = T->getAsComplexType())
495    T = CT->getElementType().getTypePtr();
496  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
497      T->isSpecificBuiltinType(BuiltinType::LongLong))
498    return std::max(ABIAlign, (unsigned)getTypeSize(T));
499
500  return ABIAlign;
501}
502
503
504/// LayoutField - Field layout.
505void ASTRecordLayout::LayoutField(const FieldDecl *FD, unsigned FieldNo,
506                                  bool IsUnion, unsigned StructPacking,
507                                  ASTContext &Context) {
508  unsigned FieldPacking = StructPacking;
509  uint64_t FieldOffset = IsUnion ? 0 : Size;
510  uint64_t FieldSize;
511  unsigned FieldAlign;
512
513  // FIXME: Should this override struct packing? Probably we want to
514  // take the minimum?
515  if (const PackedAttr *PA = FD->getAttr<PackedAttr>(Context))
516    FieldPacking = PA->getAlignment();
517
518  if (const Expr *BitWidthExpr = FD->getBitWidth()) {
519    // TODO: Need to check this algorithm on other targets!
520    //       (tested on Linux-X86)
521    FieldSize = BitWidthExpr->EvaluateAsInt(Context).getZExtValue();
522
523    std::pair<uint64_t, unsigned> FieldInfo =
524      Context.getTypeInfo(FD->getType());
525    uint64_t TypeSize = FieldInfo.first;
526
527    // Determine the alignment of this bitfield. The packing
528    // attributes define a maximum and the alignment attribute defines
529    // a minimum.
530    // FIXME: What is the right behavior when the specified alignment
531    // is smaller than the specified packing?
532    FieldAlign = FieldInfo.second;
533    if (FieldPacking)
534      FieldAlign = std::min(FieldAlign, FieldPacking);
535    if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>(Context))
536      FieldAlign = std::max(FieldAlign, AA->getAlignment());
537
538    // Check if we need to add padding to give the field the correct
539    // alignment.
540    if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
541      FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
542
543    // Padding members don't affect overall alignment
544    if (!FD->getIdentifier())
545      FieldAlign = 1;
546  } else {
547    if (FD->getType()->isIncompleteArrayType()) {
548      // This is a flexible array member; we can't directly
549      // query getTypeInfo about these, so we figure it out here.
550      // Flexible array members don't have any size, but they
551      // have to be aligned appropriately for their element type.
552      FieldSize = 0;
553      const ArrayType* ATy = Context.getAsArrayType(FD->getType());
554      FieldAlign = Context.getTypeAlign(ATy->getElementType());
555    } else if (const ReferenceType *RT = FD->getType()->getAsReferenceType()) {
556      unsigned AS = RT->getPointeeType().getAddressSpace();
557      FieldSize = Context.Target.getPointerWidth(AS);
558      FieldAlign = Context.Target.getPointerAlign(AS);
559    } else {
560      std::pair<uint64_t, unsigned> FieldInfo =
561        Context.getTypeInfo(FD->getType());
562      FieldSize = FieldInfo.first;
563      FieldAlign = FieldInfo.second;
564    }
565
566    // Determine the alignment of this bitfield. The packing
567    // attributes define a maximum and the alignment attribute defines
568    // a minimum. Additionally, the packing alignment must be at least
569    // a byte for non-bitfields.
570    //
571    // FIXME: What is the right behavior when the specified alignment
572    // is smaller than the specified packing?
573    if (FieldPacking)
574      FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
575    if (const AlignedAttr *AA = FD->getAttr<AlignedAttr>(Context))
576      FieldAlign = std::max(FieldAlign, AA->getAlignment());
577
578    // Round up the current record size to the field's alignment boundary.
579    FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
580  }
581
582  // Place this field at the current location.
583  FieldOffsets[FieldNo] = FieldOffset;
584
585  // Reserve space for this field.
586  if (IsUnion) {
587    Size = std::max(Size, FieldSize);
588  } else {
589    Size = FieldOffset + FieldSize;
590  }
591
592  // Remember the next available offset.
593  NextOffset = Size;
594
595  // Remember max struct/class alignment.
596  Alignment = std::max(Alignment, FieldAlign);
597}
598
599static void CollectLocalObjCIvars(ASTContext *Ctx,
600                                  const ObjCInterfaceDecl *OI,
601                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
602  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
603       E = OI->ivar_end(); I != E; ++I) {
604    ObjCIvarDecl *IVDecl = *I;
605    if (!IVDecl->isInvalidDecl())
606      Fields.push_back(cast<FieldDecl>(IVDecl));
607  }
608}
609
610void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
611                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
612  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
613    CollectObjCIvars(SuperClass, Fields);
614  CollectLocalObjCIvars(this, OI, Fields);
615}
616
617/// ShallowCollectObjCIvars -
618/// Collect all ivars, including those synthesized, in the current class.
619///
620void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
621                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars,
622                                 bool CollectSynthesized) {
623  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
624         E = OI->ivar_end(); I != E; ++I) {
625     Ivars.push_back(*I);
626  }
627  if (CollectSynthesized)
628    CollectSynthesizedIvars(OI, Ivars);
629}
630
631void ASTContext::CollectProtocolSynthesizedIvars(const ObjCProtocolDecl *PD,
632                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
633  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
634       E = PD->prop_end(*this); I != E; ++I)
635    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
636      Ivars.push_back(Ivar);
637
638  // Also look into nested protocols.
639  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
640       E = PD->protocol_end(); P != E; ++P)
641    CollectProtocolSynthesizedIvars(*P, Ivars);
642}
643
644/// CollectSynthesizedIvars -
645/// This routine collect synthesized ivars for the designated class.
646///
647void ASTContext::CollectSynthesizedIvars(const ObjCInterfaceDecl *OI,
648                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
649  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
650       E = OI->prop_end(*this); I != E; ++I) {
651    if (ObjCIvarDecl *Ivar = (*I)->getPropertyIvarDecl())
652      Ivars.push_back(Ivar);
653  }
654  // Also look into interface's protocol list for properties declared
655  // in the protocol and whose ivars are synthesized.
656  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
657       PE = OI->protocol_end(); P != PE; ++P) {
658    ObjCProtocolDecl *PD = (*P);
659    CollectProtocolSynthesizedIvars(PD, Ivars);
660  }
661}
662
663unsigned ASTContext::CountProtocolSynthesizedIvars(const ObjCProtocolDecl *PD) {
664  unsigned count = 0;
665  for (ObjCContainerDecl::prop_iterator I = PD->prop_begin(*this),
666       E = PD->prop_end(*this); I != E; ++I)
667    if ((*I)->getPropertyIvarDecl())
668      ++count;
669
670  // Also look into nested protocols.
671  for (ObjCProtocolDecl::protocol_iterator P = PD->protocol_begin(),
672       E = PD->protocol_end(); P != E; ++P)
673    count += CountProtocolSynthesizedIvars(*P);
674  return count;
675}
676
677unsigned ASTContext::CountSynthesizedIvars(const ObjCInterfaceDecl *OI)
678{
679  unsigned count = 0;
680  for (ObjCInterfaceDecl::prop_iterator I = OI->prop_begin(*this),
681       E = OI->prop_end(*this); I != E; ++I) {
682    if ((*I)->getPropertyIvarDecl())
683      ++count;
684  }
685  // Also look into interface's protocol list for properties declared
686  // in the protocol and whose ivars are synthesized.
687  for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
688       PE = OI->protocol_end(); P != PE; ++P) {
689    ObjCProtocolDecl *PD = (*P);
690    count += CountProtocolSynthesizedIvars(PD);
691  }
692  return count;
693}
694
695/// getInterfaceLayoutImpl - Get or compute information about the
696/// layout of the given interface.
697///
698/// \param Impl - If given, also include the layout of the interface's
699/// implementation. This may differ by including synthesized ivars.
700const ASTRecordLayout &
701ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
702                          const ObjCImplementationDecl *Impl) {
703  assert(!D->isForwardDecl() && "Invalid interface decl!");
704
705  // Look up this layout, if already laid out, return what we have.
706  ObjCContainerDecl *Key =
707    Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
708  if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
709    return *Entry;
710
711  unsigned FieldCount = D->ivar_size();
712  // Add in synthesized ivar count if laying out an implementation.
713  if (Impl) {
714    unsigned SynthCount = CountSynthesizedIvars(D);
715    FieldCount += SynthCount;
716    // If there aren't any sythesized ivars then reuse the interface
717    // entry. Note we can't cache this because we simply free all
718    // entries later; however we shouldn't look up implementations
719    // frequently.
720    if (SynthCount == 0)
721      return getObjCLayout(D, 0);
722  }
723
724  ASTRecordLayout *NewEntry = NULL;
725  if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
726    const ASTRecordLayout &SL = getASTObjCInterfaceLayout(SD);
727    unsigned Alignment = SL.getAlignment();
728
729    // We start laying out ivars not at the end of the superclass
730    // structure, but at the next byte following the last field.
731    uint64_t Size = llvm::RoundUpToAlignment(SL.NextOffset, 8);
732
733    ObjCLayouts[Key] = NewEntry = new ASTRecordLayout(Size, Alignment);
734    NewEntry->InitializeLayout(FieldCount);
735  } else {
736    ObjCLayouts[Key] = NewEntry = new ASTRecordLayout();
737    NewEntry->InitializeLayout(FieldCount);
738  }
739
740  unsigned StructPacking = 0;
741  if (const PackedAttr *PA = D->getAttr<PackedAttr>(*this))
742    StructPacking = PA->getAlignment();
743
744  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>(*this))
745    NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
746                                    AA->getAlignment()));
747
748  // Layout each ivar sequentially.
749  unsigned i = 0;
750  llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
751  ShallowCollectObjCIvars(D, Ivars, Impl);
752  for (unsigned k = 0, e = Ivars.size(); k != e; ++k)
753       NewEntry->LayoutField(Ivars[k], i++, false, StructPacking, *this);
754
755  // Finally, round the size of the total struct up to the alignment of the
756  // struct itself.
757  NewEntry->FinalizeLayout();
758  return *NewEntry;
759}
760
761const ASTRecordLayout &
762ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
763  return getObjCLayout(D, 0);
764}
765
766const ASTRecordLayout &
767ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
768  return getObjCLayout(D->getClassInterface(), D);
769}
770
771/// getASTRecordLayout - Get or compute information about the layout of the
772/// specified record (struct/union/class), which indicates its size and field
773/// position information.
774const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) {
775  D = D->getDefinition(*this);
776  assert(D && "Cannot get layout of forward declarations!");
777
778  // Look up this layout, if already laid out, return what we have.
779  const ASTRecordLayout *&Entry = ASTRecordLayouts[D];
780  if (Entry) return *Entry;
781
782  // Allocate and assign into ASTRecordLayouts here.  The "Entry" reference can
783  // be invalidated (dangle) if the ASTRecordLayouts hashtable is inserted into.
784  ASTRecordLayout *NewEntry = new ASTRecordLayout();
785  Entry = NewEntry;
786
787  // FIXME: Avoid linear walk through the fields, if possible.
788  NewEntry->InitializeLayout(std::distance(D->field_begin(*this),
789                                           D->field_end(*this)));
790  bool IsUnion = D->isUnion();
791
792  unsigned StructPacking = 0;
793  if (const PackedAttr *PA = D->getAttr<PackedAttr>(*this))
794    StructPacking = PA->getAlignment();
795
796  if (const AlignedAttr *AA = D->getAttr<AlignedAttr>(*this))
797    NewEntry->SetAlignment(std::max(NewEntry->getAlignment(),
798                                    AA->getAlignment()));
799
800  // Layout each field, for now, just sequentially, respecting alignment.  In
801  // the future, this will need to be tweakable by targets.
802  unsigned FieldIdx = 0;
803  for (RecordDecl::field_iterator Field = D->field_begin(*this),
804                               FieldEnd = D->field_end(*this);
805       Field != FieldEnd; (void)++Field, ++FieldIdx)
806    NewEntry->LayoutField(*Field, FieldIdx, IsUnion, StructPacking, *this);
807
808  // Finally, round the size of the total struct up to the alignment of the
809  // struct itself.
810  NewEntry->FinalizeLayout(getLangOptions().CPlusPlus);
811  return *NewEntry;
812}
813
814//===----------------------------------------------------------------------===//
815//                   Type creation/memoization methods
816//===----------------------------------------------------------------------===//
817
818QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
819  QualType CanT = getCanonicalType(T);
820  if (CanT.getAddressSpace() == AddressSpace)
821    return T;
822
823  // If we are composing extended qualifiers together, merge together into one
824  // ExtQualType node.
825  unsigned CVRQuals = T.getCVRQualifiers();
826  QualType::GCAttrTypes GCAttr = QualType::GCNone;
827  Type *TypeNode = T.getTypePtr();
828
829  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
830    // If this type already has an address space specified, it cannot get
831    // another one.
832    assert(EQT->getAddressSpace() == 0 &&
833           "Type cannot be in multiple addr spaces!");
834    GCAttr = EQT->getObjCGCAttr();
835    TypeNode = EQT->getBaseType();
836  }
837
838  // Check if we've already instantiated this type.
839  llvm::FoldingSetNodeID ID;
840  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
841  void *InsertPos = 0;
842  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
843    return QualType(EXTQy, CVRQuals);
844
845  // If the base type isn't canonical, this won't be a canonical type either,
846  // so fill in the canonical type field.
847  QualType Canonical;
848  if (!TypeNode->isCanonical()) {
849    Canonical = getAddrSpaceQualType(CanT, AddressSpace);
850
851    // Update InsertPos, the previous call could have invalidated it.
852    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
853    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
854  }
855  ExtQualType *New =
856    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
857  ExtQualTypes.InsertNode(New, InsertPos);
858  Types.push_back(New);
859  return QualType(New, CVRQuals);
860}
861
862QualType ASTContext::getObjCGCQualType(QualType T,
863                                       QualType::GCAttrTypes GCAttr) {
864  QualType CanT = getCanonicalType(T);
865  if (CanT.getObjCGCAttr() == GCAttr)
866    return T;
867
868  if (T->isPointerType()) {
869    QualType Pointee = T->getAsPointerType()->getPointeeType();
870    if (Pointee->isPointerType()) {
871      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
872      return getPointerType(ResultType);
873    }
874  }
875  // If we are composing extended qualifiers together, merge together into one
876  // ExtQualType node.
877  unsigned CVRQuals = T.getCVRQualifiers();
878  Type *TypeNode = T.getTypePtr();
879  unsigned AddressSpace = 0;
880
881  if (ExtQualType *EQT = dyn_cast<ExtQualType>(TypeNode)) {
882    // If this type already has an address space specified, it cannot get
883    // another one.
884    assert(EQT->getObjCGCAttr() == QualType::GCNone &&
885           "Type cannot be in multiple addr spaces!");
886    AddressSpace = EQT->getAddressSpace();
887    TypeNode = EQT->getBaseType();
888  }
889
890  // Check if we've already instantiated an gc qual'd type of this type.
891  llvm::FoldingSetNodeID ID;
892  ExtQualType::Profile(ID, TypeNode, AddressSpace, GCAttr);
893  void *InsertPos = 0;
894  if (ExtQualType *EXTQy = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos))
895    return QualType(EXTQy, CVRQuals);
896
897  // If the base type isn't canonical, this won't be a canonical type either,
898  // so fill in the canonical type field.
899  // FIXME: Isn't this also not canonical if the base type is a array
900  // or pointer type?  I can't find any documentation for objc_gc, though...
901  QualType Canonical;
902  if (!T->isCanonical()) {
903    Canonical = getObjCGCQualType(CanT, GCAttr);
904
905    // Update InsertPos, the previous call could have invalidated it.
906    ExtQualType *NewIP = ExtQualTypes.FindNodeOrInsertPos(ID, InsertPos);
907    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
908  }
909  ExtQualType *New =
910    new (*this, 8) ExtQualType(TypeNode, Canonical, AddressSpace, GCAttr);
911  ExtQualTypes.InsertNode(New, InsertPos);
912  Types.push_back(New);
913  return QualType(New, CVRQuals);
914}
915
916/// getComplexType - Return the uniqued reference to the type for a complex
917/// number with the specified element type.
918QualType ASTContext::getComplexType(QualType T) {
919  // Unique pointers, to guarantee there is only one pointer of a particular
920  // structure.
921  llvm::FoldingSetNodeID ID;
922  ComplexType::Profile(ID, T);
923
924  void *InsertPos = 0;
925  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
926    return QualType(CT, 0);
927
928  // If the pointee type isn't canonical, this won't be a canonical type either,
929  // so fill in the canonical type field.
930  QualType Canonical;
931  if (!T->isCanonical()) {
932    Canonical = getComplexType(getCanonicalType(T));
933
934    // Get the new insert position for the node we care about.
935    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
936    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
937  }
938  ComplexType *New = new (*this,8) ComplexType(T, Canonical);
939  Types.push_back(New);
940  ComplexTypes.InsertNode(New, InsertPos);
941  return QualType(New, 0);
942}
943
944QualType ASTContext::getFixedWidthIntType(unsigned Width, bool Signed) {
945  llvm::DenseMap<unsigned, FixedWidthIntType*> &Map = Signed ?
946     SignedFixedWidthIntTypes : UnsignedFixedWidthIntTypes;
947  FixedWidthIntType *&Entry = Map[Width];
948  if (!Entry)
949    Entry = new FixedWidthIntType(Width, Signed);
950  return QualType(Entry, 0);
951}
952
953/// getPointerType - Return the uniqued reference to the type for a pointer to
954/// the specified type.
955QualType ASTContext::getPointerType(QualType T) {
956  // Unique pointers, to guarantee there is only one pointer of a particular
957  // structure.
958  llvm::FoldingSetNodeID ID;
959  PointerType::Profile(ID, T);
960
961  void *InsertPos = 0;
962  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
963    return QualType(PT, 0);
964
965  // If the pointee type isn't canonical, this won't be a canonical type either,
966  // so fill in the canonical type field.
967  QualType Canonical;
968  if (!T->isCanonical()) {
969    Canonical = getPointerType(getCanonicalType(T));
970
971    // Get the new insert position for the node we care about.
972    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
973    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
974  }
975  PointerType *New = new (*this,8) PointerType(T, Canonical);
976  Types.push_back(New);
977  PointerTypes.InsertNode(New, InsertPos);
978  return QualType(New, 0);
979}
980
981/// getBlockPointerType - Return the uniqued reference to the type for
982/// a pointer to the specified block.
983QualType ASTContext::getBlockPointerType(QualType T) {
984  assert(T->isFunctionType() && "block of function types only");
985  // Unique pointers, to guarantee there is only one block of a particular
986  // structure.
987  llvm::FoldingSetNodeID ID;
988  BlockPointerType::Profile(ID, T);
989
990  void *InsertPos = 0;
991  if (BlockPointerType *PT =
992        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
993    return QualType(PT, 0);
994
995  // If the block pointee type isn't canonical, this won't be a canonical
996  // type either so fill in the canonical type field.
997  QualType Canonical;
998  if (!T->isCanonical()) {
999    Canonical = getBlockPointerType(getCanonicalType(T));
1000
1001    // Get the new insert position for the node we care about.
1002    BlockPointerType *NewIP =
1003      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1004    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1005  }
1006  BlockPointerType *New = new (*this,8) BlockPointerType(T, Canonical);
1007  Types.push_back(New);
1008  BlockPointerTypes.InsertNode(New, InsertPos);
1009  return QualType(New, 0);
1010}
1011
1012/// getLValueReferenceType - Return the uniqued reference to the type for an
1013/// lvalue reference to the specified type.
1014QualType ASTContext::getLValueReferenceType(QualType T) {
1015  // Unique pointers, to guarantee there is only one pointer of a particular
1016  // structure.
1017  llvm::FoldingSetNodeID ID;
1018  ReferenceType::Profile(ID, T);
1019
1020  void *InsertPos = 0;
1021  if (LValueReferenceType *RT =
1022        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1023    return QualType(RT, 0);
1024
1025  // If the referencee type isn't canonical, this won't be a canonical type
1026  // either, so fill in the canonical type field.
1027  QualType Canonical;
1028  if (!T->isCanonical()) {
1029    Canonical = getLValueReferenceType(getCanonicalType(T));
1030
1031    // Get the new insert position for the node we care about.
1032    LValueReferenceType *NewIP =
1033      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1034    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1035  }
1036
1037  LValueReferenceType *New = new (*this,8) LValueReferenceType(T, Canonical);
1038  Types.push_back(New);
1039  LValueReferenceTypes.InsertNode(New, InsertPos);
1040  return QualType(New, 0);
1041}
1042
1043/// getRValueReferenceType - Return the uniqued reference to the type for an
1044/// rvalue reference to the specified type.
1045QualType ASTContext::getRValueReferenceType(QualType T) {
1046  // Unique pointers, to guarantee there is only one pointer of a particular
1047  // structure.
1048  llvm::FoldingSetNodeID ID;
1049  ReferenceType::Profile(ID, T);
1050
1051  void *InsertPos = 0;
1052  if (RValueReferenceType *RT =
1053        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1054    return QualType(RT, 0);
1055
1056  // If the referencee type isn't canonical, this won't be a canonical type
1057  // either, so fill in the canonical type field.
1058  QualType Canonical;
1059  if (!T->isCanonical()) {
1060    Canonical = getRValueReferenceType(getCanonicalType(T));
1061
1062    // Get the new insert position for the node we care about.
1063    RValueReferenceType *NewIP =
1064      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1065    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1066  }
1067
1068  RValueReferenceType *New = new (*this,8) RValueReferenceType(T, Canonical);
1069  Types.push_back(New);
1070  RValueReferenceTypes.InsertNode(New, InsertPos);
1071  return QualType(New, 0);
1072}
1073
1074/// getMemberPointerType - Return the uniqued reference to the type for a
1075/// member pointer to the specified type, in the specified class.
1076QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls)
1077{
1078  // Unique pointers, to guarantee there is only one pointer of a particular
1079  // structure.
1080  llvm::FoldingSetNodeID ID;
1081  MemberPointerType::Profile(ID, T, Cls);
1082
1083  void *InsertPos = 0;
1084  if (MemberPointerType *PT =
1085      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1086    return QualType(PT, 0);
1087
1088  // If the pointee or class type isn't canonical, this won't be a canonical
1089  // type either, so fill in the canonical type field.
1090  QualType Canonical;
1091  if (!T->isCanonical()) {
1092    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1093
1094    // Get the new insert position for the node we care about.
1095    MemberPointerType *NewIP =
1096      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1097    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1098  }
1099  MemberPointerType *New = new (*this,8) MemberPointerType(T, Cls, Canonical);
1100  Types.push_back(New);
1101  MemberPointerTypes.InsertNode(New, InsertPos);
1102  return QualType(New, 0);
1103}
1104
1105/// getConstantArrayType - Return the unique reference to the type for an
1106/// array of the specified element type.
1107QualType ASTContext::getConstantArrayType(QualType EltTy,
1108                                          const llvm::APInt &ArySizeIn,
1109                                          ArrayType::ArraySizeModifier ASM,
1110                                          unsigned EltTypeQuals) {
1111  assert((EltTy->isDependentType() || EltTy->isConstantSizeType()) &&
1112         "Constant array of VLAs is illegal!");
1113
1114  // Convert the array size into a canonical width matching the pointer size for
1115  // the target.
1116  llvm::APInt ArySize(ArySizeIn);
1117  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1118
1119  llvm::FoldingSetNodeID ID;
1120  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1121
1122  void *InsertPos = 0;
1123  if (ConstantArrayType *ATP =
1124      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1125    return QualType(ATP, 0);
1126
1127  // If the element type isn't canonical, this won't be a canonical type either,
1128  // so fill in the canonical type field.
1129  QualType Canonical;
1130  if (!EltTy->isCanonical()) {
1131    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1132                                     ASM, EltTypeQuals);
1133    // Get the new insert position for the node we care about.
1134    ConstantArrayType *NewIP =
1135      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1136    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1137  }
1138
1139  ConstantArrayType *New =
1140    new(*this,8)ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1141  ConstantArrayTypes.InsertNode(New, InsertPos);
1142  Types.push_back(New);
1143  return QualType(New, 0);
1144}
1145
1146/// getVariableArrayType - Returns a non-unique reference to the type for a
1147/// variable array of the specified element type.
1148QualType ASTContext::getVariableArrayType(QualType EltTy, Expr *NumElts,
1149                                          ArrayType::ArraySizeModifier ASM,
1150                                          unsigned EltTypeQuals) {
1151  // Since we don't unique expressions, it isn't possible to unique VLA's
1152  // that have an expression provided for their size.
1153
1154  VariableArrayType *New =
1155    new(*this,8)VariableArrayType(EltTy,QualType(), NumElts, ASM, EltTypeQuals);
1156
1157  VariableArrayTypes.push_back(New);
1158  Types.push_back(New);
1159  return QualType(New, 0);
1160}
1161
1162/// getDependentSizedArrayType - Returns a non-unique reference to
1163/// the type for a dependently-sized array of the specified element
1164/// type. FIXME: We will need these to be uniqued, or at least
1165/// comparable, at some point.
1166QualType ASTContext::getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1167                                                ArrayType::ArraySizeModifier ASM,
1168                                                unsigned EltTypeQuals) {
1169  assert((NumElts->isTypeDependent() || NumElts->isValueDependent()) &&
1170         "Size must be type- or value-dependent!");
1171
1172  // Since we don't unique expressions, it isn't possible to unique
1173  // dependently-sized array types.
1174
1175  DependentSizedArrayType *New =
1176      new (*this,8) DependentSizedArrayType(EltTy, QualType(), NumElts,
1177                                            ASM, EltTypeQuals);
1178
1179  DependentSizedArrayTypes.push_back(New);
1180  Types.push_back(New);
1181  return QualType(New, 0);
1182}
1183
1184QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1185                                            ArrayType::ArraySizeModifier ASM,
1186                                            unsigned EltTypeQuals) {
1187  llvm::FoldingSetNodeID ID;
1188  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1189
1190  void *InsertPos = 0;
1191  if (IncompleteArrayType *ATP =
1192       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1193    return QualType(ATP, 0);
1194
1195  // If the element type isn't canonical, this won't be a canonical type
1196  // either, so fill in the canonical type field.
1197  QualType Canonical;
1198
1199  if (!EltTy->isCanonical()) {
1200    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1201                                       ASM, EltTypeQuals);
1202
1203    // Get the new insert position for the node we care about.
1204    IncompleteArrayType *NewIP =
1205      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1206    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1207  }
1208
1209  IncompleteArrayType *New = new (*this,8) IncompleteArrayType(EltTy, Canonical,
1210                                                           ASM, EltTypeQuals);
1211
1212  IncompleteArrayTypes.InsertNode(New, InsertPos);
1213  Types.push_back(New);
1214  return QualType(New, 0);
1215}
1216
1217/// getVectorType - Return the unique reference to a vector type of
1218/// the specified element type and size. VectorType must be a built-in type.
1219QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts) {
1220  BuiltinType *baseType;
1221
1222  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1223  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1224
1225  // Check if we've already instantiated a vector of this type.
1226  llvm::FoldingSetNodeID ID;
1227  VectorType::Profile(ID, vecType, NumElts, Type::Vector);
1228  void *InsertPos = 0;
1229  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1230    return QualType(VTP, 0);
1231
1232  // If the element type isn't canonical, this won't be a canonical type either,
1233  // so fill in the canonical type field.
1234  QualType Canonical;
1235  if (!vecType->isCanonical()) {
1236    Canonical = getVectorType(getCanonicalType(vecType), NumElts);
1237
1238    // Get the new insert position for the node we care about.
1239    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1240    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1241  }
1242  VectorType *New = new (*this,8) VectorType(vecType, NumElts, Canonical);
1243  VectorTypes.InsertNode(New, InsertPos);
1244  Types.push_back(New);
1245  return QualType(New, 0);
1246}
1247
1248/// getExtVectorType - Return the unique reference to an extended vector type of
1249/// the specified element type and size. VectorType must be a built-in type.
1250QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1251  BuiltinType *baseType;
1252
1253  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1254  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1255
1256  // Check if we've already instantiated a vector of this type.
1257  llvm::FoldingSetNodeID ID;
1258  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector);
1259  void *InsertPos = 0;
1260  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1261    return QualType(VTP, 0);
1262
1263  // If the element type isn't canonical, this won't be a canonical type either,
1264  // so fill in the canonical type field.
1265  QualType Canonical;
1266  if (!vecType->isCanonical()) {
1267    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1268
1269    // Get the new insert position for the node we care about.
1270    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1271    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1272  }
1273  ExtVectorType *New = new (*this,8) ExtVectorType(vecType, NumElts, Canonical);
1274  VectorTypes.InsertNode(New, InsertPos);
1275  Types.push_back(New);
1276  return QualType(New, 0);
1277}
1278
1279QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1280                                                    Expr *SizeExpr,
1281                                                    SourceLocation AttrLoc) {
1282  DependentSizedExtVectorType *New =
1283      new (*this,8) DependentSizedExtVectorType(vecType, QualType(),
1284                                                SizeExpr, AttrLoc);
1285
1286  DependentSizedExtVectorTypes.push_back(New);
1287  Types.push_back(New);
1288  return QualType(New, 0);
1289}
1290
1291/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1292///
1293QualType ASTContext::getFunctionNoProtoType(QualType ResultTy) {
1294  // Unique functions, to guarantee there is only one function of a particular
1295  // structure.
1296  llvm::FoldingSetNodeID ID;
1297  FunctionNoProtoType::Profile(ID, ResultTy);
1298
1299  void *InsertPos = 0;
1300  if (FunctionNoProtoType *FT =
1301        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1302    return QualType(FT, 0);
1303
1304  QualType Canonical;
1305  if (!ResultTy->isCanonical()) {
1306    Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy));
1307
1308    // Get the new insert position for the node we care about.
1309    FunctionNoProtoType *NewIP =
1310      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1311    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1312  }
1313
1314  FunctionNoProtoType *New =new(*this,8)FunctionNoProtoType(ResultTy,Canonical);
1315  Types.push_back(New);
1316  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1317  return QualType(New, 0);
1318}
1319
1320/// getFunctionType - Return a normal function type with a typed argument
1321/// list.  isVariadic indicates whether the argument list includes '...'.
1322QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1323                                     unsigned NumArgs, bool isVariadic,
1324                                     unsigned TypeQuals, bool hasExceptionSpec,
1325                                     bool hasAnyExceptionSpec, unsigned NumExs,
1326                                     const QualType *ExArray) {
1327  // Unique functions, to guarantee there is only one function of a particular
1328  // structure.
1329  llvm::FoldingSetNodeID ID;
1330  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1331                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1332                             NumExs, ExArray);
1333
1334  void *InsertPos = 0;
1335  if (FunctionProtoType *FTP =
1336        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1337    return QualType(FTP, 0);
1338
1339  // Determine whether the type being created is already canonical or not.
1340  bool isCanonical = ResultTy->isCanonical();
1341  if (hasExceptionSpec)
1342    isCanonical = false;
1343  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1344    if (!ArgArray[i]->isCanonical())
1345      isCanonical = false;
1346
1347  // If this type isn't canonical, get the canonical version of it.
1348  // The exception spec is not part of the canonical type.
1349  QualType Canonical;
1350  if (!isCanonical) {
1351    llvm::SmallVector<QualType, 16> CanonicalArgs;
1352    CanonicalArgs.reserve(NumArgs);
1353    for (unsigned i = 0; i != NumArgs; ++i)
1354      CanonicalArgs.push_back(getCanonicalType(ArgArray[i]));
1355
1356    Canonical = getFunctionType(getCanonicalType(ResultTy),
1357                                CanonicalArgs.data(), NumArgs,
1358                                isVariadic, TypeQuals);
1359
1360    // Get the new insert position for the node we care about.
1361    FunctionProtoType *NewIP =
1362      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1363    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1364  }
1365
1366  // FunctionProtoType objects are allocated with extra bytes after them
1367  // for two variable size arrays (for parameter and exception types) at the
1368  // end of them.
1369  FunctionProtoType *FTP =
1370    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1371                                 NumArgs*sizeof(QualType) +
1372                                 NumExs*sizeof(QualType), 8);
1373  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1374                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1375                              ExArray, NumExs, Canonical);
1376  Types.push_back(FTP);
1377  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1378  return QualType(FTP, 0);
1379}
1380
1381/// getTypeDeclType - Return the unique reference to the type for the
1382/// specified type declaration.
1383QualType ASTContext::getTypeDeclType(TypeDecl *Decl, TypeDecl* PrevDecl) {
1384  assert(Decl && "Passed null for Decl param");
1385  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1386
1387  if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1388    return getTypedefType(Typedef);
1389  else if (isa<TemplateTypeParmDecl>(Decl)) {
1390    assert(false && "Template type parameter types are always available.");
1391  } else if (ObjCInterfaceDecl *ObjCInterface = dyn_cast<ObjCInterfaceDecl>(Decl))
1392    return getObjCInterfaceType(ObjCInterface);
1393
1394  if (RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1395    if (PrevDecl)
1396      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1397    else
1398      Decl->TypeForDecl = new (*this,8) RecordType(Record);
1399  }
1400  else if (EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1401    if (PrevDecl)
1402      Decl->TypeForDecl = PrevDecl->TypeForDecl;
1403    else
1404      Decl->TypeForDecl = new (*this,8) EnumType(Enum);
1405  }
1406  else
1407    assert(false && "TypeDecl without a type?");
1408
1409  if (!PrevDecl) Types.push_back(Decl->TypeForDecl);
1410  return QualType(Decl->TypeForDecl, 0);
1411}
1412
1413/// getTypedefType - Return the unique reference to the type for the
1414/// specified typename decl.
1415QualType ASTContext::getTypedefType(TypedefDecl *Decl) {
1416  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1417
1418  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1419  Decl->TypeForDecl = new(*this,8) TypedefType(Type::Typedef, Decl, Canonical);
1420  Types.push_back(Decl->TypeForDecl);
1421  return QualType(Decl->TypeForDecl, 0);
1422}
1423
1424/// getObjCInterfaceType - Return the unique reference to the type for the
1425/// specified ObjC interface decl.
1426QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
1427  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1428
1429  ObjCInterfaceDecl *OID = const_cast<ObjCInterfaceDecl*>(Decl);
1430  Decl->TypeForDecl = new(*this,8) ObjCInterfaceType(Type::ObjCInterface, OID);
1431  Types.push_back(Decl->TypeForDecl);
1432  return QualType(Decl->TypeForDecl, 0);
1433}
1434
1435/// \brief Retrieve the template type parameter type for a template
1436/// parameter or parameter pack with the given depth, index, and (optionally)
1437/// name.
1438QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1439                                             bool ParameterPack,
1440                                             IdentifierInfo *Name) {
1441  llvm::FoldingSetNodeID ID;
1442  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1443  void *InsertPos = 0;
1444  TemplateTypeParmType *TypeParm
1445    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1446
1447  if (TypeParm)
1448    return QualType(TypeParm, 0);
1449
1450  if (Name) {
1451    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1452    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack,
1453                                                   Name, Canon);
1454  } else
1455    TypeParm = new (*this, 8) TemplateTypeParmType(Depth, Index, ParameterPack);
1456
1457  Types.push_back(TypeParm);
1458  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1459
1460  return QualType(TypeParm, 0);
1461}
1462
1463QualType
1464ASTContext::getTemplateSpecializationType(TemplateName Template,
1465                                          const TemplateArgument *Args,
1466                                          unsigned NumArgs,
1467                                          QualType Canon) {
1468  if (!Canon.isNull())
1469    Canon = getCanonicalType(Canon);
1470
1471  llvm::FoldingSetNodeID ID;
1472  TemplateSpecializationType::Profile(ID, Template, Args, NumArgs);
1473
1474  void *InsertPos = 0;
1475  TemplateSpecializationType *Spec
1476    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1477
1478  if (Spec)
1479    return QualType(Spec, 0);
1480
1481  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1482                        sizeof(TemplateArgument) * NumArgs),
1483                       8);
1484  Spec = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, Canon);
1485  Types.push_back(Spec);
1486  TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1487
1488  return QualType(Spec, 0);
1489}
1490
1491QualType
1492ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS,
1493                                 QualType NamedType) {
1494  llvm::FoldingSetNodeID ID;
1495  QualifiedNameType::Profile(ID, NNS, NamedType);
1496
1497  void *InsertPos = 0;
1498  QualifiedNameType *T
1499    = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1500  if (T)
1501    return QualType(T, 0);
1502
1503  T = new (*this) QualifiedNameType(NNS, NamedType,
1504                                    getCanonicalType(NamedType));
1505  Types.push_back(T);
1506  QualifiedNameTypes.InsertNode(T, InsertPos);
1507  return QualType(T, 0);
1508}
1509
1510QualType ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1511                                     const IdentifierInfo *Name,
1512                                     QualType Canon) {
1513  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1514
1515  if (Canon.isNull()) {
1516    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1517    if (CanonNNS != NNS)
1518      Canon = getTypenameType(CanonNNS, Name);
1519  }
1520
1521  llvm::FoldingSetNodeID ID;
1522  TypenameType::Profile(ID, NNS, Name);
1523
1524  void *InsertPos = 0;
1525  TypenameType *T
1526    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1527  if (T)
1528    return QualType(T, 0);
1529
1530  T = new (*this) TypenameType(NNS, Name, Canon);
1531  Types.push_back(T);
1532  TypenameTypes.InsertNode(T, InsertPos);
1533  return QualType(T, 0);
1534}
1535
1536QualType
1537ASTContext::getTypenameType(NestedNameSpecifier *NNS,
1538                            const TemplateSpecializationType *TemplateId,
1539                            QualType Canon) {
1540  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1541
1542  if (Canon.isNull()) {
1543    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1544    QualType CanonType = getCanonicalType(QualType(TemplateId, 0));
1545    if (CanonNNS != NNS || CanonType != QualType(TemplateId, 0)) {
1546      const TemplateSpecializationType *CanonTemplateId
1547        = CanonType->getAsTemplateSpecializationType();
1548      assert(CanonTemplateId &&
1549             "Canonical type must also be a template specialization type");
1550      Canon = getTypenameType(CanonNNS, CanonTemplateId);
1551    }
1552  }
1553
1554  llvm::FoldingSetNodeID ID;
1555  TypenameType::Profile(ID, NNS, TemplateId);
1556
1557  void *InsertPos = 0;
1558  TypenameType *T
1559    = TypenameTypes.FindNodeOrInsertPos(ID, InsertPos);
1560  if (T)
1561    return QualType(T, 0);
1562
1563  T = new (*this) TypenameType(NNS, TemplateId, Canon);
1564  Types.push_back(T);
1565  TypenameTypes.InsertNode(T, InsertPos);
1566  return QualType(T, 0);
1567}
1568
1569/// CmpProtocolNames - Comparison predicate for sorting protocols
1570/// alphabetically.
1571static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
1572                            const ObjCProtocolDecl *RHS) {
1573  return LHS->getDeclName() < RHS->getDeclName();
1574}
1575
1576static void SortAndUniqueProtocols(ObjCProtocolDecl **&Protocols,
1577                                   unsigned &NumProtocols) {
1578  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
1579
1580  // Sort protocols, keyed by name.
1581  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
1582
1583  // Remove duplicates.
1584  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
1585  NumProtocols = ProtocolsEnd-Protocols;
1586}
1587
1588/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
1589/// the given interface decl and the conforming protocol list.
1590QualType ASTContext::getObjCObjectPointerType(ObjCInterfaceDecl *Decl,
1591                                              ObjCProtocolDecl **Protocols,
1592                                              unsigned NumProtocols) {
1593  // Sort the protocol list alphabetically to canonicalize it.
1594  if (NumProtocols)
1595    SortAndUniqueProtocols(Protocols, NumProtocols);
1596
1597  llvm::FoldingSetNodeID ID;
1598  ObjCObjectPointerType::Profile(ID, Decl, Protocols, NumProtocols);
1599
1600  void *InsertPos = 0;
1601  if (ObjCObjectPointerType *QT =
1602              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1603    return QualType(QT, 0);
1604
1605  // No Match;
1606  ObjCObjectPointerType *QType =
1607    new (*this,8) ObjCObjectPointerType(Decl, Protocols, NumProtocols);
1608
1609  Types.push_back(QType);
1610  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
1611  return QualType(QType, 0);
1612}
1613
1614/// getObjCQualifiedInterfaceType - Return a ObjCQualifiedInterfaceType type for
1615/// the given interface decl and the conforming protocol list.
1616QualType ASTContext::getObjCQualifiedInterfaceType(ObjCInterfaceDecl *Decl,
1617                       ObjCProtocolDecl **Protocols, unsigned NumProtocols) {
1618  // Sort the protocol list alphabetically to canonicalize it.
1619  SortAndUniqueProtocols(Protocols, NumProtocols);
1620
1621  llvm::FoldingSetNodeID ID;
1622  ObjCQualifiedInterfaceType::Profile(ID, Decl, Protocols, NumProtocols);
1623
1624  void *InsertPos = 0;
1625  if (ObjCQualifiedInterfaceType *QT =
1626      ObjCQualifiedInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos))
1627    return QualType(QT, 0);
1628
1629  // No Match;
1630  ObjCQualifiedInterfaceType *QType =
1631    new (*this,8) ObjCQualifiedInterfaceType(Decl, Protocols, NumProtocols);
1632
1633  Types.push_back(QType);
1634  ObjCQualifiedInterfaceTypes.InsertNode(QType, InsertPos);
1635  return QualType(QType, 0);
1636}
1637
1638/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
1639/// TypeOfExprType AST's (since expression's are never shared). For example,
1640/// multiple declarations that refer to "typeof(x)" all contain different
1641/// DeclRefExpr's. This doesn't effect the type checker, since it operates
1642/// on canonical type's (which are always unique).
1643QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
1644  QualType Canonical = getCanonicalType(tofExpr->getType());
1645  TypeOfExprType *toe = new (*this,8) TypeOfExprType(tofExpr, Canonical);
1646  Types.push_back(toe);
1647  return QualType(toe, 0);
1648}
1649
1650/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
1651/// TypeOfType AST's. The only motivation to unique these nodes would be
1652/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
1653/// an issue. This doesn't effect the type checker, since it operates
1654/// on canonical type's (which are always unique).
1655QualType ASTContext::getTypeOfType(QualType tofType) {
1656  QualType Canonical = getCanonicalType(tofType);
1657  TypeOfType *tot = new (*this,8) TypeOfType(tofType, Canonical);
1658  Types.push_back(tot);
1659  return QualType(tot, 0);
1660}
1661
1662/// getDecltypeForExpr - Given an expr, will return the decltype for that
1663/// expression, according to the rules in C++0x [dcl.type.simple]p4
1664static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
1665  if (e->isTypeDependent())
1666    return Context.DependentTy;
1667
1668  // If e is an id expression or a class member access, decltype(e) is defined
1669  // as the type of the entity named by e.
1670  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
1671    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
1672      return VD->getType();
1673  }
1674  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
1675    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
1676      return FD->getType();
1677  }
1678  // If e is a function call or an invocation of an overloaded operator,
1679  // (parentheses around e are ignored), decltype(e) is defined as the
1680  // return type of that function.
1681  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
1682    return CE->getCallReturnType();
1683
1684  QualType T = e->getType();
1685
1686  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
1687  // defined as T&, otherwise decltype(e) is defined as T.
1688  if (e->isLvalue(Context) == Expr::LV_Valid)
1689    T = Context.getLValueReferenceType(T);
1690
1691  return T;
1692}
1693
1694/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
1695/// DecltypeType AST's. The only motivation to unique these nodes would be
1696/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
1697/// an issue. This doesn't effect the type checker, since it operates
1698/// on canonical type's (which are always unique).
1699QualType ASTContext::getDecltypeType(Expr *e) {
1700  QualType T = getDecltypeForExpr(e, *this);
1701  DecltypeType *dt = new (*this, 8) DecltypeType(e, getCanonicalType(T));
1702  Types.push_back(dt);
1703  return QualType(dt, 0);
1704}
1705
1706/// getTagDeclType - Return the unique reference to the type for the
1707/// specified TagDecl (struct/union/class/enum) decl.
1708QualType ASTContext::getTagDeclType(TagDecl *Decl) {
1709  assert (Decl);
1710  return getTypeDeclType(Decl);
1711}
1712
1713/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
1714/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
1715/// needs to agree with the definition in <stddef.h>.
1716QualType ASTContext::getSizeType() const {
1717  return getFromTargetType(Target.getSizeType());
1718}
1719
1720/// getSignedWCharType - Return the type of "signed wchar_t".
1721/// Used when in C++, as a GCC extension.
1722QualType ASTContext::getSignedWCharType() const {
1723  // FIXME: derive from "Target" ?
1724  return WCharTy;
1725}
1726
1727/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
1728/// Used when in C++, as a GCC extension.
1729QualType ASTContext::getUnsignedWCharType() const {
1730  // FIXME: derive from "Target" ?
1731  return UnsignedIntTy;
1732}
1733
1734/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
1735/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1736QualType ASTContext::getPointerDiffType() const {
1737  return getFromTargetType(Target.getPtrDiffType(0));
1738}
1739
1740//===----------------------------------------------------------------------===//
1741//                              Type Operators
1742//===----------------------------------------------------------------------===//
1743
1744/// getCanonicalType - Return the canonical (structural) type corresponding to
1745/// the specified potentially non-canonical type.  The non-canonical version
1746/// of a type may have many "decorated" versions of types.  Decorators can
1747/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
1748/// to be free of any of these, allowing two canonical types to be compared
1749/// for exact equality with a simple pointer comparison.
1750QualType ASTContext::getCanonicalType(QualType T) {
1751  QualType CanType = T.getTypePtr()->getCanonicalTypeInternal();
1752
1753  // If the result has type qualifiers, make sure to canonicalize them as well.
1754  unsigned TypeQuals = T.getCVRQualifiers() | CanType.getCVRQualifiers();
1755  if (TypeQuals == 0) return CanType;
1756
1757  // If the type qualifiers are on an array type, get the canonical type of the
1758  // array with the qualifiers applied to the element type.
1759  ArrayType *AT = dyn_cast<ArrayType>(CanType);
1760  if (!AT)
1761    return CanType.getQualifiedType(TypeQuals);
1762
1763  // Get the canonical version of the element with the extra qualifiers on it.
1764  // This can recursively sink qualifiers through multiple levels of arrays.
1765  QualType NewEltTy=AT->getElementType().getWithAdditionalQualifiers(TypeQuals);
1766  NewEltTy = getCanonicalType(NewEltTy);
1767
1768  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
1769    return getConstantArrayType(NewEltTy, CAT->getSize(),CAT->getSizeModifier(),
1770                                CAT->getIndexTypeQualifier());
1771  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
1772    return getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
1773                                  IAT->getIndexTypeQualifier());
1774
1775  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
1776    return getDependentSizedArrayType(NewEltTy, DSAT->getSizeExpr(),
1777                                      DSAT->getSizeModifier(),
1778                                      DSAT->getIndexTypeQualifier());
1779
1780  VariableArrayType *VAT = cast<VariableArrayType>(AT);
1781  return getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1782                              VAT->getSizeModifier(),
1783                              VAT->getIndexTypeQualifier());
1784}
1785
1786Decl *ASTContext::getCanonicalDecl(Decl *D) {
1787  if (!D)
1788    return 0;
1789
1790  if (TagDecl *Tag = dyn_cast<TagDecl>(D)) {
1791    QualType T = getTagDeclType(Tag);
1792    return cast<TagDecl>(cast<TagType>(T.getTypePtr()->CanonicalType)
1793                         ->getDecl());
1794  }
1795
1796  if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(D)) {
1797    while (Template->getPreviousDeclaration())
1798      Template = Template->getPreviousDeclaration();
1799    return Template;
1800  }
1801
1802  if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1803    while (Function->getPreviousDeclaration())
1804      Function = Function->getPreviousDeclaration();
1805    return const_cast<FunctionDecl *>(Function);
1806  }
1807
1808  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D)) {
1809    while (FunTmpl->getPreviousDeclaration())
1810      FunTmpl = FunTmpl->getPreviousDeclaration();
1811    return FunTmpl;
1812  }
1813
1814  if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
1815    while (Var->getPreviousDeclaration())
1816      Var = Var->getPreviousDeclaration();
1817    return const_cast<VarDecl *>(Var);
1818  }
1819
1820  return D;
1821}
1822
1823TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
1824  // If this template name refers to a template, the canonical
1825  // template name merely stores the template itself.
1826  if (TemplateDecl *Template = Name.getAsTemplateDecl())
1827    return TemplateName(cast<TemplateDecl>(getCanonicalDecl(Template)));
1828
1829  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
1830  assert(DTN && "Non-dependent template names must refer to template decls.");
1831  return DTN->CanonicalTemplateName;
1832}
1833
1834NestedNameSpecifier *
1835ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
1836  if (!NNS)
1837    return 0;
1838
1839  switch (NNS->getKind()) {
1840  case NestedNameSpecifier::Identifier:
1841    // Canonicalize the prefix but keep the identifier the same.
1842    return NestedNameSpecifier::Create(*this,
1843                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
1844                                       NNS->getAsIdentifier());
1845
1846  case NestedNameSpecifier::Namespace:
1847    // A namespace is canonical; build a nested-name-specifier with
1848    // this namespace and no prefix.
1849    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
1850
1851  case NestedNameSpecifier::TypeSpec:
1852  case NestedNameSpecifier::TypeSpecWithTemplate: {
1853    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
1854    NestedNameSpecifier *Prefix = 0;
1855
1856    // FIXME: This isn't the right check!
1857    if (T->isDependentType())
1858      Prefix = getCanonicalNestedNameSpecifier(NNS->getPrefix());
1859
1860    return NestedNameSpecifier::Create(*this, Prefix,
1861                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
1862                                       T.getTypePtr());
1863  }
1864
1865  case NestedNameSpecifier::Global:
1866    // The global specifier is canonical and unique.
1867    return NNS;
1868  }
1869
1870  // Required to silence a GCC warning
1871  return 0;
1872}
1873
1874
1875const ArrayType *ASTContext::getAsArrayType(QualType T) {
1876  // Handle the non-qualified case efficiently.
1877  if (T.getCVRQualifiers() == 0) {
1878    // Handle the common positive case fast.
1879    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
1880      return AT;
1881  }
1882
1883  // Handle the common negative case fast, ignoring CVR qualifiers.
1884  QualType CType = T->getCanonicalTypeInternal();
1885
1886  // Make sure to look through type qualifiers (like ExtQuals) for the negative
1887  // test.
1888  if (!isa<ArrayType>(CType) &&
1889      !isa<ArrayType>(CType.getUnqualifiedType()))
1890    return 0;
1891
1892  // Apply any CVR qualifiers from the array type to the element type.  This
1893  // implements C99 6.7.3p8: "If the specification of an array type includes
1894  // any type qualifiers, the element type is so qualified, not the array type."
1895
1896  // If we get here, we either have type qualifiers on the type, or we have
1897  // sugar such as a typedef in the way.  If we have type qualifiers on the type
1898  // we must propagate them down into the elemeng type.
1899  unsigned CVRQuals = T.getCVRQualifiers();
1900  unsigned AddrSpace = 0;
1901  Type *Ty = T.getTypePtr();
1902
1903  // Rip through ExtQualType's and typedefs to get to a concrete type.
1904  while (1) {
1905    if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty)) {
1906      AddrSpace = EXTQT->getAddressSpace();
1907      Ty = EXTQT->getBaseType();
1908    } else {
1909      T = Ty->getDesugaredType();
1910      if (T.getTypePtr() == Ty && T.getCVRQualifiers() == 0)
1911        break;
1912      CVRQuals |= T.getCVRQualifiers();
1913      Ty = T.getTypePtr();
1914    }
1915  }
1916
1917  // If we have a simple case, just return now.
1918  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
1919  if (ATy == 0 || (AddrSpace == 0 && CVRQuals == 0))
1920    return ATy;
1921
1922  // Otherwise, we have an array and we have qualifiers on it.  Push the
1923  // qualifiers into the array element type and return a new array type.
1924  // Get the canonical version of the element with the extra qualifiers on it.
1925  // This can recursively sink qualifiers through multiple levels of arrays.
1926  QualType NewEltTy = ATy->getElementType();
1927  if (AddrSpace)
1928    NewEltTy = getAddrSpaceQualType(NewEltTy, AddrSpace);
1929  NewEltTy = NewEltTy.getWithAdditionalQualifiers(CVRQuals);
1930
1931  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
1932    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
1933                                                CAT->getSizeModifier(),
1934                                                CAT->getIndexTypeQualifier()));
1935  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
1936    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
1937                                                  IAT->getSizeModifier(),
1938                                                 IAT->getIndexTypeQualifier()));
1939
1940  if (const DependentSizedArrayType *DSAT
1941        = dyn_cast<DependentSizedArrayType>(ATy))
1942    return cast<ArrayType>(
1943                     getDependentSizedArrayType(NewEltTy,
1944                                                DSAT->getSizeExpr(),
1945                                                DSAT->getSizeModifier(),
1946                                                DSAT->getIndexTypeQualifier()));
1947
1948  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
1949  return cast<ArrayType>(getVariableArrayType(NewEltTy, VAT->getSizeExpr(),
1950                                              VAT->getSizeModifier(),
1951                                              VAT->getIndexTypeQualifier()));
1952}
1953
1954
1955/// getArrayDecayedType - Return the properly qualified result of decaying the
1956/// specified array type to a pointer.  This operation is non-trivial when
1957/// handling typedefs etc.  The canonical type of "T" must be an array type,
1958/// this returns a pointer to a properly qualified element of the array.
1959///
1960/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
1961QualType ASTContext::getArrayDecayedType(QualType Ty) {
1962  // Get the element type with 'getAsArrayType' so that we don't lose any
1963  // typedefs in the element type of the array.  This also handles propagation
1964  // of type qualifiers from the array type into the element type if present
1965  // (C99 6.7.3p8).
1966  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
1967  assert(PrettyArrayType && "Not an array type!");
1968
1969  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
1970
1971  // int x[restrict 4] ->  int *restrict
1972  return PtrTy.getQualifiedType(PrettyArrayType->getIndexTypeQualifier());
1973}
1974
1975QualType ASTContext::getBaseElementType(const VariableArrayType *VAT) {
1976  QualType ElemTy = VAT->getElementType();
1977
1978  if (const VariableArrayType *VAT = getAsVariableArrayType(ElemTy))
1979    return getBaseElementType(VAT);
1980
1981  return ElemTy;
1982}
1983
1984/// getFloatingRank - Return a relative rank for floating point types.
1985/// This routine will assert if passed a built-in type that isn't a float.
1986static FloatingRank getFloatingRank(QualType T) {
1987  if (const ComplexType *CT = T->getAsComplexType())
1988    return getFloatingRank(CT->getElementType());
1989
1990  assert(T->getAsBuiltinType() && "getFloatingRank(): not a floating type");
1991  switch (T->getAsBuiltinType()->getKind()) {
1992  default: assert(0 && "getFloatingRank(): not a floating type");
1993  case BuiltinType::Float:      return FloatRank;
1994  case BuiltinType::Double:     return DoubleRank;
1995  case BuiltinType::LongDouble: return LongDoubleRank;
1996  }
1997}
1998
1999/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2000/// point or a complex type (based on typeDomain/typeSize).
2001/// 'typeDomain' is a real floating point or complex type.
2002/// 'typeSize' is a real floating point or complex type.
2003QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2004                                                       QualType Domain) const {
2005  FloatingRank EltRank = getFloatingRank(Size);
2006  if (Domain->isComplexType()) {
2007    switch (EltRank) {
2008    default: assert(0 && "getFloatingRank(): illegal value for rank");
2009    case FloatRank:      return FloatComplexTy;
2010    case DoubleRank:     return DoubleComplexTy;
2011    case LongDoubleRank: return LongDoubleComplexTy;
2012    }
2013  }
2014
2015  assert(Domain->isRealFloatingType() && "Unknown domain!");
2016  switch (EltRank) {
2017  default: assert(0 && "getFloatingRank(): illegal value for rank");
2018  case FloatRank:      return FloatTy;
2019  case DoubleRank:     return DoubleTy;
2020  case LongDoubleRank: return LongDoubleTy;
2021  }
2022}
2023
2024/// getFloatingTypeOrder - Compare the rank of the two specified floating
2025/// point types, ignoring the domain of the type (i.e. 'double' ==
2026/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2027/// LHS < RHS, return -1.
2028int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2029  FloatingRank LHSR = getFloatingRank(LHS);
2030  FloatingRank RHSR = getFloatingRank(RHS);
2031
2032  if (LHSR == RHSR)
2033    return 0;
2034  if (LHSR > RHSR)
2035    return 1;
2036  return -1;
2037}
2038
2039/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2040/// routine will assert if passed a built-in type that isn't an integer or enum,
2041/// or if it is not canonicalized.
2042unsigned ASTContext::getIntegerRank(Type *T) {
2043  assert(T->isCanonical() && "T should be canonicalized");
2044  if (EnumType* ET = dyn_cast<EnumType>(T))
2045    T = ET->getDecl()->getIntegerType().getTypePtr();
2046
2047  // There are two things which impact the integer rank: the width, and
2048  // the ordering of builtins.  The builtin ordering is encoded in the
2049  // bottom three bits; the width is encoded in the bits above that.
2050  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T))
2051    return FWIT->getWidth() << 3;
2052
2053  switch (cast<BuiltinType>(T)->getKind()) {
2054  default: assert(0 && "getIntegerRank(): not a built-in integer");
2055  case BuiltinType::Bool:
2056    return 1 + (getIntWidth(BoolTy) << 3);
2057  case BuiltinType::Char_S:
2058  case BuiltinType::Char_U:
2059  case BuiltinType::SChar:
2060  case BuiltinType::UChar:
2061    return 2 + (getIntWidth(CharTy) << 3);
2062  case BuiltinType::Short:
2063  case BuiltinType::UShort:
2064    return 3 + (getIntWidth(ShortTy) << 3);
2065  case BuiltinType::Int:
2066  case BuiltinType::UInt:
2067    return 4 + (getIntWidth(IntTy) << 3);
2068  case BuiltinType::Long:
2069  case BuiltinType::ULong:
2070    return 5 + (getIntWidth(LongTy) << 3);
2071  case BuiltinType::LongLong:
2072  case BuiltinType::ULongLong:
2073    return 6 + (getIntWidth(LongLongTy) << 3);
2074  case BuiltinType::Int128:
2075  case BuiltinType::UInt128:
2076    return 7 + (getIntWidth(Int128Ty) << 3);
2077  }
2078}
2079
2080/// getIntegerTypeOrder - Returns the highest ranked integer type:
2081/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2082/// LHS < RHS, return -1.
2083int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2084  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2085  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2086  if (LHSC == RHSC) return 0;
2087
2088  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2089  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2090
2091  unsigned LHSRank = getIntegerRank(LHSC);
2092  unsigned RHSRank = getIntegerRank(RHSC);
2093
2094  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2095    if (LHSRank == RHSRank) return 0;
2096    return LHSRank > RHSRank ? 1 : -1;
2097  }
2098
2099  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2100  if (LHSUnsigned) {
2101    // If the unsigned [LHS] type is larger, return it.
2102    if (LHSRank >= RHSRank)
2103      return 1;
2104
2105    // If the signed type can represent all values of the unsigned type, it
2106    // wins.  Because we are dealing with 2's complement and types that are
2107    // powers of two larger than each other, this is always safe.
2108    return -1;
2109  }
2110
2111  // If the unsigned [RHS] type is larger, return it.
2112  if (RHSRank >= LHSRank)
2113    return -1;
2114
2115  // If the signed type can represent all values of the unsigned type, it
2116  // wins.  Because we are dealing with 2's complement and types that are
2117  // powers of two larger than each other, this is always safe.
2118  return 1;
2119}
2120
2121// getCFConstantStringType - Return the type used for constant CFStrings.
2122QualType ASTContext::getCFConstantStringType() {
2123  if (!CFConstantStringTypeDecl) {
2124    CFConstantStringTypeDecl =
2125      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2126                         &Idents.get("NSConstantString"));
2127    QualType FieldTypes[4];
2128
2129    // const int *isa;
2130    FieldTypes[0] = getPointerType(IntTy.getQualifiedType(QualType::Const));
2131    // int flags;
2132    FieldTypes[1] = IntTy;
2133    // const char *str;
2134    FieldTypes[2] = getPointerType(CharTy.getQualifiedType(QualType::Const));
2135    // long length;
2136    FieldTypes[3] = LongTy;
2137
2138    // Create fields
2139    for (unsigned i = 0; i < 4; ++i) {
2140      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2141                                           SourceLocation(), 0,
2142                                           FieldTypes[i], /*BitWidth=*/0,
2143                                           /*Mutable=*/false);
2144      CFConstantStringTypeDecl->addDecl(*this, Field);
2145    }
2146
2147    CFConstantStringTypeDecl->completeDefinition(*this);
2148  }
2149
2150  return getTagDeclType(CFConstantStringTypeDecl);
2151}
2152
2153void ASTContext::setCFConstantStringType(QualType T) {
2154  const RecordType *Rec = T->getAsRecordType();
2155  assert(Rec && "Invalid CFConstantStringType");
2156  CFConstantStringTypeDecl = Rec->getDecl();
2157}
2158
2159QualType ASTContext::getObjCFastEnumerationStateType()
2160{
2161  if (!ObjCFastEnumerationStateTypeDecl) {
2162    ObjCFastEnumerationStateTypeDecl =
2163      RecordDecl::Create(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2164                         &Idents.get("__objcFastEnumerationState"));
2165
2166    QualType FieldTypes[] = {
2167      UnsignedLongTy,
2168      getPointerType(ObjCIdType),
2169      getPointerType(UnsignedLongTy),
2170      getConstantArrayType(UnsignedLongTy,
2171                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2172    };
2173
2174    for (size_t i = 0; i < 4; ++i) {
2175      FieldDecl *Field = FieldDecl::Create(*this,
2176                                           ObjCFastEnumerationStateTypeDecl,
2177                                           SourceLocation(), 0,
2178                                           FieldTypes[i], /*BitWidth=*/0,
2179                                           /*Mutable=*/false);
2180      ObjCFastEnumerationStateTypeDecl->addDecl(*this, Field);
2181    }
2182
2183    ObjCFastEnumerationStateTypeDecl->completeDefinition(*this);
2184  }
2185
2186  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2187}
2188
2189void ASTContext::setObjCFastEnumerationStateType(QualType T) {
2190  const RecordType *Rec = T->getAsRecordType();
2191  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
2192  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
2193}
2194
2195// This returns true if a type has been typedefed to BOOL:
2196// typedef <type> BOOL;
2197static bool isTypeTypedefedAsBOOL(QualType T) {
2198  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
2199    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
2200      return II->isStr("BOOL");
2201
2202  return false;
2203}
2204
2205/// getObjCEncodingTypeSize returns size of type for objective-c encoding
2206/// purpose.
2207int ASTContext::getObjCEncodingTypeSize(QualType type) {
2208  uint64_t sz = getTypeSize(type);
2209
2210  // Make all integer and enum types at least as large as an int
2211  if (sz > 0 && type->isIntegralType())
2212    sz = std::max(sz, getTypeSize(IntTy));
2213  // Treat arrays as pointers, since that's how they're passed in.
2214  else if (type->isArrayType())
2215    sz = getTypeSize(VoidPtrTy);
2216  return sz / getTypeSize(CharTy);
2217}
2218
2219/// getObjCEncodingForMethodDecl - Return the encoded type for this method
2220/// declaration.
2221void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
2222                                              std::string& S) {
2223  // FIXME: This is not very efficient.
2224  // Encode type qualifer, 'in', 'inout', etc. for the return type.
2225  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
2226  // Encode result type.
2227  getObjCEncodingForType(Decl->getResultType(), S);
2228  // Compute size of all parameters.
2229  // Start with computing size of a pointer in number of bytes.
2230  // FIXME: There might(should) be a better way of doing this computation!
2231  SourceLocation Loc;
2232  int PtrSize = getTypeSize(VoidPtrTy) / getTypeSize(CharTy);
2233  // The first two arguments (self and _cmd) are pointers; account for
2234  // their size.
2235  int ParmOffset = 2 * PtrSize;
2236  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2237       E = Decl->param_end(); PI != E; ++PI) {
2238    QualType PType = (*PI)->getType();
2239    int sz = getObjCEncodingTypeSize(PType);
2240    assert (sz > 0 && "getObjCEncodingForMethodDecl - Incomplete param type");
2241    ParmOffset += sz;
2242  }
2243  S += llvm::utostr(ParmOffset);
2244  S += "@0:";
2245  S += llvm::utostr(PtrSize);
2246
2247  // Argument types.
2248  ParmOffset = 2 * PtrSize;
2249  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
2250       E = Decl->param_end(); PI != E; ++PI) {
2251    ParmVarDecl *PVDecl = *PI;
2252    QualType PType = PVDecl->getOriginalType();
2253    if (const ArrayType *AT =
2254          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
2255      // Use array's original type only if it has known number of
2256      // elements.
2257      if (!isa<ConstantArrayType>(AT))
2258        PType = PVDecl->getType();
2259    } else if (PType->isFunctionType())
2260      PType = PVDecl->getType();
2261    // Process argument qualifiers for user supplied arguments; such as,
2262    // 'in', 'inout', etc.
2263    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
2264    getObjCEncodingForType(PType, S);
2265    S += llvm::utostr(ParmOffset);
2266    ParmOffset += getObjCEncodingTypeSize(PType);
2267  }
2268}
2269
2270/// getObjCEncodingForPropertyDecl - Return the encoded type for this
2271/// property declaration. If non-NULL, Container must be either an
2272/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
2273/// NULL when getting encodings for protocol properties.
2274/// Property attributes are stored as a comma-delimited C string. The simple
2275/// attributes readonly and bycopy are encoded as single characters. The
2276/// parametrized attributes, getter=name, setter=name, and ivar=name, are
2277/// encoded as single characters, followed by an identifier. Property types
2278/// are also encoded as a parametrized attribute. The characters used to encode
2279/// these attributes are defined by the following enumeration:
2280/// @code
2281/// enum PropertyAttributes {
2282/// kPropertyReadOnly = 'R',   // property is read-only.
2283/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
2284/// kPropertyByref = '&',  // property is a reference to the value last assigned
2285/// kPropertyDynamic = 'D',    // property is dynamic
2286/// kPropertyGetter = 'G',     // followed by getter selector name
2287/// kPropertySetter = 'S',     // followed by setter selector name
2288/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
2289/// kPropertyType = 't'              // followed by old-style type encoding.
2290/// kPropertyWeak = 'W'              // 'weak' property
2291/// kPropertyStrong = 'P'            // property GC'able
2292/// kPropertyNonAtomic = 'N'         // property non-atomic
2293/// };
2294/// @endcode
2295void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
2296                                                const Decl *Container,
2297                                                std::string& S) {
2298  // Collect information from the property implementation decl(s).
2299  bool Dynamic = false;
2300  ObjCPropertyImplDecl *SynthesizePID = 0;
2301
2302  // FIXME: Duplicated code due to poor abstraction.
2303  if (Container) {
2304    if (const ObjCCategoryImplDecl *CID =
2305        dyn_cast<ObjCCategoryImplDecl>(Container)) {
2306      for (ObjCCategoryImplDecl::propimpl_iterator
2307             i = CID->propimpl_begin(*this), e = CID->propimpl_end(*this);
2308           i != e; ++i) {
2309        ObjCPropertyImplDecl *PID = *i;
2310        if (PID->getPropertyDecl() == PD) {
2311          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2312            Dynamic = true;
2313          } else {
2314            SynthesizePID = PID;
2315          }
2316        }
2317      }
2318    } else {
2319      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
2320      for (ObjCCategoryImplDecl::propimpl_iterator
2321             i = OID->propimpl_begin(*this), e = OID->propimpl_end(*this);
2322           i != e; ++i) {
2323        ObjCPropertyImplDecl *PID = *i;
2324        if (PID->getPropertyDecl() == PD) {
2325          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
2326            Dynamic = true;
2327          } else {
2328            SynthesizePID = PID;
2329          }
2330        }
2331      }
2332    }
2333  }
2334
2335  // FIXME: This is not very efficient.
2336  S = "T";
2337
2338  // Encode result type.
2339  // GCC has some special rules regarding encoding of properties which
2340  // closely resembles encoding of ivars.
2341  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
2342                             true /* outermost type */,
2343                             true /* encoding for property */);
2344
2345  if (PD->isReadOnly()) {
2346    S += ",R";
2347  } else {
2348    switch (PD->getSetterKind()) {
2349    case ObjCPropertyDecl::Assign: break;
2350    case ObjCPropertyDecl::Copy:   S += ",C"; break;
2351    case ObjCPropertyDecl::Retain: S += ",&"; break;
2352    }
2353  }
2354
2355  // It really isn't clear at all what this means, since properties
2356  // are "dynamic by default".
2357  if (Dynamic)
2358    S += ",D";
2359
2360  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
2361    S += ",N";
2362
2363  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
2364    S += ",G";
2365    S += PD->getGetterName().getAsString();
2366  }
2367
2368  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
2369    S += ",S";
2370    S += PD->getSetterName().getAsString();
2371  }
2372
2373  if (SynthesizePID) {
2374    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
2375    S += ",V";
2376    S += OID->getNameAsString();
2377  }
2378
2379  // FIXME: OBJCGC: weak & strong
2380}
2381
2382/// getLegacyIntegralTypeEncoding -
2383/// Another legacy compatibility encoding: 32-bit longs are encoded as
2384/// 'l' or 'L' , but not always.  For typedefs, we need to use
2385/// 'i' or 'I' instead if encoding a struct field, or a pointer!
2386///
2387void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
2388  if (dyn_cast<TypedefType>(PointeeTy.getTypePtr())) {
2389    if (const BuiltinType *BT = PointeeTy->getAsBuiltinType()) {
2390      if (BT->getKind() == BuiltinType::ULong &&
2391          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2392        PointeeTy = UnsignedIntTy;
2393      else
2394        if (BT->getKind() == BuiltinType::Long &&
2395            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
2396          PointeeTy = IntTy;
2397    }
2398  }
2399}
2400
2401void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
2402                                        const FieldDecl *Field) {
2403  // We follow the behavior of gcc, expanding structures which are
2404  // directly pointed to, and expanding embedded structures. Note that
2405  // these rules are sufficient to prevent recursive encoding of the
2406  // same type.
2407  getObjCEncodingForTypeImpl(T, S, true, true, Field,
2408                             true /* outermost type */);
2409}
2410
2411static void EncodeBitField(const ASTContext *Context, std::string& S,
2412                           const FieldDecl *FD) {
2413  const Expr *E = FD->getBitWidth();
2414  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
2415  ASTContext *Ctx = const_cast<ASTContext*>(Context);
2416  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
2417  S += 'b';
2418  S += llvm::utostr(N);
2419}
2420
2421void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
2422                                            bool ExpandPointedToStructures,
2423                                            bool ExpandStructures,
2424                                            const FieldDecl *FD,
2425                                            bool OutermostType,
2426                                            bool EncodingProperty) {
2427  if (const BuiltinType *BT = T->getAsBuiltinType()) {
2428    if (FD && FD->isBitField()) {
2429      EncodeBitField(this, S, FD);
2430    }
2431    else {
2432      char encoding;
2433      switch (BT->getKind()) {
2434      default: assert(0 && "Unhandled builtin type kind");
2435      case BuiltinType::Void:       encoding = 'v'; break;
2436      case BuiltinType::Bool:       encoding = 'B'; break;
2437      case BuiltinType::Char_U:
2438      case BuiltinType::UChar:      encoding = 'C'; break;
2439      case BuiltinType::UShort:     encoding = 'S'; break;
2440      case BuiltinType::UInt:       encoding = 'I'; break;
2441      case BuiltinType::ULong:
2442          encoding =
2443            (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
2444          break;
2445      case BuiltinType::UInt128:    encoding = 'T'; break;
2446      case BuiltinType::ULongLong:  encoding = 'Q'; break;
2447      case BuiltinType::Char_S:
2448      case BuiltinType::SChar:      encoding = 'c'; break;
2449      case BuiltinType::Short:      encoding = 's'; break;
2450      case BuiltinType::Int:        encoding = 'i'; break;
2451      case BuiltinType::Long:
2452        encoding =
2453          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
2454        break;
2455      case BuiltinType::LongLong:   encoding = 'q'; break;
2456      case BuiltinType::Int128:     encoding = 't'; break;
2457      case BuiltinType::Float:      encoding = 'f'; break;
2458      case BuiltinType::Double:     encoding = 'd'; break;
2459      case BuiltinType::LongDouble: encoding = 'd'; break;
2460      }
2461
2462      S += encoding;
2463    }
2464  } else if (const ComplexType *CT = T->getAsComplexType()) {
2465    S += 'j';
2466    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
2467                               false);
2468  } else if (T->isObjCQualifiedIdType()) {
2469    getObjCEncodingForTypeImpl(getObjCIdType(), S,
2470                               ExpandPointedToStructures,
2471                               ExpandStructures, FD);
2472    if (FD || EncodingProperty) {
2473      // Note that we do extended encoding of protocol qualifer list
2474      // Only when doing ivar or property encoding.
2475      const ObjCObjectPointerType *QIDT = T->getAsObjCQualifiedIdType();
2476      S += '"';
2477      for (ObjCObjectPointerType::qual_iterator I = QIDT->qual_begin(),
2478           E = QIDT->qual_end(); I != E; ++I) {
2479        S += '<';
2480        S += (*I)->getNameAsString();
2481        S += '>';
2482      }
2483      S += '"';
2484    }
2485    return;
2486  }
2487  else if (const PointerType *PT = T->getAsPointerType()) {
2488    QualType PointeeTy = PT->getPointeeType();
2489    bool isReadOnly = false;
2490    // For historical/compatibility reasons, the read-only qualifier of the
2491    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
2492    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
2493    // Also, do not emit the 'r' for anything but the outermost type!
2494    if (dyn_cast<TypedefType>(T.getTypePtr())) {
2495      if (OutermostType && T.isConstQualified()) {
2496        isReadOnly = true;
2497        S += 'r';
2498      }
2499    }
2500    else if (OutermostType) {
2501      QualType P = PointeeTy;
2502      while (P->getAsPointerType())
2503        P = P->getAsPointerType()->getPointeeType();
2504      if (P.isConstQualified()) {
2505        isReadOnly = true;
2506        S += 'r';
2507      }
2508    }
2509    if (isReadOnly) {
2510      // Another legacy compatibility encoding. Some ObjC qualifier and type
2511      // combinations need to be rearranged.
2512      // Rewrite "in const" from "nr" to "rn"
2513      const char * s = S.c_str();
2514      int len = S.length();
2515      if (len >= 2 && s[len-2] == 'n' && s[len-1] == 'r') {
2516        std::string replace = "rn";
2517        S.replace(S.end()-2, S.end(), replace);
2518      }
2519    }
2520    if (isObjCIdStructType(PointeeTy)) {
2521      S += '@';
2522      return;
2523    }
2524    else if (PointeeTy->isObjCInterfaceType()) {
2525      if (!EncodingProperty &&
2526          isa<TypedefType>(PointeeTy.getTypePtr())) {
2527        // Another historical/compatibility reason.
2528        // We encode the underlying type which comes out as
2529        // {...};
2530        S += '^';
2531        getObjCEncodingForTypeImpl(PointeeTy, S,
2532                                   false, ExpandPointedToStructures,
2533                                   NULL);
2534        return;
2535      }
2536      S += '@';
2537      if (FD || EncodingProperty) {
2538        const ObjCInterfaceType *OIT =
2539                PointeeTy.getUnqualifiedType()->getAsObjCInterfaceType();
2540        ObjCInterfaceDecl *OI = OIT->getDecl();
2541        S += '"';
2542        S += OI->getNameAsCString();
2543        for (ObjCInterfaceType::qual_iterator I = OIT->qual_begin(),
2544             E = OIT->qual_end(); I != E; ++I) {
2545          S += '<';
2546          S += (*I)->getNameAsString();
2547          S += '>';
2548        }
2549        S += '"';
2550      }
2551      return;
2552    } else if (isObjCClassStructType(PointeeTy)) {
2553      S += '#';
2554      return;
2555    } else if (isObjCSelType(PointeeTy)) {
2556      S += ':';
2557      return;
2558    }
2559
2560    if (PointeeTy->isCharType()) {
2561      // char pointer types should be encoded as '*' unless it is a
2562      // type that has been typedef'd to 'BOOL'.
2563      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
2564        S += '*';
2565        return;
2566      }
2567    }
2568
2569    S += '^';
2570    getLegacyIntegralTypeEncoding(PointeeTy);
2571
2572    getObjCEncodingForTypeImpl(PointeeTy, S,
2573                               false, ExpandPointedToStructures,
2574                               NULL);
2575  } else if (const ArrayType *AT =
2576               // Ignore type qualifiers etc.
2577               dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
2578    if (isa<IncompleteArrayType>(AT)) {
2579      // Incomplete arrays are encoded as a pointer to the array element.
2580      S += '^';
2581
2582      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2583                                 false, ExpandStructures, FD);
2584    } else {
2585      S += '[';
2586
2587      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2588        S += llvm::utostr(CAT->getSize().getZExtValue());
2589      else {
2590        //Variable length arrays are encoded as a regular array with 0 elements.
2591        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
2592        S += '0';
2593      }
2594
2595      getObjCEncodingForTypeImpl(AT->getElementType(), S,
2596                                 false, ExpandStructures, FD);
2597      S += ']';
2598    }
2599  } else if (T->getAsFunctionType()) {
2600    S += '?';
2601  } else if (const RecordType *RTy = T->getAsRecordType()) {
2602    RecordDecl *RDecl = RTy->getDecl();
2603    S += RDecl->isUnion() ? '(' : '{';
2604    // Anonymous structures print as '?'
2605    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
2606      S += II->getName();
2607    } else {
2608      S += '?';
2609    }
2610    if (ExpandStructures) {
2611      S += '=';
2612      for (RecordDecl::field_iterator Field = RDecl->field_begin(*this),
2613                                   FieldEnd = RDecl->field_end(*this);
2614           Field != FieldEnd; ++Field) {
2615        if (FD) {
2616          S += '"';
2617          S += Field->getNameAsString();
2618          S += '"';
2619        }
2620
2621        // Special case bit-fields.
2622        if (Field->isBitField()) {
2623          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
2624                                     (*Field));
2625        } else {
2626          QualType qt = Field->getType();
2627          getLegacyIntegralTypeEncoding(qt);
2628          getObjCEncodingForTypeImpl(qt, S, false, true,
2629                                     FD);
2630        }
2631      }
2632    }
2633    S += RDecl->isUnion() ? ')' : '}';
2634  } else if (T->isEnumeralType()) {
2635    if (FD && FD->isBitField())
2636      EncodeBitField(this, S, FD);
2637    else
2638      S += 'i';
2639  } else if (T->isBlockPointerType()) {
2640    S += "@?"; // Unlike a pointer-to-function, which is "^?".
2641  } else if (T->isObjCInterfaceType()) {
2642    // @encode(class_name)
2643    ObjCInterfaceDecl *OI = T->getAsObjCInterfaceType()->getDecl();
2644    S += '{';
2645    const IdentifierInfo *II = OI->getIdentifier();
2646    S += II->getName();
2647    S += '=';
2648    llvm::SmallVector<FieldDecl*, 32> RecFields;
2649    CollectObjCIvars(OI, RecFields);
2650    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
2651      if (RecFields[i]->isBitField())
2652        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2653                                   RecFields[i]);
2654      else
2655        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
2656                                   FD);
2657    }
2658    S += '}';
2659  }
2660  else
2661    assert(0 && "@encode for type not implemented!");
2662}
2663
2664void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
2665                                                 std::string& S) const {
2666  if (QT & Decl::OBJC_TQ_In)
2667    S += 'n';
2668  if (QT & Decl::OBJC_TQ_Inout)
2669    S += 'N';
2670  if (QT & Decl::OBJC_TQ_Out)
2671    S += 'o';
2672  if (QT & Decl::OBJC_TQ_Bycopy)
2673    S += 'O';
2674  if (QT & Decl::OBJC_TQ_Byref)
2675    S += 'R';
2676  if (QT & Decl::OBJC_TQ_Oneway)
2677    S += 'V';
2678}
2679
2680void ASTContext::setBuiltinVaListType(QualType T)
2681{
2682  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
2683
2684  BuiltinVaListType = T;
2685}
2686
2687void ASTContext::setObjCIdType(QualType T)
2688{
2689  ObjCIdType = T;
2690
2691  const TypedefType *TT = T->getAsTypedefType();
2692  if (!TT)
2693    return;
2694
2695  TypedefDecl *TD = TT->getDecl();
2696
2697  // typedef struct objc_object *id;
2698  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2699  // User error - caller will issue diagnostics.
2700  if (!ptr)
2701    return;
2702  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2703  // User error - caller will issue diagnostics.
2704  if (!rec)
2705    return;
2706  IdStructType = rec;
2707}
2708
2709void ASTContext::setObjCSelType(QualType T)
2710{
2711  ObjCSelType = T;
2712
2713  const TypedefType *TT = T->getAsTypedefType();
2714  if (!TT)
2715    return;
2716  TypedefDecl *TD = TT->getDecl();
2717
2718  // typedef struct objc_selector *SEL;
2719  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2720  if (!ptr)
2721    return;
2722  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2723  if (!rec)
2724    return;
2725  SelStructType = rec;
2726}
2727
2728void ASTContext::setObjCProtoType(QualType QT)
2729{
2730  ObjCProtoType = QT;
2731}
2732
2733void ASTContext::setObjCClassType(QualType T)
2734{
2735  ObjCClassType = T;
2736
2737  const TypedefType *TT = T->getAsTypedefType();
2738  if (!TT)
2739    return;
2740  TypedefDecl *TD = TT->getDecl();
2741
2742  // typedef struct objc_class *Class;
2743  const PointerType *ptr = TD->getUnderlyingType()->getAsPointerType();
2744  assert(ptr && "'Class' incorrectly typed");
2745  const RecordType *rec = ptr->getPointeeType()->getAsStructureType();
2746  assert(rec && "'Class' incorrectly typed");
2747  ClassStructType = rec;
2748}
2749
2750void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
2751  assert(ObjCConstantStringType.isNull() &&
2752         "'NSConstantString' type already set!");
2753
2754  ObjCConstantStringType = getObjCInterfaceType(Decl);
2755}
2756
2757/// \brief Retrieve the template name that represents a qualified
2758/// template name such as \c std::vector.
2759TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
2760                                                  bool TemplateKeyword,
2761                                                  TemplateDecl *Template) {
2762  llvm::FoldingSetNodeID ID;
2763  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
2764
2765  void *InsertPos = 0;
2766  QualifiedTemplateName *QTN =
2767    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2768  if (!QTN) {
2769    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
2770    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
2771  }
2772
2773  return TemplateName(QTN);
2774}
2775
2776/// \brief Retrieve the template name that represents a dependent
2777/// template name such as \c MetaFun::template apply.
2778TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
2779                                                  const IdentifierInfo *Name) {
2780  assert(NNS->isDependent() && "Nested name specifier must be dependent");
2781
2782  llvm::FoldingSetNodeID ID;
2783  DependentTemplateName::Profile(ID, NNS, Name);
2784
2785  void *InsertPos = 0;
2786  DependentTemplateName *QTN =
2787    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
2788
2789  if (QTN)
2790    return TemplateName(QTN);
2791
2792  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2793  if (CanonNNS == NNS) {
2794    QTN = new (*this,4) DependentTemplateName(NNS, Name);
2795  } else {
2796    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
2797    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
2798  }
2799
2800  DependentTemplateNames.InsertNode(QTN, InsertPos);
2801  return TemplateName(QTN);
2802}
2803
2804/// getFromTargetType - Given one of the integer types provided by
2805/// TargetInfo, produce the corresponding type. The unsigned @p Type
2806/// is actually a value of type @c TargetInfo::IntType.
2807QualType ASTContext::getFromTargetType(unsigned Type) const {
2808  switch (Type) {
2809  case TargetInfo::NoInt: return QualType();
2810  case TargetInfo::SignedShort: return ShortTy;
2811  case TargetInfo::UnsignedShort: return UnsignedShortTy;
2812  case TargetInfo::SignedInt: return IntTy;
2813  case TargetInfo::UnsignedInt: return UnsignedIntTy;
2814  case TargetInfo::SignedLong: return LongTy;
2815  case TargetInfo::UnsignedLong: return UnsignedLongTy;
2816  case TargetInfo::SignedLongLong: return LongLongTy;
2817  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
2818  }
2819
2820  assert(false && "Unhandled TargetInfo::IntType value");
2821  return QualType();
2822}
2823
2824//===----------------------------------------------------------------------===//
2825//                        Type Predicates.
2826//===----------------------------------------------------------------------===//
2827
2828/// isObjCNSObjectType - Return true if this is an NSObject object using
2829/// NSObject attribute on a c-style pointer type.
2830/// FIXME - Make it work directly on types.
2831///
2832bool ASTContext::isObjCNSObjectType(QualType Ty) const {
2833  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2834    if (TypedefDecl *TD = TDT->getDecl())
2835      if (TD->getAttr<ObjCNSObjectAttr>(*const_cast<ASTContext*>(this)))
2836        return true;
2837  }
2838  return false;
2839}
2840
2841/// isObjCObjectPointerType - Returns true if type is an Objective-C pointer
2842/// to an object type.  This includes "id" and "Class" (two 'special' pointers
2843/// to struct), Interface* (pointer to ObjCInterfaceType) and id<P> (qualified
2844/// ID type).
2845bool ASTContext::isObjCObjectPointerType(QualType Ty) const {
2846  if (Ty->isObjCQualifiedIdType())
2847    return true;
2848
2849  // Blocks are objects.
2850  if (Ty->isBlockPointerType())
2851    return true;
2852
2853  // All other object types are pointers.
2854  const PointerType *PT = Ty->getAsPointerType();
2855  if (PT == 0)
2856    return false;
2857
2858  // If this a pointer to an interface (e.g. NSString*), it is ok.
2859  if (PT->getPointeeType()->isObjCInterfaceType() ||
2860      // If is has NSObject attribute, OK as well.
2861      isObjCNSObjectType(Ty))
2862    return true;
2863
2864  // Check to see if this is 'id' or 'Class', both of which are typedefs for
2865  // pointer types.  This looks for the typedef specifically, not for the
2866  // underlying type.  Iteratively strip off typedefs so that we can handle
2867  // typedefs of typedefs.
2868  while (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
2869    if (Ty.getUnqualifiedType() == getObjCIdType() ||
2870        Ty.getUnqualifiedType() == getObjCClassType())
2871      return true;
2872
2873    Ty = TDT->getDecl()->getUnderlyingType();
2874  }
2875
2876  return false;
2877}
2878
2879/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
2880/// garbage collection attribute.
2881///
2882QualType::GCAttrTypes ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
2883  QualType::GCAttrTypes GCAttrs = QualType::GCNone;
2884  if (getLangOptions().ObjC1 &&
2885      getLangOptions().getGCMode() != LangOptions::NonGC) {
2886    GCAttrs = Ty.getObjCGCAttr();
2887    // Default behavious under objective-c's gc is for objective-c pointers
2888    // (or pointers to them) be treated as though they were declared
2889    // as __strong.
2890    if (GCAttrs == QualType::GCNone) {
2891      if (isObjCObjectPointerType(Ty))
2892        GCAttrs = QualType::Strong;
2893      else if (Ty->isPointerType())
2894        return getObjCGCAttrKind(Ty->getAsPointerType()->getPointeeType());
2895    }
2896    // Non-pointers have none gc'able attribute regardless of the attribute
2897    // set on them.
2898    else if (!Ty->isPointerType() && !isObjCObjectPointerType(Ty))
2899      return QualType::GCNone;
2900  }
2901  return GCAttrs;
2902}
2903
2904//===----------------------------------------------------------------------===//
2905//                        Type Compatibility Testing
2906//===----------------------------------------------------------------------===//
2907
2908/// areCompatVectorTypes - Return true if the two specified vector types are
2909/// compatible.
2910static bool areCompatVectorTypes(const VectorType *LHS,
2911                                 const VectorType *RHS) {
2912  assert(LHS->isCanonical() && RHS->isCanonical());
2913  return LHS->getElementType() == RHS->getElementType() &&
2914         LHS->getNumElements() == RHS->getNumElements();
2915}
2916
2917/// canAssignObjCInterfaces - Return true if the two interface types are
2918/// compatible for assignment from RHS to LHS.  This handles validation of any
2919/// protocol qualifiers on the LHS or RHS.
2920///
2921bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
2922                                         const ObjCInterfaceType *RHS) {
2923  // Verify that the base decls are compatible: the RHS must be a subclass of
2924  // the LHS.
2925  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
2926    return false;
2927
2928  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
2929  // protocol qualified at all, then we are good.
2930  if (!isa<ObjCQualifiedInterfaceType>(LHS))
2931    return true;
2932
2933  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
2934  // isn't a superset.
2935  if (!isa<ObjCQualifiedInterfaceType>(RHS))
2936    return true;  // FIXME: should return false!
2937
2938  // Finally, we must have two protocol-qualified interfaces.
2939  const ObjCQualifiedInterfaceType *LHSP =cast<ObjCQualifiedInterfaceType>(LHS);
2940  const ObjCQualifiedInterfaceType *RHSP =cast<ObjCQualifiedInterfaceType>(RHS);
2941
2942  // All LHS protocols must have a presence on the RHS.
2943  assert(LHSP->qual_begin() != LHSP->qual_end() && "Empty LHS protocol list?");
2944
2945  for (ObjCQualifiedInterfaceType::qual_iterator LHSPI = LHSP->qual_begin(),
2946                                                 LHSPE = LHSP->qual_end();
2947       LHSPI != LHSPE; LHSPI++) {
2948    bool RHSImplementsProtocol = false;
2949
2950    // If the RHS doesn't implement the protocol on the left, the types
2951    // are incompatible.
2952    for (ObjCQualifiedInterfaceType::qual_iterator RHSPI = RHSP->qual_begin(),
2953                                                   RHSPE = RHSP->qual_end();
2954         !RHSImplementsProtocol && (RHSPI != RHSPE); RHSPI++) {
2955      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier()))
2956        RHSImplementsProtocol = true;
2957    }
2958    // FIXME: For better diagnostics, consider passing back the protocol name.
2959    if (!RHSImplementsProtocol)
2960      return false;
2961  }
2962  // The RHS implements all protocols listed on the LHS.
2963  return true;
2964}
2965
2966bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
2967  // get the "pointed to" types
2968  const PointerType *LHSPT = LHS->getAsPointerType();
2969  const PointerType *RHSPT = RHS->getAsPointerType();
2970
2971  if (!LHSPT || !RHSPT)
2972    return false;
2973
2974  QualType lhptee = LHSPT->getPointeeType();
2975  QualType rhptee = RHSPT->getPointeeType();
2976  const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2977  const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2978  // ID acts sort of like void* for ObjC interfaces
2979  if (LHSIface && isObjCIdStructType(rhptee))
2980    return true;
2981  if (RHSIface && isObjCIdStructType(lhptee))
2982    return true;
2983  if (!LHSIface || !RHSIface)
2984    return false;
2985  return canAssignObjCInterfaces(LHSIface, RHSIface) ||
2986         canAssignObjCInterfaces(RHSIface, LHSIface);
2987}
2988
2989/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
2990/// both shall have the identically qualified version of a compatible type.
2991/// C99 6.2.7p1: Two types have compatible types if their types are the
2992/// same. See 6.7.[2,3,5] for additional rules.
2993bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
2994  return !mergeTypes(LHS, RHS).isNull();
2995}
2996
2997QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs) {
2998  const FunctionType *lbase = lhs->getAsFunctionType();
2999  const FunctionType *rbase = rhs->getAsFunctionType();
3000  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
3001  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
3002  bool allLTypes = true;
3003  bool allRTypes = true;
3004
3005  // Check return type
3006  QualType retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
3007  if (retType.isNull()) return QualType();
3008  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
3009    allLTypes = false;
3010  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
3011    allRTypes = false;
3012
3013  if (lproto && rproto) { // two C99 style function prototypes
3014    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
3015           "C++ shouldn't be here");
3016    unsigned lproto_nargs = lproto->getNumArgs();
3017    unsigned rproto_nargs = rproto->getNumArgs();
3018
3019    // Compatible functions must have the same number of arguments
3020    if (lproto_nargs != rproto_nargs)
3021      return QualType();
3022
3023    // Variadic and non-variadic functions aren't compatible
3024    if (lproto->isVariadic() != rproto->isVariadic())
3025      return QualType();
3026
3027    if (lproto->getTypeQuals() != rproto->getTypeQuals())
3028      return QualType();
3029
3030    // Check argument compatibility
3031    llvm::SmallVector<QualType, 10> types;
3032    for (unsigned i = 0; i < lproto_nargs; i++) {
3033      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
3034      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
3035      QualType argtype = mergeTypes(largtype, rargtype);
3036      if (argtype.isNull()) return QualType();
3037      types.push_back(argtype);
3038      if (getCanonicalType(argtype) != getCanonicalType(largtype))
3039        allLTypes = false;
3040      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
3041        allRTypes = false;
3042    }
3043    if (allLTypes) return lhs;
3044    if (allRTypes) return rhs;
3045    return getFunctionType(retType, types.begin(), types.size(),
3046                           lproto->isVariadic(), lproto->getTypeQuals());
3047  }
3048
3049  if (lproto) allRTypes = false;
3050  if (rproto) allLTypes = false;
3051
3052  const FunctionProtoType *proto = lproto ? lproto : rproto;
3053  if (proto) {
3054    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
3055    if (proto->isVariadic()) return QualType();
3056    // Check that the types are compatible with the types that
3057    // would result from default argument promotions (C99 6.7.5.3p15).
3058    // The only types actually affected are promotable integer
3059    // types and floats, which would be passed as a different
3060    // type depending on whether the prototype is visible.
3061    unsigned proto_nargs = proto->getNumArgs();
3062    for (unsigned i = 0; i < proto_nargs; ++i) {
3063      QualType argTy = proto->getArgType(i);
3064      if (argTy->isPromotableIntegerType() ||
3065          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
3066        return QualType();
3067    }
3068
3069    if (allLTypes) return lhs;
3070    if (allRTypes) return rhs;
3071    return getFunctionType(retType, proto->arg_type_begin(),
3072                           proto->getNumArgs(), lproto->isVariadic(),
3073                           lproto->getTypeQuals());
3074  }
3075
3076  if (allLTypes) return lhs;
3077  if (allRTypes) return rhs;
3078  return getFunctionNoProtoType(retType);
3079}
3080
3081QualType ASTContext::mergeTypes(QualType LHS, QualType RHS) {
3082  // C++ [expr]: If an expression initially has the type "reference to T", the
3083  // type is adjusted to "T" prior to any further analysis, the expression
3084  // designates the object or function denoted by the reference, and the
3085  // expression is an lvalue unless the reference is an rvalue reference and
3086  // the expression is a function call (possibly inside parentheses).
3087  // FIXME: C++ shouldn't be going through here!  The rules are different
3088  // enough that they should be handled separately.
3089  // FIXME: Merging of lvalue and rvalue references is incorrect. C++ *really*
3090  // shouldn't be going through here!
3091  if (const ReferenceType *RT = LHS->getAsReferenceType())
3092    LHS = RT->getPointeeType();
3093  if (const ReferenceType *RT = RHS->getAsReferenceType())
3094    RHS = RT->getPointeeType();
3095
3096  QualType LHSCan = getCanonicalType(LHS),
3097           RHSCan = getCanonicalType(RHS);
3098
3099  // If two types are identical, they are compatible.
3100  if (LHSCan == RHSCan)
3101    return LHS;
3102
3103  // If the qualifiers are different, the types aren't compatible
3104  // Note that we handle extended qualifiers later, in the
3105  // case for ExtQualType.
3106  if (LHSCan.getCVRQualifiers() != RHSCan.getCVRQualifiers())
3107    return QualType();
3108
3109  Type::TypeClass LHSClass = LHSCan->getTypeClass();
3110  Type::TypeClass RHSClass = RHSCan->getTypeClass();
3111
3112  // We want to consider the two function types to be the same for these
3113  // comparisons, just force one to the other.
3114  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
3115  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
3116
3117  // Strip off objc_gc attributes off the top level so they can be merged.
3118  // This is a complete mess, but the attribute itself doesn't make much sense.
3119  if (RHSClass == Type::ExtQual) {
3120    QualType::GCAttrTypes GCAttr = RHSCan.getObjCGCAttr();
3121    if (GCAttr != QualType::GCNone) {
3122      QualType::GCAttrTypes GCLHSAttr = LHSCan.getObjCGCAttr();
3123      // __weak attribute must appear on both declarations.
3124      // __strong attribue is redundant if other decl is an objective-c
3125      // object pointer (or decorated with __strong attribute); otherwise
3126      // issue error.
3127      if ((GCAttr == QualType::Weak && GCLHSAttr != GCAttr) ||
3128          (GCAttr == QualType::Strong && GCLHSAttr != GCAttr &&
3129           LHSCan->isPointerType() && !isObjCObjectPointerType(LHSCan) &&
3130           !isObjCIdStructType(LHSCan->getAsPointerType()->getPointeeType())))
3131        return QualType();
3132
3133      RHS = QualType(cast<ExtQualType>(RHS.getDesugaredType())->getBaseType(),
3134                     RHS.getCVRQualifiers());
3135      QualType Result = mergeTypes(LHS, RHS);
3136      if (!Result.isNull()) {
3137        if (Result.getObjCGCAttr() == QualType::GCNone)
3138          Result = getObjCGCQualType(Result, GCAttr);
3139        else if (Result.getObjCGCAttr() != GCAttr)
3140          Result = QualType();
3141      }
3142      return Result;
3143    }
3144  }
3145  if (LHSClass == Type::ExtQual) {
3146    QualType::GCAttrTypes GCAttr = LHSCan.getObjCGCAttr();
3147    if (GCAttr != QualType::GCNone) {
3148      QualType::GCAttrTypes GCRHSAttr = RHSCan.getObjCGCAttr();
3149      // __weak attribute must appear on both declarations. __strong
3150      // __strong attribue is redundant if other decl is an objective-c
3151      // object pointer (or decorated with __strong attribute); otherwise
3152      // issue error.
3153      if ((GCAttr == QualType::Weak && GCRHSAttr != GCAttr) ||
3154          (GCAttr == QualType::Strong && GCRHSAttr != GCAttr &&
3155           RHSCan->isPointerType() && !isObjCObjectPointerType(RHSCan) &&
3156           !isObjCIdStructType(RHSCan->getAsPointerType()->getPointeeType())))
3157        return QualType();
3158
3159      LHS = QualType(cast<ExtQualType>(LHS.getDesugaredType())->getBaseType(),
3160                     LHS.getCVRQualifiers());
3161      QualType Result = mergeTypes(LHS, RHS);
3162      if (!Result.isNull()) {
3163        if (Result.getObjCGCAttr() == QualType::GCNone)
3164          Result = getObjCGCQualType(Result, GCAttr);
3165        else if (Result.getObjCGCAttr() != GCAttr)
3166          Result = QualType();
3167      }
3168      return Result;
3169    }
3170  }
3171
3172  // Same as above for arrays
3173  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
3174    LHSClass = Type::ConstantArray;
3175  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
3176    RHSClass = Type::ConstantArray;
3177
3178  // Canonicalize ExtVector -> Vector.
3179  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
3180  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
3181
3182  // Consider qualified interfaces and interfaces the same.
3183  if (LHSClass == Type::ObjCQualifiedInterface) LHSClass = Type::ObjCInterface;
3184  if (RHSClass == Type::ObjCQualifiedInterface) RHSClass = Type::ObjCInterface;
3185
3186  // If the canonical type classes don't match.
3187  if (LHSClass != RHSClass) {
3188    const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3189    const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3190
3191    // 'id' and 'Class' act sort of like void* for ObjC interfaces
3192    if (LHSIface && (isObjCIdStructType(RHS) || isObjCClassStructType(RHS)))
3193      return LHS;
3194    if (RHSIface && (isObjCIdStructType(LHS) || isObjCClassStructType(LHS)))
3195      return RHS;
3196
3197    // ID is compatible with all qualified id types.
3198    if (LHS->isObjCQualifiedIdType()) {
3199      if (const PointerType *PT = RHS->getAsPointerType()) {
3200        QualType pType = PT->getPointeeType();
3201        if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
3202          return LHS;
3203        // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3204        // Unfortunately, this API is part of Sema (which we don't have access
3205        // to. Need to refactor. The following check is insufficient, since we
3206        // need to make sure the class implements the protocol.
3207        if (pType->isObjCInterfaceType())
3208          return LHS;
3209      }
3210    }
3211    if (RHS->isObjCQualifiedIdType()) {
3212      if (const PointerType *PT = LHS->getAsPointerType()) {
3213        QualType pType = PT->getPointeeType();
3214        if (isObjCIdStructType(pType) || isObjCClassStructType(pType))
3215          return RHS;
3216        // FIXME: need to use ObjCQualifiedIdTypesAreCompatible(LHS, RHS, true).
3217        // Unfortunately, this API is part of Sema (which we don't have access
3218        // to. Need to refactor. The following check is insufficient, since we
3219        // need to make sure the class implements the protocol.
3220        if (pType->isObjCInterfaceType())
3221          return RHS;
3222      }
3223    }
3224    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
3225    // a signed integer type, or an unsigned integer type.
3226    if (const EnumType* ETy = LHS->getAsEnumType()) {
3227      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
3228        return RHS;
3229    }
3230    if (const EnumType* ETy = RHS->getAsEnumType()) {
3231      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
3232        return LHS;
3233    }
3234
3235    return QualType();
3236  }
3237
3238  // The canonical type classes match.
3239  switch (LHSClass) {
3240#define TYPE(Class, Base)
3241#define ABSTRACT_TYPE(Class, Base)
3242#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3243#define DEPENDENT_TYPE(Class, Base) case Type::Class:
3244#include "clang/AST/TypeNodes.def"
3245    assert(false && "Non-canonical and dependent types shouldn't get here");
3246    return QualType();
3247
3248  case Type::LValueReference:
3249  case Type::RValueReference:
3250  case Type::MemberPointer:
3251    assert(false && "C++ should never be in mergeTypes");
3252    return QualType();
3253
3254  case Type::IncompleteArray:
3255  case Type::VariableArray:
3256  case Type::FunctionProto:
3257  case Type::ExtVector:
3258  case Type::ObjCQualifiedInterface:
3259    assert(false && "Types are eliminated above");
3260    return QualType();
3261
3262  case Type::Pointer:
3263  {
3264    // Merge two pointer types, while trying to preserve typedef info
3265    QualType LHSPointee = LHS->getAsPointerType()->getPointeeType();
3266    QualType RHSPointee = RHS->getAsPointerType()->getPointeeType();
3267    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3268    if (ResultType.isNull()) return QualType();
3269    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3270      return LHS;
3271    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3272      return RHS;
3273    return getPointerType(ResultType);
3274  }
3275  case Type::BlockPointer:
3276  {
3277    // Merge two block pointer types, while trying to preserve typedef info
3278    QualType LHSPointee = LHS->getAsBlockPointerType()->getPointeeType();
3279    QualType RHSPointee = RHS->getAsBlockPointerType()->getPointeeType();
3280    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
3281    if (ResultType.isNull()) return QualType();
3282    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
3283      return LHS;
3284    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
3285      return RHS;
3286    return getBlockPointerType(ResultType);
3287  }
3288  case Type::ConstantArray:
3289  {
3290    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
3291    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
3292    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
3293      return QualType();
3294
3295    QualType LHSElem = getAsArrayType(LHS)->getElementType();
3296    QualType RHSElem = getAsArrayType(RHS)->getElementType();
3297    QualType ResultType = mergeTypes(LHSElem, RHSElem);
3298    if (ResultType.isNull()) return QualType();
3299    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3300      return LHS;
3301    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3302      return RHS;
3303    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
3304                                          ArrayType::ArraySizeModifier(), 0);
3305    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
3306                                          ArrayType::ArraySizeModifier(), 0);
3307    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
3308    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
3309    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
3310      return LHS;
3311    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
3312      return RHS;
3313    if (LVAT) {
3314      // FIXME: This isn't correct! But tricky to implement because
3315      // the array's size has to be the size of LHS, but the type
3316      // has to be different.
3317      return LHS;
3318    }
3319    if (RVAT) {
3320      // FIXME: This isn't correct! But tricky to implement because
3321      // the array's size has to be the size of RHS, but the type
3322      // has to be different.
3323      return RHS;
3324    }
3325    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
3326    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
3327    return getIncompleteArrayType(ResultType, ArrayType::ArraySizeModifier(),0);
3328  }
3329  case Type::FunctionNoProto:
3330    return mergeFunctionTypes(LHS, RHS);
3331  case Type::Record:
3332  case Type::Enum:
3333    // FIXME: Why are these compatible?
3334    if (isObjCIdStructType(LHS) && isObjCClassStructType(RHS)) return LHS;
3335    if (isObjCClassStructType(LHS) && isObjCIdStructType(RHS)) return LHS;
3336    return QualType();
3337  case Type::Builtin:
3338    // Only exactly equal builtin types are compatible, which is tested above.
3339    return QualType();
3340  case Type::Complex:
3341    // Distinct complex types are incompatible.
3342    return QualType();
3343  case Type::Vector:
3344    // FIXME: The merged type should be an ExtVector!
3345    if (areCompatVectorTypes(LHS->getAsVectorType(), RHS->getAsVectorType()))
3346      return LHS;
3347    return QualType();
3348  case Type::ObjCInterface: {
3349    // Check if the interfaces are assignment compatible.
3350    // FIXME: This should be type compatibility, e.g. whether
3351    // "LHS x; RHS x;" at global scope is legal.
3352    const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
3353    const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
3354    if (LHSIface && RHSIface &&
3355        canAssignObjCInterfaces(LHSIface, RHSIface))
3356      return LHS;
3357
3358    return QualType();
3359  }
3360  case Type::ObjCObjectPointer:
3361    // FIXME: finish
3362    // Distinct qualified id's are not compatible.
3363    return QualType();
3364  case Type::FixedWidthInt:
3365    // Distinct fixed-width integers are not compatible.
3366    return QualType();
3367  case Type::ExtQual:
3368    // FIXME: ExtQual types can be compatible even if they're not
3369    // identical!
3370    return QualType();
3371    // First attempt at an implementation, but I'm not really sure it's
3372    // right...
3373#if 0
3374    ExtQualType* LQual = cast<ExtQualType>(LHSCan);
3375    ExtQualType* RQual = cast<ExtQualType>(RHSCan);
3376    if (LQual->getAddressSpace() != RQual->getAddressSpace() ||
3377        LQual->getObjCGCAttr() != RQual->getObjCGCAttr())
3378      return QualType();
3379    QualType LHSBase, RHSBase, ResultType, ResCanUnqual;
3380    LHSBase = QualType(LQual->getBaseType(), 0);
3381    RHSBase = QualType(RQual->getBaseType(), 0);
3382    ResultType = mergeTypes(LHSBase, RHSBase);
3383    if (ResultType.isNull()) return QualType();
3384    ResCanUnqual = getCanonicalType(ResultType).getUnqualifiedType();
3385    if (LHSCan.getUnqualifiedType() == ResCanUnqual)
3386      return LHS;
3387    if (RHSCan.getUnqualifiedType() == ResCanUnqual)
3388      return RHS;
3389    ResultType = getAddrSpaceQualType(ResultType, LQual->getAddressSpace());
3390    ResultType = getObjCGCQualType(ResultType, LQual->getObjCGCAttr());
3391    ResultType.setCVRQualifiers(LHSCan.getCVRQualifiers());
3392    return ResultType;
3393#endif
3394
3395  case Type::TemplateSpecialization:
3396    assert(false && "Dependent types have no size");
3397    break;
3398  }
3399
3400  return QualType();
3401}
3402
3403//===----------------------------------------------------------------------===//
3404//                         Integer Predicates
3405//===----------------------------------------------------------------------===//
3406
3407unsigned ASTContext::getIntWidth(QualType T) {
3408  if (T == BoolTy)
3409    return 1;
3410  if (FixedWidthIntType* FWIT = dyn_cast<FixedWidthIntType>(T)) {
3411    return FWIT->getWidth();
3412  }
3413  // For builtin types, just use the standard type sizing method
3414  return (unsigned)getTypeSize(T);
3415}
3416
3417QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
3418  assert(T->isSignedIntegerType() && "Unexpected type");
3419  if (const EnumType* ETy = T->getAsEnumType())
3420    T = ETy->getDecl()->getIntegerType();
3421  const BuiltinType* BTy = T->getAsBuiltinType();
3422  assert (BTy && "Unexpected signed integer type");
3423  switch (BTy->getKind()) {
3424  case BuiltinType::Char_S:
3425  case BuiltinType::SChar:
3426    return UnsignedCharTy;
3427  case BuiltinType::Short:
3428    return UnsignedShortTy;
3429  case BuiltinType::Int:
3430    return UnsignedIntTy;
3431  case BuiltinType::Long:
3432    return UnsignedLongTy;
3433  case BuiltinType::LongLong:
3434    return UnsignedLongLongTy;
3435  case BuiltinType::Int128:
3436    return UnsignedInt128Ty;
3437  default:
3438    assert(0 && "Unexpected signed integer type");
3439    return QualType();
3440  }
3441}
3442
3443ExternalASTSource::~ExternalASTSource() { }
3444
3445void ExternalASTSource::PrintStats() { }
3446
3447
3448//===----------------------------------------------------------------------===//
3449//                          Builtin Type Computation
3450//===----------------------------------------------------------------------===//
3451
3452/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
3453/// pointer over the consumed characters.  This returns the resultant type.
3454static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
3455                                  ASTContext::GetBuiltinTypeError &Error,
3456                                  bool AllowTypeModifiers = true) {
3457  // Modifiers.
3458  int HowLong = 0;
3459  bool Signed = false, Unsigned = false;
3460
3461  // Read the modifiers first.
3462  bool Done = false;
3463  while (!Done) {
3464    switch (*Str++) {
3465    default: Done = true; --Str; break;
3466    case 'S':
3467      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
3468      assert(!Signed && "Can't use 'S' modifier multiple times!");
3469      Signed = true;
3470      break;
3471    case 'U':
3472      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
3473      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
3474      Unsigned = true;
3475      break;
3476    case 'L':
3477      assert(HowLong <= 2 && "Can't have LLLL modifier");
3478      ++HowLong;
3479      break;
3480    }
3481  }
3482
3483  QualType Type;
3484
3485  // Read the base type.
3486  switch (*Str++) {
3487  default: assert(0 && "Unknown builtin type letter!");
3488  case 'v':
3489    assert(HowLong == 0 && !Signed && !Unsigned &&
3490           "Bad modifiers used with 'v'!");
3491    Type = Context.VoidTy;
3492    break;
3493  case 'f':
3494    assert(HowLong == 0 && !Signed && !Unsigned &&
3495           "Bad modifiers used with 'f'!");
3496    Type = Context.FloatTy;
3497    break;
3498  case 'd':
3499    assert(HowLong < 2 && !Signed && !Unsigned &&
3500           "Bad modifiers used with 'd'!");
3501    if (HowLong)
3502      Type = Context.LongDoubleTy;
3503    else
3504      Type = Context.DoubleTy;
3505    break;
3506  case 's':
3507    assert(HowLong == 0 && "Bad modifiers used with 's'!");
3508    if (Unsigned)
3509      Type = Context.UnsignedShortTy;
3510    else
3511      Type = Context.ShortTy;
3512    break;
3513  case 'i':
3514    if (HowLong == 3)
3515      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
3516    else if (HowLong == 2)
3517      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
3518    else if (HowLong == 1)
3519      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
3520    else
3521      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
3522    break;
3523  case 'c':
3524    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
3525    if (Signed)
3526      Type = Context.SignedCharTy;
3527    else if (Unsigned)
3528      Type = Context.UnsignedCharTy;
3529    else
3530      Type = Context.CharTy;
3531    break;
3532  case 'b': // boolean
3533    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
3534    Type = Context.BoolTy;
3535    break;
3536  case 'z':  // size_t.
3537    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
3538    Type = Context.getSizeType();
3539    break;
3540  case 'F':
3541    Type = Context.getCFConstantStringType();
3542    break;
3543  case 'a':
3544    Type = Context.getBuiltinVaListType();
3545    assert(!Type.isNull() && "builtin va list type not initialized!");
3546    break;
3547  case 'A':
3548    // This is a "reference" to a va_list; however, what exactly
3549    // this means depends on how va_list is defined. There are two
3550    // different kinds of va_list: ones passed by value, and ones
3551    // passed by reference.  An example of a by-value va_list is
3552    // x86, where va_list is a char*. An example of by-ref va_list
3553    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
3554    // we want this argument to be a char*&; for x86-64, we want
3555    // it to be a __va_list_tag*.
3556    Type = Context.getBuiltinVaListType();
3557    assert(!Type.isNull() && "builtin va list type not initialized!");
3558    if (Type->isArrayType()) {
3559      Type = Context.getArrayDecayedType(Type);
3560    } else {
3561      Type = Context.getLValueReferenceType(Type);
3562    }
3563    break;
3564  case 'V': {
3565    char *End;
3566
3567    unsigned NumElements = strtoul(Str, &End, 10);
3568    assert(End != Str && "Missing vector size");
3569
3570    Str = End;
3571
3572    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
3573    Type = Context.getVectorType(ElementType, NumElements);
3574    break;
3575  }
3576  case 'P': {
3577    IdentifierInfo *II = &Context.Idents.get("FILE");
3578    DeclContext::lookup_result Lookup
3579      = Context.getTranslationUnitDecl()->lookup(Context, II);
3580    if (Lookup.first != Lookup.second && isa<TypeDecl>(*Lookup.first)) {
3581      Type = Context.getTypeDeclType(cast<TypeDecl>(*Lookup.first));
3582      break;
3583    }
3584    else {
3585      Error = ASTContext::GE_Missing_FILE;
3586      return QualType();
3587    }
3588  }
3589  }
3590
3591  if (!AllowTypeModifiers)
3592    return Type;
3593
3594  Done = false;
3595  while (!Done) {
3596    switch (*Str++) {
3597      default: Done = true; --Str; break;
3598      case '*':
3599        Type = Context.getPointerType(Type);
3600        break;
3601      case '&':
3602        Type = Context.getLValueReferenceType(Type);
3603        break;
3604      // FIXME: There's no way to have a built-in with an rvalue ref arg.
3605      case 'C':
3606        Type = Type.getQualifiedType(QualType::Const);
3607        break;
3608    }
3609  }
3610
3611  return Type;
3612}
3613
3614/// GetBuiltinType - Return the type for the specified builtin.
3615QualType ASTContext::GetBuiltinType(unsigned id,
3616                                    GetBuiltinTypeError &Error) {
3617  const char *TypeStr = BuiltinInfo.GetTypeString(id);
3618
3619  llvm::SmallVector<QualType, 8> ArgTypes;
3620
3621  Error = GE_None;
3622  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
3623  if (Error != GE_None)
3624    return QualType();
3625  while (TypeStr[0] && TypeStr[0] != '.') {
3626    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
3627    if (Error != GE_None)
3628      return QualType();
3629
3630    // Do array -> pointer decay.  The builtin should use the decayed type.
3631    if (Ty->isArrayType())
3632      Ty = getArrayDecayedType(Ty);
3633
3634    ArgTypes.push_back(Ty);
3635  }
3636
3637  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
3638         "'.' should only occur at end of builtin type list!");
3639
3640  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
3641  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
3642    return getFunctionNoProtoType(ResType);
3643  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
3644                         TypeStr[0] == '.', 0);
3645}
3646