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