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