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