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