ASTContext.cpp revision 80aa1cd7973561889e51c1c152c8990a8de9c953
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/CharUnits.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExternalASTSource.h"
23#include "clang/AST/RecordLayout.h"
24#include "clang/Basic/Builtins.h"
25#include "clang/Basic/SourceManager.h"
26#include "clang/Basic/TargetInfo.h"
27#include "llvm/ADT/SmallString.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/Support/MathExtras.h"
30#include "llvm/Support/raw_ostream.h"
31
32using namespace clang;
33
34enum FloatingRank {
35  FloatRank, DoubleRank, LongDoubleRank
36};
37
38void
39ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
40                                               TemplateTemplateParmDecl *Parm) {
41  ID.AddInteger(Parm->getDepth());
42  ID.AddInteger(Parm->getPosition());
43  // FIXME: Parameter pack
44
45  TemplateParameterList *Params = Parm->getTemplateParameters();
46  ID.AddInteger(Params->size());
47  for (TemplateParameterList::const_iterator P = Params->begin(),
48                                          PEnd = Params->end();
49       P != PEnd; ++P) {
50    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
51      ID.AddInteger(0);
52      ID.AddBoolean(TTP->isParameterPack());
53      continue;
54    }
55
56    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
57      ID.AddInteger(1);
58      // FIXME: Parameter pack
59      ID.AddPointer(NTTP->getType().getAsOpaquePtr());
60      continue;
61    }
62
63    TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
64    ID.AddInteger(2);
65    Profile(ID, TTP);
66  }
67}
68
69TemplateTemplateParmDecl *
70ASTContext::getCanonicalTemplateTemplateParmDecl(
71                                                 TemplateTemplateParmDecl *TTP) {
72  // Check if we already have a canonical template template parameter.
73  llvm::FoldingSetNodeID ID;
74  CanonicalTemplateTemplateParm::Profile(ID, TTP);
75  void *InsertPos = 0;
76  CanonicalTemplateTemplateParm *Canonical
77    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
78  if (Canonical)
79    return Canonical->getParam();
80
81  // Build a canonical template parameter list.
82  TemplateParameterList *Params = TTP->getTemplateParameters();
83  llvm::SmallVector<NamedDecl *, 4> CanonParams;
84  CanonParams.reserve(Params->size());
85  for (TemplateParameterList::const_iterator P = Params->begin(),
86                                          PEnd = Params->end();
87       P != PEnd; ++P) {
88    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
89      CanonParams.push_back(
90                  TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
91                                               SourceLocation(), TTP->getDepth(),
92                                               TTP->getIndex(), 0, false,
93                                               TTP->isParameterPack()));
94    else if (NonTypeTemplateParmDecl *NTTP
95             = dyn_cast<NonTypeTemplateParmDecl>(*P))
96      CanonParams.push_back(
97            NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
98                                            SourceLocation(), NTTP->getDepth(),
99                                            NTTP->getPosition(), 0,
100                                            getCanonicalType(NTTP->getType()),
101                                            0));
102    else
103      CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
104                                           cast<TemplateTemplateParmDecl>(*P)));
105  }
106
107  TemplateTemplateParmDecl *CanonTTP
108    = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
109                                       SourceLocation(), TTP->getDepth(),
110                                       TTP->getPosition(), 0,
111                         TemplateParameterList::Create(*this, SourceLocation(),
112                                                       SourceLocation(),
113                                                       CanonParams.data(),
114                                                       CanonParams.size(),
115                                                       SourceLocation()));
116
117  // Get the new insert position for the node we care about.
118  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
119  assert(Canonical == 0 && "Shouldn't be in the map!");
120  (void)Canonical;
121
122  // Create the canonical template template parameter entry.
123  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
124  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
125  return CanonTTP;
126}
127
128ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM,
129                       const TargetInfo &t,
130                       IdentifierTable &idents, SelectorTable &sels,
131                       Builtin::Context &builtins,
132                       bool FreeMem, unsigned size_reserve) :
133  TemplateSpecializationTypes(this_()),
134  DependentTemplateSpecializationTypes(this_()),
135  GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0),
136  NSConstantStringTypeDecl(0),
137  ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0),
138  sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0),
139  NullTypeSourceInfo(QualType()),
140  SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t),
141  Idents(idents), Selectors(sels),
142  BuiltinInfo(builtins),
143  DeclarationNames(*this),
144  ExternalSource(0), PrintingPolicy(LOpts),
145  LastSDM(0, 0),
146  UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) {
147  ObjCIdRedefinitionType = QualType();
148  ObjCClassRedefinitionType = QualType();
149  ObjCSelRedefinitionType = QualType();
150  if (size_reserve > 0) Types.reserve(size_reserve);
151  TUDecl = TranslationUnitDecl::Create(*this);
152  InitBuiltinTypes();
153}
154
155ASTContext::~ASTContext() {
156  // Release the DenseMaps associated with DeclContext objects.
157  // FIXME: Is this the ideal solution?
158  ReleaseDeclContextMaps();
159
160  if (!FreeMemory) {
161    // Call all of the deallocation functions.
162    for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
163      Deallocations[I].first(Deallocations[I].second);
164  }
165
166  // Release all of the memory associated with overridden C++ methods.
167  for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator
168         OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end();
169       OM != OMEnd; ++OM)
170    OM->second.Destroy();
171
172  if (FreeMemory) {
173    // Deallocate all the types.
174    while (!Types.empty()) {
175      Types.back()->Destroy(*this);
176      Types.pop_back();
177    }
178
179    for (llvm::FoldingSet<ExtQuals>::iterator
180         I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) {
181      // Increment in loop to prevent using deallocated memory.
182      Deallocate(&*I++);
183    }
184
185    for (llvm::DenseMap<const ObjCContainerDecl*,
186         const ASTRecordLayout*>::iterator
187         I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) {
188      // Increment in loop to prevent using deallocated memory.
189      if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
190        R->Destroy(*this);
191    }
192  }
193
194  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
195  // even when using the BumpPtrAllocator because they can contain
196  // DenseMaps.
197  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
198       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
199    // Increment in loop to prevent using deallocated memory.
200    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
201      R->Destroy(*this);
202  }
203
204  // Destroy nested-name-specifiers.
205  for (llvm::FoldingSet<NestedNameSpecifier>::iterator
206         NNS = NestedNameSpecifiers.begin(),
207         NNSEnd = NestedNameSpecifiers.end();
208       NNS != NNSEnd; ) {
209    // Increment in loop to prevent using deallocated memory.
210    (*NNS++).Destroy(*this);
211  }
212
213  if (GlobalNestedNameSpecifier)
214    GlobalNestedNameSpecifier->Destroy(*this);
215
216  TUDecl->Destroy(*this);
217}
218
219void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
220  Deallocations.push_back(std::make_pair(Callback, Data));
221}
222
223void
224ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) {
225  ExternalSource.reset(Source.take());
226}
227
228void ASTContext::PrintStats() const {
229  fprintf(stderr, "*** AST Context Stats:\n");
230  fprintf(stderr, "  %d types total.\n", (int)Types.size());
231
232  unsigned counts[] = {
233#define TYPE(Name, Parent) 0,
234#define ABSTRACT_TYPE(Name, Parent)
235#include "clang/AST/TypeNodes.def"
236    0 // Extra
237  };
238
239  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
240    Type *T = Types[i];
241    counts[(unsigned)T->getTypeClass()]++;
242  }
243
244  unsigned Idx = 0;
245  unsigned TotalBytes = 0;
246#define TYPE(Name, Parent)                                              \
247  if (counts[Idx])                                                      \
248    fprintf(stderr, "    %d %s types\n", (int)counts[Idx], #Name);      \
249  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
250  ++Idx;
251#define ABSTRACT_TYPE(Name, Parent)
252#include "clang/AST/TypeNodes.def"
253
254  fprintf(stderr, "Total bytes = %d\n", int(TotalBytes));
255
256  if (ExternalSource.get()) {
257    fprintf(stderr, "\n");
258    ExternalSource->PrintStats();
259  }
260}
261
262
263void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
264  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
265  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
266  Types.push_back(Ty);
267}
268
269void ASTContext::InitBuiltinTypes() {
270  assert(VoidTy.isNull() && "Context reinitialized?");
271
272  // C99 6.2.5p19.
273  InitBuiltinType(VoidTy,              BuiltinType::Void);
274
275  // C99 6.2.5p2.
276  InitBuiltinType(BoolTy,              BuiltinType::Bool);
277  // C99 6.2.5p3.
278  if (LangOpts.CharIsSigned)
279    InitBuiltinType(CharTy,            BuiltinType::Char_S);
280  else
281    InitBuiltinType(CharTy,            BuiltinType::Char_U);
282  // C99 6.2.5p4.
283  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
284  InitBuiltinType(ShortTy,             BuiltinType::Short);
285  InitBuiltinType(IntTy,               BuiltinType::Int);
286  InitBuiltinType(LongTy,              BuiltinType::Long);
287  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
288
289  // C99 6.2.5p6.
290  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
291  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
292  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
293  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
294  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
295
296  // C99 6.2.5p10.
297  InitBuiltinType(FloatTy,             BuiltinType::Float);
298  InitBuiltinType(DoubleTy,            BuiltinType::Double);
299  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
300
301  // GNU extension, 128-bit integers.
302  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
303  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
304
305  if (LangOpts.CPlusPlus) // C++ 3.9.1p5
306    InitBuiltinType(WCharTy,           BuiltinType::WChar);
307  else // C99
308    WCharTy = getFromTargetType(Target.getWCharType());
309
310  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
311    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
312  else // C99
313    Char16Ty = getFromTargetType(Target.getChar16Type());
314
315  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
316    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
317  else // C99
318    Char32Ty = getFromTargetType(Target.getChar32Type());
319
320  // Placeholder type for functions.
321  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
322
323  // Placeholder type for type-dependent expressions whose type is
324  // completely unknown. No code should ever check a type against
325  // DependentTy and users should never see it; however, it is here to
326  // help diagnose failures to properly check for type-dependent
327  // expressions.
328  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
329
330  // Placeholder type for C++0x auto declarations whose real type has
331  // not yet been deduced.
332  InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto);
333
334  // C99 6.2.5p11.
335  FloatComplexTy      = getComplexType(FloatTy);
336  DoubleComplexTy     = getComplexType(DoubleTy);
337  LongDoubleComplexTy = getComplexType(LongDoubleTy);
338
339  BuiltinVaListType = QualType();
340
341  // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope().
342  ObjCIdTypedefType = QualType();
343  ObjCClassTypedefType = QualType();
344  ObjCSelTypedefType = QualType();
345
346  // Builtin types for 'id', 'Class', and 'SEL'.
347  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
348  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
349  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
350
351  ObjCConstantStringType = QualType();
352
353  // void * type
354  VoidPtrTy = getPointerType(VoidTy);
355
356  // nullptr type (C++0x 2.14.7)
357  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
358}
359
360MemberSpecializationInfo *
361ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
362  assert(Var->isStaticDataMember() && "Not a static data member");
363  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
364    = InstantiatedFromStaticDataMember.find(Var);
365  if (Pos == InstantiatedFromStaticDataMember.end())
366    return 0;
367
368  return Pos->second;
369}
370
371void
372ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
373                                                TemplateSpecializationKind TSK) {
374  assert(Inst->isStaticDataMember() && "Not a static data member");
375  assert(Tmpl->isStaticDataMember() && "Not a static data member");
376  assert(!InstantiatedFromStaticDataMember[Inst] &&
377         "Already noted what static data member was instantiated from");
378  InstantiatedFromStaticDataMember[Inst]
379    = new (*this) MemberSpecializationInfo(Tmpl, TSK);
380}
381
382NamedDecl *
383ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
384  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
385    = InstantiatedFromUsingDecl.find(UUD);
386  if (Pos == InstantiatedFromUsingDecl.end())
387    return 0;
388
389  return Pos->second;
390}
391
392void
393ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
394  assert((isa<UsingDecl>(Pattern) ||
395          isa<UnresolvedUsingValueDecl>(Pattern) ||
396          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
397         "pattern decl is not a using decl");
398  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
399  InstantiatedFromUsingDecl[Inst] = Pattern;
400}
401
402UsingShadowDecl *
403ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
404  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
405    = InstantiatedFromUsingShadowDecl.find(Inst);
406  if (Pos == InstantiatedFromUsingShadowDecl.end())
407    return 0;
408
409  return Pos->second;
410}
411
412void
413ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
414                                               UsingShadowDecl *Pattern) {
415  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
416  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
417}
418
419FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
420  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
421    = InstantiatedFromUnnamedFieldDecl.find(Field);
422  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
423    return 0;
424
425  return Pos->second;
426}
427
428void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
429                                                     FieldDecl *Tmpl) {
430  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
431  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
432  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
433         "Already noted what unnamed field was instantiated from");
434
435  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
436}
437
438ASTContext::overridden_cxx_method_iterator
439ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
440  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
441    = OverriddenMethods.find(Method);
442  if (Pos == OverriddenMethods.end())
443    return 0;
444
445  return Pos->second.begin();
446}
447
448ASTContext::overridden_cxx_method_iterator
449ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
450  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
451    = OverriddenMethods.find(Method);
452  if (Pos == OverriddenMethods.end())
453    return 0;
454
455  return Pos->second.end();
456}
457
458void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
459                                     const CXXMethodDecl *Overridden) {
460  OverriddenMethods[Method].push_back(Overridden);
461}
462
463namespace {
464  class BeforeInTranslationUnit
465    : std::binary_function<SourceRange, SourceRange, bool> {
466    SourceManager *SourceMgr;
467
468  public:
469    explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { }
470
471    bool operator()(SourceRange X, SourceRange Y) {
472      return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin());
473    }
474  };
475}
476
477//===----------------------------------------------------------------------===//
478//                         Type Sizing and Analysis
479//===----------------------------------------------------------------------===//
480
481/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
482/// scalar floating point type.
483const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
484  const BuiltinType *BT = T->getAs<BuiltinType>();
485  assert(BT && "Not a floating point type!");
486  switch (BT->getKind()) {
487  default: assert(0 && "Not a floating point type!");
488  case BuiltinType::Float:      return Target.getFloatFormat();
489  case BuiltinType::Double:     return Target.getDoubleFormat();
490  case BuiltinType::LongDouble: return Target.getLongDoubleFormat();
491  }
492}
493
494/// getDeclAlign - Return a conservative estimate of the alignment of the
495/// specified decl.  Note that bitfields do not have a valid alignment, so
496/// this method will assert on them.
497/// If @p RefAsPointee, references are treated like their underlying type
498/// (for alignof), else they're treated like pointers (for CodeGen).
499CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) {
500  unsigned Align = Target.getCharWidth();
501
502  if (const AlignedAttr* AA = D->getAttr<AlignedAttr>())
503    Align = std::max(Align, AA->getMaxAlignment());
504
505  if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
506    QualType T = VD->getType();
507    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
508      if (RefAsPointee)
509        T = RT->getPointeeType();
510      else
511        T = getPointerType(RT->getPointeeType());
512    }
513    if (!T->isIncompleteType() && !T->isFunctionType()) {
514      unsigned MinWidth = Target.getLargeArrayMinWidth();
515      unsigned ArrayAlign = Target.getLargeArrayAlign();
516      if (isa<VariableArrayType>(T) && MinWidth != 0)
517        Align = std::max(Align, ArrayAlign);
518      if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) {
519        unsigned Size = getTypeSize(CT);
520        if (MinWidth != 0 && MinWidth <= Size)
521          Align = std::max(Align, ArrayAlign);
522      }
523      // Incomplete or function types default to 1.
524      while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T))
525        T = cast<ArrayType>(T)->getElementType();
526
527      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
528    }
529    if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
530      // In the case of a field in a packed struct, we want the minimum
531      // of the alignment of the field and the alignment of the struct.
532      Align = std::min(Align,
533        getPreferredTypeAlign(FD->getParent()->getTypeForDecl()));
534    }
535  }
536
537  return CharUnits::fromQuantity(Align / Target.getCharWidth());
538}
539
540std::pair<CharUnits, CharUnits>
541ASTContext::getTypeInfoInChars(const Type *T) {
542  std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
543  return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()),
544                        CharUnits::fromQuantity(Info.second / getCharWidth()));
545}
546
547std::pair<CharUnits, CharUnits>
548ASTContext::getTypeInfoInChars(QualType T) {
549  return getTypeInfoInChars(T.getTypePtr());
550}
551
552/// getTypeSize - Return the size of the specified type, in bits.  This method
553/// does not work on incomplete types.
554///
555/// FIXME: Pointers into different addr spaces could have different sizes and
556/// alignment requirements: getPointerInfo should take an AddrSpace, this
557/// should take a QualType, &c.
558std::pair<uint64_t, unsigned>
559ASTContext::getTypeInfo(const Type *T) {
560  uint64_t Width=0;
561  unsigned Align=8;
562  switch (T->getTypeClass()) {
563#define TYPE(Class, Base)
564#define ABSTRACT_TYPE(Class, Base)
565#define NON_CANONICAL_TYPE(Class, Base)
566#define DEPENDENT_TYPE(Class, Base) case Type::Class:
567#include "clang/AST/TypeNodes.def"
568    assert(false && "Should not see dependent types");
569    break;
570
571  case Type::FunctionNoProto:
572  case Type::FunctionProto:
573    // GCC extension: alignof(function) = 32 bits
574    Width = 0;
575    Align = 32;
576    break;
577
578  case Type::IncompleteArray:
579  case Type::VariableArray:
580    Width = 0;
581    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
582    break;
583
584  case Type::ConstantArray: {
585    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
586
587    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
588    Width = EltInfo.first*CAT->getSize().getZExtValue();
589    Align = EltInfo.second;
590    break;
591  }
592  case Type::ExtVector:
593  case Type::Vector: {
594    const VectorType *VT = cast<VectorType>(T);
595    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
596    Width = EltInfo.first*VT->getNumElements();
597    Align = Width;
598    // If the alignment is not a power of 2, round up to the next power of 2.
599    // This happens for non-power-of-2 length vectors.
600    if (Align & (Align-1)) {
601      Align = llvm::NextPowerOf2(Align);
602      Width = llvm::RoundUpToAlignment(Width, Align);
603    }
604    break;
605  }
606
607  case Type::Builtin:
608    switch (cast<BuiltinType>(T)->getKind()) {
609    default: assert(0 && "Unknown builtin type!");
610    case BuiltinType::Void:
611      // GCC extension: alignof(void) = 8 bits.
612      Width = 0;
613      Align = 8;
614      break;
615
616    case BuiltinType::Bool:
617      Width = Target.getBoolWidth();
618      Align = Target.getBoolAlign();
619      break;
620    case BuiltinType::Char_S:
621    case BuiltinType::Char_U:
622    case BuiltinType::UChar:
623    case BuiltinType::SChar:
624      Width = Target.getCharWidth();
625      Align = Target.getCharAlign();
626      break;
627    case BuiltinType::WChar:
628      Width = Target.getWCharWidth();
629      Align = Target.getWCharAlign();
630      break;
631    case BuiltinType::Char16:
632      Width = Target.getChar16Width();
633      Align = Target.getChar16Align();
634      break;
635    case BuiltinType::Char32:
636      Width = Target.getChar32Width();
637      Align = Target.getChar32Align();
638      break;
639    case BuiltinType::UShort:
640    case BuiltinType::Short:
641      Width = Target.getShortWidth();
642      Align = Target.getShortAlign();
643      break;
644    case BuiltinType::UInt:
645    case BuiltinType::Int:
646      Width = Target.getIntWidth();
647      Align = Target.getIntAlign();
648      break;
649    case BuiltinType::ULong:
650    case BuiltinType::Long:
651      Width = Target.getLongWidth();
652      Align = Target.getLongAlign();
653      break;
654    case BuiltinType::ULongLong:
655    case BuiltinType::LongLong:
656      Width = Target.getLongLongWidth();
657      Align = Target.getLongLongAlign();
658      break;
659    case BuiltinType::Int128:
660    case BuiltinType::UInt128:
661      Width = 128;
662      Align = 128; // int128_t is 128-bit aligned on all targets.
663      break;
664    case BuiltinType::Float:
665      Width = Target.getFloatWidth();
666      Align = Target.getFloatAlign();
667      break;
668    case BuiltinType::Double:
669      Width = Target.getDoubleWidth();
670      Align = Target.getDoubleAlign();
671      break;
672    case BuiltinType::LongDouble:
673      Width = Target.getLongDoubleWidth();
674      Align = Target.getLongDoubleAlign();
675      break;
676    case BuiltinType::NullPtr:
677      Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
678      Align = Target.getPointerAlign(0); //   == sizeof(void*)
679      break;
680    }
681    break;
682  case Type::ObjCObjectPointer:
683    Width = Target.getPointerWidth(0);
684    Align = Target.getPointerAlign(0);
685    break;
686  case Type::BlockPointer: {
687    unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace();
688    Width = Target.getPointerWidth(AS);
689    Align = Target.getPointerAlign(AS);
690    break;
691  }
692  case Type::LValueReference:
693  case Type::RValueReference: {
694    // alignof and sizeof should never enter this code path here, so we go
695    // the pointer route.
696    unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace();
697    Width = Target.getPointerWidth(AS);
698    Align = Target.getPointerAlign(AS);
699    break;
700  }
701  case Type::Pointer: {
702    unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace();
703    Width = Target.getPointerWidth(AS);
704    Align = Target.getPointerAlign(AS);
705    break;
706  }
707  case Type::MemberPointer: {
708    QualType Pointee = cast<MemberPointerType>(T)->getPointeeType();
709    std::pair<uint64_t, unsigned> PtrDiffInfo =
710      getTypeInfo(getPointerDiffType());
711    Width = PtrDiffInfo.first;
712    if (Pointee->isFunctionType())
713      Width *= 2;
714    Align = PtrDiffInfo.second;
715    break;
716  }
717  case Type::Complex: {
718    // Complex types have the same alignment as their elements, but twice the
719    // size.
720    std::pair<uint64_t, unsigned> EltInfo =
721      getTypeInfo(cast<ComplexType>(T)->getElementType());
722    Width = EltInfo.first*2;
723    Align = EltInfo.second;
724    break;
725  }
726  case Type::ObjCObject:
727    return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
728  case Type::ObjCInterface: {
729    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
730    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
731    Width = Layout.getSize();
732    Align = Layout.getAlignment();
733    break;
734  }
735  case Type::Record:
736  case Type::Enum: {
737    const TagType *TT = cast<TagType>(T);
738
739    if (TT->getDecl()->isInvalidDecl()) {
740      Width = 1;
741      Align = 1;
742      break;
743    }
744
745    if (const EnumType *ET = dyn_cast<EnumType>(TT))
746      return getTypeInfo(ET->getDecl()->getIntegerType());
747
748    const RecordType *RT = cast<RecordType>(TT);
749    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
750    Width = Layout.getSize();
751    Align = Layout.getAlignment();
752    break;
753  }
754
755  case Type::SubstTemplateTypeParm:
756    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
757                       getReplacementType().getTypePtr());
758
759  case Type::Typedef: {
760    const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl();
761    if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) {
762      Align = std::max(Aligned->getMaxAlignment(),
763                       getTypeAlign(Typedef->getUnderlyingType().getTypePtr()));
764      Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr());
765    } else
766      return getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
767    break;
768  }
769
770  case Type::TypeOfExpr:
771    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
772                         .getTypePtr());
773
774  case Type::TypeOf:
775    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
776
777  case Type::Decltype:
778    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
779                        .getTypePtr());
780
781  case Type::Elaborated:
782    return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
783
784  case Type::TemplateSpecialization:
785    assert(getCanonicalType(T) != T &&
786           "Cannot request the size of a dependent type");
787    // FIXME: this is likely to be wrong once we support template
788    // aliases, since a template alias could refer to a typedef that
789    // has an __aligned__ attribute on it.
790    return getTypeInfo(getCanonicalType(T));
791  }
792
793  assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2");
794  return std::make_pair(Width, Align);
795}
796
797/// getTypeSizeInChars - Return the size of the specified type, in characters.
798/// This method does not work on incomplete types.
799CharUnits ASTContext::getTypeSizeInChars(QualType T) {
800  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
801}
802CharUnits ASTContext::getTypeSizeInChars(const Type *T) {
803  return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth());
804}
805
806/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
807/// characters. This method does not work on incomplete types.
808CharUnits ASTContext::getTypeAlignInChars(QualType T) {
809  return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
810}
811CharUnits ASTContext::getTypeAlignInChars(const Type *T) {
812  return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth());
813}
814
815/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
816/// type for the current target in bits.  This can be different than the ABI
817/// alignment in cases where it is beneficial for performance to overalign
818/// a data type.
819unsigned ASTContext::getPreferredTypeAlign(const Type *T) {
820  unsigned ABIAlign = getTypeAlign(T);
821
822  // Double and long long should be naturally aligned if possible.
823  if (const ComplexType* CT = T->getAs<ComplexType>())
824    T = CT->getElementType().getTypePtr();
825  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
826      T->isSpecificBuiltinType(BuiltinType::LongLong))
827    return std::max(ABIAlign, (unsigned)getTypeSize(T));
828
829  return ABIAlign;
830}
831
832static void CollectLocalObjCIvars(ASTContext *Ctx,
833                                  const ObjCInterfaceDecl *OI,
834                                  llvm::SmallVectorImpl<FieldDecl*> &Fields) {
835  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
836       E = OI->ivar_end(); I != E; ++I) {
837    ObjCIvarDecl *IVDecl = *I;
838    if (!IVDecl->isInvalidDecl())
839      Fields.push_back(cast<FieldDecl>(IVDecl));
840  }
841}
842
843void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI,
844                             llvm::SmallVectorImpl<FieldDecl*> &Fields) {
845  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
846    CollectObjCIvars(SuperClass, Fields);
847  CollectLocalObjCIvars(this, OI, Fields);
848}
849
850/// ShallowCollectObjCIvars -
851/// Collect all ivars, including those synthesized, in the current class.
852///
853void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI,
854                                 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
855  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
856         E = OI->ivar_end(); I != E; ++I) {
857     Ivars.push_back(*I);
858  }
859
860  CollectNonClassIvars(OI, Ivars);
861}
862
863/// CollectNonClassIvars -
864/// This routine collects all other ivars which are not declared in the class.
865/// This includes synthesized ivars (via @synthesize) and those in
866//  class's @implementation.
867///
868void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI,
869                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
870  // Find ivars declared in class extension.
871  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
872       CDecl = CDecl->getNextClassExtension()) {
873    for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
874         E = CDecl->ivar_end(); I != E; ++I) {
875      Ivars.push_back(*I);
876    }
877  }
878
879  // Also add any ivar defined in this class's implementation.  This
880  // includes synthesized ivars.
881  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
882    for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
883         E = ImplDecl->ivar_end(); I != E; ++I)
884      Ivars.push_back(*I);
885  }
886}
887
888/// CollectInheritedProtocols - Collect all protocols in current class and
889/// those inherited by it.
890void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
891                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
892  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
893    for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(),
894         PE = OI->protocol_end(); P != PE; ++P) {
895      ObjCProtocolDecl *Proto = (*P);
896      Protocols.insert(Proto);
897      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
898           PE = Proto->protocol_end(); P != PE; ++P) {
899        Protocols.insert(*P);
900        CollectInheritedProtocols(*P, Protocols);
901      }
902    }
903
904    // Categories of this Interface.
905    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
906         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
907      CollectInheritedProtocols(CDeclChain, Protocols);
908    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
909      while (SD) {
910        CollectInheritedProtocols(SD, Protocols);
911        SD = SD->getSuperClass();
912      }
913  } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
914    for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(),
915         PE = OC->protocol_end(); P != PE; ++P) {
916      ObjCProtocolDecl *Proto = (*P);
917      Protocols.insert(Proto);
918      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
919           PE = Proto->protocol_end(); P != PE; ++P)
920        CollectInheritedProtocols(*P, Protocols);
921    }
922  } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
923    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
924         PE = OP->protocol_end(); P != PE; ++P) {
925      ObjCProtocolDecl *Proto = (*P);
926      Protocols.insert(Proto);
927      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
928           PE = Proto->protocol_end(); P != PE; ++P)
929        CollectInheritedProtocols(*P, Protocols);
930    }
931  }
932}
933
934unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) {
935  unsigned count = 0;
936  // Count ivars declared in class extension.
937  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
938       CDecl = CDecl->getNextClassExtension())
939    count += CDecl->ivar_size();
940
941  // Count ivar defined in this class's implementation.  This
942  // includes synthesized ivars.
943  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
944    count += ImplDecl->ivar_size();
945
946  return count;
947}
948
949/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
950ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
951  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
952    I = ObjCImpls.find(D);
953  if (I != ObjCImpls.end())
954    return cast<ObjCImplementationDecl>(I->second);
955  return 0;
956}
957/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
958ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
959  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
960    I = ObjCImpls.find(D);
961  if (I != ObjCImpls.end())
962    return cast<ObjCCategoryImplDecl>(I->second);
963  return 0;
964}
965
966/// \brief Set the implementation of ObjCInterfaceDecl.
967void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
968                           ObjCImplementationDecl *ImplD) {
969  assert(IFaceD && ImplD && "Passed null params");
970  ObjCImpls[IFaceD] = ImplD;
971}
972/// \brief Set the implementation of ObjCCategoryDecl.
973void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
974                           ObjCCategoryImplDecl *ImplD) {
975  assert(CatD && ImplD && "Passed null params");
976  ObjCImpls[CatD] = ImplD;
977}
978
979/// \brief Allocate an uninitialized TypeSourceInfo.
980///
981/// The caller should initialize the memory held by TypeSourceInfo using
982/// the TypeLoc wrappers.
983///
984/// \param T the type that will be the basis for type source info. This type
985/// should refer to how the declarator was written in source code, not to
986/// what type semantic analysis resolved the declarator to.
987TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
988                                                 unsigned DataSize) {
989  if (!DataSize)
990    DataSize = TypeLoc::getFullDataSizeForType(T);
991  else
992    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
993           "incorrect data size provided to CreateTypeSourceInfo!");
994
995  TypeSourceInfo *TInfo =
996    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
997  new (TInfo) TypeSourceInfo(T);
998  return TInfo;
999}
1000
1001TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1002                                                     SourceLocation L) {
1003  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1004  DI->getTypeLoc().initialize(L);
1005  return DI;
1006}
1007
1008const ASTRecordLayout &
1009ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) {
1010  return getObjCLayout(D, 0);
1011}
1012
1013const ASTRecordLayout &
1014ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) {
1015  return getObjCLayout(D->getClassInterface(), D);
1016}
1017
1018//===----------------------------------------------------------------------===//
1019//                   Type creation/memoization methods
1020//===----------------------------------------------------------------------===//
1021
1022QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) {
1023  unsigned Fast = Quals.getFastQualifiers();
1024  Quals.removeFastQualifiers();
1025
1026  // Check if we've already instantiated this type.
1027  llvm::FoldingSetNodeID ID;
1028  ExtQuals::Profile(ID, TypeNode, Quals);
1029  void *InsertPos = 0;
1030  if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) {
1031    assert(EQ->getQualifiers() == Quals);
1032    QualType T = QualType(EQ, Fast);
1033    return T;
1034  }
1035
1036  ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals);
1037  ExtQualNodes.InsertNode(New, InsertPos);
1038  QualType T = QualType(New, Fast);
1039  return T;
1040}
1041
1042QualType ASTContext::getVolatileType(QualType T) {
1043  QualType CanT = getCanonicalType(T);
1044  if (CanT.isVolatileQualified()) return T;
1045
1046  QualifierCollector Quals;
1047  const Type *TypeNode = Quals.strip(T);
1048  Quals.addVolatile();
1049
1050  return getExtQualType(TypeNode, Quals);
1051}
1052
1053QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) {
1054  QualType CanT = getCanonicalType(T);
1055  if (CanT.getAddressSpace() == AddressSpace)
1056    return T;
1057
1058  // If we are composing extended qualifiers together, merge together
1059  // into one ExtQuals node.
1060  QualifierCollector Quals;
1061  const Type *TypeNode = Quals.strip(T);
1062
1063  // If this type already has an address space specified, it cannot get
1064  // another one.
1065  assert(!Quals.hasAddressSpace() &&
1066         "Type cannot be in multiple addr spaces!");
1067  Quals.addAddressSpace(AddressSpace);
1068
1069  return getExtQualType(TypeNode, Quals);
1070}
1071
1072QualType ASTContext::getObjCGCQualType(QualType T,
1073                                       Qualifiers::GC GCAttr) {
1074  QualType CanT = getCanonicalType(T);
1075  if (CanT.getObjCGCAttr() == GCAttr)
1076    return T;
1077
1078  if (T->isPointerType()) {
1079    QualType Pointee = T->getAs<PointerType>()->getPointeeType();
1080    if (Pointee->isAnyPointerType()) {
1081      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1082      return getPointerType(ResultType);
1083    }
1084  }
1085
1086  // If we are composing extended qualifiers together, merge together
1087  // into one ExtQuals node.
1088  QualifierCollector Quals;
1089  const Type *TypeNode = Quals.strip(T);
1090
1091  // If this type already has an ObjCGC specified, it cannot get
1092  // another one.
1093  assert(!Quals.hasObjCGCAttr() &&
1094         "Type cannot have multiple ObjCGCs!");
1095  Quals.addObjCGCAttr(GCAttr);
1096
1097  return getExtQualType(TypeNode, Quals);
1098}
1099
1100static QualType getExtFunctionType(ASTContext& Context, QualType T,
1101                                        const FunctionType::ExtInfo &Info) {
1102  QualType ResultType;
1103  if (const PointerType *Pointer = T->getAs<PointerType>()) {
1104    QualType Pointee = Pointer->getPointeeType();
1105    ResultType = getExtFunctionType(Context, Pointee, Info);
1106    if (ResultType == Pointee)
1107      return T;
1108
1109    ResultType = Context.getPointerType(ResultType);
1110  } else if (const BlockPointerType *BlockPointer
1111                                              = T->getAs<BlockPointerType>()) {
1112    QualType Pointee = BlockPointer->getPointeeType();
1113    ResultType = getExtFunctionType(Context, Pointee, Info);
1114    if (ResultType == Pointee)
1115      return T;
1116
1117    ResultType = Context.getBlockPointerType(ResultType);
1118   } else if (const FunctionType *F = T->getAs<FunctionType>()) {
1119    if (F->getExtInfo() == Info)
1120      return T;
1121
1122    if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) {
1123      ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(),
1124                                                  Info);
1125    } else {
1126      const FunctionProtoType *FPT = cast<FunctionProtoType>(F);
1127      ResultType
1128        = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1129                                  FPT->getNumArgs(), FPT->isVariadic(),
1130                                  FPT->getTypeQuals(),
1131                                  FPT->hasExceptionSpec(),
1132                                  FPT->hasAnyExceptionSpec(),
1133                                  FPT->getNumExceptions(),
1134                                  FPT->exception_begin(),
1135                                  Info);
1136    }
1137  } else
1138    return T;
1139
1140  return Context.getQualifiedType(ResultType, T.getLocalQualifiers());
1141}
1142
1143QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) {
1144  FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1145  return getExtFunctionType(*this, T,
1146                                 Info.withNoReturn(AddNoReturn));
1147}
1148
1149QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) {
1150  FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1151  return getExtFunctionType(*this, T,
1152                            Info.withCallingConv(CallConv));
1153}
1154
1155QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) {
1156  FunctionType::ExtInfo Info = getFunctionExtInfo(T);
1157  return getExtFunctionType(*this, T,
1158                                 Info.withRegParm(RegParm));
1159}
1160
1161/// getComplexType - Return the uniqued reference to the type for a complex
1162/// number with the specified element type.
1163QualType ASTContext::getComplexType(QualType T) {
1164  // Unique pointers, to guarantee there is only one pointer of a particular
1165  // structure.
1166  llvm::FoldingSetNodeID ID;
1167  ComplexType::Profile(ID, T);
1168
1169  void *InsertPos = 0;
1170  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1171    return QualType(CT, 0);
1172
1173  // If the pointee type isn't canonical, this won't be a canonical type either,
1174  // so fill in the canonical type field.
1175  QualType Canonical;
1176  if (!T.isCanonical()) {
1177    Canonical = getComplexType(getCanonicalType(T));
1178
1179    // Get the new insert position for the node we care about.
1180    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1181    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1182  }
1183  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1184  Types.push_back(New);
1185  ComplexTypes.InsertNode(New, InsertPos);
1186  return QualType(New, 0);
1187}
1188
1189/// getPointerType - Return the uniqued reference to the type for a pointer to
1190/// the specified type.
1191QualType ASTContext::getPointerType(QualType T) {
1192  // Unique pointers, to guarantee there is only one pointer of a particular
1193  // structure.
1194  llvm::FoldingSetNodeID ID;
1195  PointerType::Profile(ID, T);
1196
1197  void *InsertPos = 0;
1198  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1199    return QualType(PT, 0);
1200
1201  // If the pointee 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 (!T.isCanonical()) {
1205    Canonical = getPointerType(getCanonicalType(T));
1206
1207    // Get the new insert position for the node we care about.
1208    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1209    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1210  }
1211  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1212  Types.push_back(New);
1213  PointerTypes.InsertNode(New, InsertPos);
1214  return QualType(New, 0);
1215}
1216
1217/// getBlockPointerType - Return the uniqued reference to the type for
1218/// a pointer to the specified block.
1219QualType ASTContext::getBlockPointerType(QualType T) {
1220  assert(T->isFunctionType() && "block of function types only");
1221  // Unique pointers, to guarantee there is only one block of a particular
1222  // structure.
1223  llvm::FoldingSetNodeID ID;
1224  BlockPointerType::Profile(ID, T);
1225
1226  void *InsertPos = 0;
1227  if (BlockPointerType *PT =
1228        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1229    return QualType(PT, 0);
1230
1231  // If the block pointee type isn't canonical, this won't be a canonical
1232  // type either so fill in the canonical type field.
1233  QualType Canonical;
1234  if (!T.isCanonical()) {
1235    Canonical = getBlockPointerType(getCanonicalType(T));
1236
1237    // Get the new insert position for the node we care about.
1238    BlockPointerType *NewIP =
1239      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1240    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1241  }
1242  BlockPointerType *New
1243    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1244  Types.push_back(New);
1245  BlockPointerTypes.InsertNode(New, InsertPos);
1246  return QualType(New, 0);
1247}
1248
1249/// getLValueReferenceType - Return the uniqued reference to the type for an
1250/// lvalue reference to the specified type.
1251QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) {
1252  // Unique pointers, to guarantee there is only one pointer of a particular
1253  // structure.
1254  llvm::FoldingSetNodeID ID;
1255  ReferenceType::Profile(ID, T, SpelledAsLValue);
1256
1257  void *InsertPos = 0;
1258  if (LValueReferenceType *RT =
1259        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1260    return QualType(RT, 0);
1261
1262  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1263
1264  // If the referencee type isn't canonical, this won't be a canonical type
1265  // either, so fill in the canonical type field.
1266  QualType Canonical;
1267  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1268    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1269    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1270
1271    // Get the new insert position for the node we care about.
1272    LValueReferenceType *NewIP =
1273      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1274    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1275  }
1276
1277  LValueReferenceType *New
1278    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1279                                                     SpelledAsLValue);
1280  Types.push_back(New);
1281  LValueReferenceTypes.InsertNode(New, InsertPos);
1282
1283  return QualType(New, 0);
1284}
1285
1286/// getRValueReferenceType - Return the uniqued reference to the type for an
1287/// rvalue reference to the specified type.
1288QualType ASTContext::getRValueReferenceType(QualType T) {
1289  // Unique pointers, to guarantee there is only one pointer of a particular
1290  // structure.
1291  llvm::FoldingSetNodeID ID;
1292  ReferenceType::Profile(ID, T, false);
1293
1294  void *InsertPos = 0;
1295  if (RValueReferenceType *RT =
1296        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1297    return QualType(RT, 0);
1298
1299  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1300
1301  // If the referencee type isn't canonical, this won't be a canonical type
1302  // either, so fill in the canonical type field.
1303  QualType Canonical;
1304  if (InnerRef || !T.isCanonical()) {
1305    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1306    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1307
1308    // Get the new insert position for the node we care about.
1309    RValueReferenceType *NewIP =
1310      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1311    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1312  }
1313
1314  RValueReferenceType *New
1315    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1316  Types.push_back(New);
1317  RValueReferenceTypes.InsertNode(New, InsertPos);
1318  return QualType(New, 0);
1319}
1320
1321/// getMemberPointerType - Return the uniqued reference to the type for a
1322/// member pointer to the specified type, in the specified class.
1323QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) {
1324  // Unique pointers, to guarantee there is only one pointer of a particular
1325  // structure.
1326  llvm::FoldingSetNodeID ID;
1327  MemberPointerType::Profile(ID, T, Cls);
1328
1329  void *InsertPos = 0;
1330  if (MemberPointerType *PT =
1331      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1332    return QualType(PT, 0);
1333
1334  // If the pointee or class type isn't canonical, this won't be a canonical
1335  // type either, so fill in the canonical type field.
1336  QualType Canonical;
1337  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1338    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1339
1340    // Get the new insert position for the node we care about.
1341    MemberPointerType *NewIP =
1342      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1343    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1344  }
1345  MemberPointerType *New
1346    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1347  Types.push_back(New);
1348  MemberPointerTypes.InsertNode(New, InsertPos);
1349  return QualType(New, 0);
1350}
1351
1352/// getConstantArrayType - Return the unique reference to the type for an
1353/// array of the specified element type.
1354QualType ASTContext::getConstantArrayType(QualType EltTy,
1355                                          const llvm::APInt &ArySizeIn,
1356                                          ArrayType::ArraySizeModifier ASM,
1357                                          unsigned EltTypeQuals) {
1358  assert((EltTy->isDependentType() ||
1359          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1360         "Constant array of VLAs is illegal!");
1361
1362  // Convert the array size into a canonical width matching the pointer size for
1363  // the target.
1364  llvm::APInt ArySize(ArySizeIn);
1365  ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace()));
1366
1367  llvm::FoldingSetNodeID ID;
1368  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals);
1369
1370  void *InsertPos = 0;
1371  if (ConstantArrayType *ATP =
1372      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1373    return QualType(ATP, 0);
1374
1375  // If the element type isn't canonical, this won't be a canonical type either,
1376  // so fill in the canonical type field.
1377  QualType Canonical;
1378  if (!EltTy.isCanonical()) {
1379    Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize,
1380                                     ASM, EltTypeQuals);
1381    // Get the new insert position for the node we care about.
1382    ConstantArrayType *NewIP =
1383      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1384    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1385  }
1386
1387  ConstantArrayType *New = new(*this,TypeAlignment)
1388    ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals);
1389  ConstantArrayTypes.InsertNode(New, InsertPos);
1390  Types.push_back(New);
1391  return QualType(New, 0);
1392}
1393
1394/// getVariableArrayType - Returns a non-unique reference to the type for a
1395/// variable array of the specified element type.
1396QualType ASTContext::getVariableArrayType(QualType EltTy,
1397                                          Expr *NumElts,
1398                                          ArrayType::ArraySizeModifier ASM,
1399                                          unsigned EltTypeQuals,
1400                                          SourceRange Brackets) {
1401  // Since we don't unique expressions, it isn't possible to unique VLA's
1402  // that have an expression provided for their size.
1403  QualType CanonType;
1404
1405  if (!EltTy.isCanonical()) {
1406    if (NumElts)
1407      NumElts->Retain();
1408    CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM,
1409                                     EltTypeQuals, Brackets);
1410  }
1411
1412  VariableArrayType *New = new(*this, TypeAlignment)
1413    VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets);
1414
1415  VariableArrayTypes.push_back(New);
1416  Types.push_back(New);
1417  return QualType(New, 0);
1418}
1419
1420/// getDependentSizedArrayType - Returns a non-unique reference to
1421/// the type for a dependently-sized array of the specified element
1422/// type.
1423QualType ASTContext::getDependentSizedArrayType(QualType EltTy,
1424                                                Expr *NumElts,
1425                                                ArrayType::ArraySizeModifier ASM,
1426                                                unsigned EltTypeQuals,
1427                                                SourceRange Brackets) {
1428  assert((!NumElts || NumElts->isTypeDependent() ||
1429          NumElts->isValueDependent()) &&
1430         "Size must be type- or value-dependent!");
1431
1432  void *InsertPos = 0;
1433  DependentSizedArrayType *Canon = 0;
1434  llvm::FoldingSetNodeID ID;
1435
1436  if (NumElts) {
1437    // Dependently-sized array types that do not have a specified
1438    // number of elements will have their sizes deduced from an
1439    // initializer.
1440    DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM,
1441                                     EltTypeQuals, NumElts);
1442
1443    Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1444  }
1445
1446  DependentSizedArrayType *New;
1447  if (Canon) {
1448    // We already have a canonical version of this array type; use it as
1449    // the canonical type for a newly-built type.
1450    New = new (*this, TypeAlignment)
1451      DependentSizedArrayType(*this, EltTy, QualType(Canon, 0),
1452                              NumElts, ASM, EltTypeQuals, Brackets);
1453  } else {
1454    QualType CanonEltTy = getCanonicalType(EltTy);
1455    if (CanonEltTy == EltTy) {
1456      New = new (*this, TypeAlignment)
1457        DependentSizedArrayType(*this, EltTy, QualType(),
1458                                NumElts, ASM, EltTypeQuals, Brackets);
1459
1460      if (NumElts) {
1461        DependentSizedArrayType *CanonCheck
1462          = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1463        assert(!CanonCheck && "Dependent-sized canonical array type broken");
1464        (void)CanonCheck;
1465        DependentSizedArrayTypes.InsertNode(New, InsertPos);
1466      }
1467    } else {
1468      QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts,
1469                                                  ASM, EltTypeQuals,
1470                                                  SourceRange());
1471      New = new (*this, TypeAlignment)
1472        DependentSizedArrayType(*this, EltTy, Canon,
1473                                NumElts, ASM, EltTypeQuals, Brackets);
1474    }
1475  }
1476
1477  Types.push_back(New);
1478  return QualType(New, 0);
1479}
1480
1481QualType ASTContext::getIncompleteArrayType(QualType EltTy,
1482                                            ArrayType::ArraySizeModifier ASM,
1483                                            unsigned EltTypeQuals) {
1484  llvm::FoldingSetNodeID ID;
1485  IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals);
1486
1487  void *InsertPos = 0;
1488  if (IncompleteArrayType *ATP =
1489       IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1490    return QualType(ATP, 0);
1491
1492  // If the element type isn't canonical, this won't be a canonical type
1493  // either, so fill in the canonical type field.
1494  QualType Canonical;
1495
1496  if (!EltTy.isCanonical()) {
1497    Canonical = getIncompleteArrayType(getCanonicalType(EltTy),
1498                                       ASM, EltTypeQuals);
1499
1500    // Get the new insert position for the node we care about.
1501    IncompleteArrayType *NewIP =
1502      IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1503    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1504  }
1505
1506  IncompleteArrayType *New = new (*this, TypeAlignment)
1507    IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals);
1508
1509  IncompleteArrayTypes.InsertNode(New, InsertPos);
1510  Types.push_back(New);
1511  return QualType(New, 0);
1512}
1513
1514/// getVectorType - Return the unique reference to a vector type of
1515/// the specified element type and size. VectorType must be a built-in type.
1516QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
1517                                   bool IsAltiVec, bool IsPixel) {
1518  BuiltinType *baseType;
1519
1520  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1521  assert(baseType != 0 && "getVectorType(): Expecting a built-in type");
1522
1523  // Check if we've already instantiated a vector of this type.
1524  llvm::FoldingSetNodeID ID;
1525  VectorType::Profile(ID, vecType, NumElts, Type::Vector,
1526    IsAltiVec, IsPixel);
1527  void *InsertPos = 0;
1528  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1529    return QualType(VTP, 0);
1530
1531  // If the element type isn't canonical, this won't be a canonical type either,
1532  // so fill in the canonical type field.
1533  QualType Canonical;
1534  if (!vecType.isCanonical() || IsAltiVec || IsPixel) {
1535    Canonical = getVectorType(getCanonicalType(vecType),
1536      NumElts, false, false);
1537
1538    // Get the new insert position for the node we care about.
1539    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1540    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1541  }
1542  VectorType *New = new (*this, TypeAlignment)
1543    VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel);
1544  VectorTypes.InsertNode(New, InsertPos);
1545  Types.push_back(New);
1546  return QualType(New, 0);
1547}
1548
1549/// getExtVectorType - Return the unique reference to an extended vector type of
1550/// the specified element type and size. VectorType must be a built-in type.
1551QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) {
1552  BuiltinType *baseType;
1553
1554  baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr());
1555  assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type");
1556
1557  // Check if we've already instantiated a vector of this type.
1558  llvm::FoldingSetNodeID ID;
1559  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false);
1560  void *InsertPos = 0;
1561  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
1562    return QualType(VTP, 0);
1563
1564  // If the element type isn't canonical, this won't be a canonical type either,
1565  // so fill in the canonical type field.
1566  QualType Canonical;
1567  if (!vecType.isCanonical()) {
1568    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
1569
1570    // Get the new insert position for the node we care about.
1571    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1572    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1573  }
1574  ExtVectorType *New = new (*this, TypeAlignment)
1575    ExtVectorType(vecType, NumElts, Canonical);
1576  VectorTypes.InsertNode(New, InsertPos);
1577  Types.push_back(New);
1578  return QualType(New, 0);
1579}
1580
1581QualType ASTContext::getDependentSizedExtVectorType(QualType vecType,
1582                                                    Expr *SizeExpr,
1583                                                    SourceLocation AttrLoc) {
1584  llvm::FoldingSetNodeID ID;
1585  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
1586                                       SizeExpr);
1587
1588  void *InsertPos = 0;
1589  DependentSizedExtVectorType *Canon
1590    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1591  DependentSizedExtVectorType *New;
1592  if (Canon) {
1593    // We already have a canonical version of this array type; use it as
1594    // the canonical type for a newly-built type.
1595    New = new (*this, TypeAlignment)
1596      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
1597                                  SizeExpr, AttrLoc);
1598  } else {
1599    QualType CanonVecTy = getCanonicalType(vecType);
1600    if (CanonVecTy == vecType) {
1601      New = new (*this, TypeAlignment)
1602        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
1603                                    AttrLoc);
1604
1605      DependentSizedExtVectorType *CanonCheck
1606        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
1607      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
1608      (void)CanonCheck;
1609      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
1610    } else {
1611      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
1612                                                      SourceLocation());
1613      New = new (*this, TypeAlignment)
1614        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
1615    }
1616  }
1617
1618  Types.push_back(New);
1619  return QualType(New, 0);
1620}
1621
1622/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
1623///
1624QualType ASTContext::getFunctionNoProtoType(QualType ResultTy,
1625                                            const FunctionType::ExtInfo &Info) {
1626  const CallingConv CallConv = Info.getCC();
1627  // Unique functions, to guarantee there is only one function of a particular
1628  // structure.
1629  llvm::FoldingSetNodeID ID;
1630  FunctionNoProtoType::Profile(ID, ResultTy, Info);
1631
1632  void *InsertPos = 0;
1633  if (FunctionNoProtoType *FT =
1634        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1635    return QualType(FT, 0);
1636
1637  QualType Canonical;
1638  if (!ResultTy.isCanonical() ||
1639      getCanonicalCallConv(CallConv) != CallConv) {
1640    Canonical =
1641      getFunctionNoProtoType(getCanonicalType(ResultTy),
1642                     Info.withCallingConv(getCanonicalCallConv(CallConv)));
1643
1644    // Get the new insert position for the node we care about.
1645    FunctionNoProtoType *NewIP =
1646      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1647    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1648  }
1649
1650  FunctionNoProtoType *New = new (*this, TypeAlignment)
1651    FunctionNoProtoType(ResultTy, Canonical, Info);
1652  Types.push_back(New);
1653  FunctionNoProtoTypes.InsertNode(New, InsertPos);
1654  return QualType(New, 0);
1655}
1656
1657/// getFunctionType - Return a normal function type with a typed argument
1658/// list.  isVariadic indicates whether the argument list includes '...'.
1659QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray,
1660                                     unsigned NumArgs, bool isVariadic,
1661                                     unsigned TypeQuals, bool hasExceptionSpec,
1662                                     bool hasAnyExceptionSpec, unsigned NumExs,
1663                                     const QualType *ExArray,
1664                                     const FunctionType::ExtInfo &Info) {
1665  const CallingConv CallConv= Info.getCC();
1666  // Unique functions, to guarantee there is only one function of a particular
1667  // structure.
1668  llvm::FoldingSetNodeID ID;
1669  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic,
1670                             TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1671                             NumExs, ExArray, Info);
1672
1673  void *InsertPos = 0;
1674  if (FunctionProtoType *FTP =
1675        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
1676    return QualType(FTP, 0);
1677
1678  // Determine whether the type being created is already canonical or not.
1679  bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical();
1680  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
1681    if (!ArgArray[i].isCanonicalAsParam())
1682      isCanonical = false;
1683
1684  // If this type isn't canonical, get the canonical version of it.
1685  // The exception spec is not part of the canonical type.
1686  QualType Canonical;
1687  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
1688    llvm::SmallVector<QualType, 16> CanonicalArgs;
1689    CanonicalArgs.reserve(NumArgs);
1690    for (unsigned i = 0; i != NumArgs; ++i)
1691      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
1692
1693    Canonical = getFunctionType(getCanonicalType(ResultTy),
1694                                CanonicalArgs.data(), NumArgs,
1695                                isVariadic, TypeQuals, false,
1696                                false, 0, 0,
1697                     Info.withCallingConv(getCanonicalCallConv(CallConv)));
1698
1699    // Get the new insert position for the node we care about.
1700    FunctionProtoType *NewIP =
1701      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
1702    assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP;
1703  }
1704
1705  // FunctionProtoType objects are allocated with extra bytes after them
1706  // for two variable size arrays (for parameter and exception types) at the
1707  // end of them.
1708  FunctionProtoType *FTP =
1709    (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) +
1710                                 NumArgs*sizeof(QualType) +
1711                                 NumExs*sizeof(QualType), TypeAlignment);
1712  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic,
1713                              TypeQuals, hasExceptionSpec, hasAnyExceptionSpec,
1714                              ExArray, NumExs, Canonical, Info);
1715  Types.push_back(FTP);
1716  FunctionProtoTypes.InsertNode(FTP, InsertPos);
1717  return QualType(FTP, 0);
1718}
1719
1720#ifndef NDEBUG
1721static bool NeedsInjectedClassNameType(const RecordDecl *D) {
1722  if (!isa<CXXRecordDecl>(D)) return false;
1723  const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
1724  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
1725    return true;
1726  if (RD->getDescribedClassTemplate() &&
1727      !isa<ClassTemplateSpecializationDecl>(RD))
1728    return true;
1729  return false;
1730}
1731#endif
1732
1733/// getInjectedClassNameType - Return the unique reference to the
1734/// injected class name type for the specified templated declaration.
1735QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
1736                                              QualType TST) {
1737  assert(NeedsInjectedClassNameType(Decl));
1738  if (Decl->TypeForDecl) {
1739    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1740  } else if (CXXRecordDecl *PrevDecl
1741               = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) {
1742    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
1743    Decl->TypeForDecl = PrevDecl->TypeForDecl;
1744    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
1745  } else {
1746    Decl->TypeForDecl =
1747      new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
1748    Types.push_back(Decl->TypeForDecl);
1749  }
1750  return QualType(Decl->TypeForDecl, 0);
1751}
1752
1753/// getTypeDeclType - Return the unique reference to the type for the
1754/// specified type declaration.
1755QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) {
1756  assert(Decl && "Passed null for Decl param");
1757  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
1758
1759  if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl))
1760    return getTypedefType(Typedef);
1761
1762  assert(!isa<TemplateTypeParmDecl>(Decl) &&
1763         "Template type parameter types are always available.");
1764
1765  if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
1766    assert(!Record->getPreviousDeclaration() &&
1767           "struct/union has previous declaration");
1768    assert(!NeedsInjectedClassNameType(Record));
1769    Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record);
1770  } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
1771    assert(!Enum->getPreviousDeclaration() &&
1772           "enum has previous declaration");
1773    Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum);
1774  } else if (const UnresolvedUsingTypenameDecl *Using =
1775               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
1776    Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using);
1777  } else
1778    llvm_unreachable("TypeDecl without a type?");
1779
1780  Types.push_back(Decl->TypeForDecl);
1781  return QualType(Decl->TypeForDecl, 0);
1782}
1783
1784/// getTypedefType - Return the unique reference to the type for the
1785/// specified typename decl.
1786QualType ASTContext::getTypedefType(const TypedefDecl *Decl) {
1787  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
1788
1789  QualType Canonical = getCanonicalType(Decl->getUnderlyingType());
1790  Decl->TypeForDecl = new(*this, TypeAlignment)
1791    TypedefType(Type::Typedef, Decl, Canonical);
1792  Types.push_back(Decl->TypeForDecl);
1793  return QualType(Decl->TypeForDecl, 0);
1794}
1795
1796/// \brief Retrieve a substitution-result type.
1797QualType
1798ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
1799                                         QualType Replacement) {
1800  assert(Replacement.isCanonical()
1801         && "replacement types must always be canonical");
1802
1803  llvm::FoldingSetNodeID ID;
1804  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
1805  void *InsertPos = 0;
1806  SubstTemplateTypeParmType *SubstParm
1807    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1808
1809  if (!SubstParm) {
1810    SubstParm = new (*this, TypeAlignment)
1811      SubstTemplateTypeParmType(Parm, Replacement);
1812    Types.push_back(SubstParm);
1813    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
1814  }
1815
1816  return QualType(SubstParm, 0);
1817}
1818
1819/// \brief Retrieve the template type parameter type for a template
1820/// parameter or parameter pack with the given depth, index, and (optionally)
1821/// name.
1822QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
1823                                             bool ParameterPack,
1824                                             IdentifierInfo *Name) {
1825  llvm::FoldingSetNodeID ID;
1826  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name);
1827  void *InsertPos = 0;
1828  TemplateTypeParmType *TypeParm
1829    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1830
1831  if (TypeParm)
1832    return QualType(TypeParm, 0);
1833
1834  if (Name) {
1835    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
1836    TypeParm = new (*this, TypeAlignment)
1837      TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon);
1838
1839    TemplateTypeParmType *TypeCheck
1840      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
1841    assert(!TypeCheck && "Template type parameter canonical type broken");
1842    (void)TypeCheck;
1843  } else
1844    TypeParm = new (*this, TypeAlignment)
1845      TemplateTypeParmType(Depth, Index, ParameterPack);
1846
1847  Types.push_back(TypeParm);
1848  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
1849
1850  return QualType(TypeParm, 0);
1851}
1852
1853TypeSourceInfo *
1854ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
1855                                              SourceLocation NameLoc,
1856                                        const TemplateArgumentListInfo &Args,
1857                                              QualType CanonType) {
1858  QualType TST = getTemplateSpecializationType(Name, Args, CanonType);
1859
1860  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
1861  TemplateSpecializationTypeLoc TL
1862    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
1863  TL.setTemplateNameLoc(NameLoc);
1864  TL.setLAngleLoc(Args.getLAngleLoc());
1865  TL.setRAngleLoc(Args.getRAngleLoc());
1866  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
1867    TL.setArgLocInfo(i, Args[i].getLocInfo());
1868  return DI;
1869}
1870
1871QualType
1872ASTContext::getTemplateSpecializationType(TemplateName Template,
1873                                          const TemplateArgumentListInfo &Args,
1874                                          QualType Canon) {
1875  unsigned NumArgs = Args.size();
1876
1877  llvm::SmallVector<TemplateArgument, 4> ArgVec;
1878  ArgVec.reserve(NumArgs);
1879  for (unsigned i = 0; i != NumArgs; ++i)
1880    ArgVec.push_back(Args[i].getArgument());
1881
1882  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
1883                                       Canon);
1884}
1885
1886QualType
1887ASTContext::getTemplateSpecializationType(TemplateName Template,
1888                                          const TemplateArgument *Args,
1889                                          unsigned NumArgs,
1890                                          QualType Canon) {
1891  if (!Canon.isNull())
1892    Canon = getCanonicalType(Canon);
1893  else {
1894    // Build the canonical template specialization type.
1895    TemplateName CanonTemplate = getCanonicalTemplateName(Template);
1896    llvm::SmallVector<TemplateArgument, 4> CanonArgs;
1897    CanonArgs.reserve(NumArgs);
1898    for (unsigned I = 0; I != NumArgs; ++I)
1899      CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
1900
1901    // Determine whether this canonical template specialization type already
1902    // exists.
1903    llvm::FoldingSetNodeID ID;
1904    TemplateSpecializationType::Profile(ID, CanonTemplate,
1905                                        CanonArgs.data(), NumArgs, *this);
1906
1907    void *InsertPos = 0;
1908    TemplateSpecializationType *Spec
1909      = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
1910
1911    if (!Spec) {
1912      // Allocate a new canonical template specialization type.
1913      void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1914                            sizeof(TemplateArgument) * NumArgs),
1915                           TypeAlignment);
1916      Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
1917                                                  CanonArgs.data(), NumArgs,
1918                                                  Canon);
1919      Types.push_back(Spec);
1920      TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
1921    }
1922
1923    if (Canon.isNull())
1924      Canon = QualType(Spec, 0);
1925    assert(Canon->isDependentType() &&
1926           "Non-dependent template-id type must have a canonical type");
1927  }
1928
1929  // Allocate the (non-canonical) template specialization type, but don't
1930  // try to unique it: these types typically have location information that
1931  // we don't unique and don't want to lose.
1932  void *Mem = Allocate((sizeof(TemplateSpecializationType) +
1933                        sizeof(TemplateArgument) * NumArgs),
1934                       TypeAlignment);
1935  TemplateSpecializationType *Spec
1936    = new (Mem) TemplateSpecializationType(Template,
1937                                           Args, NumArgs,
1938                                           Canon);
1939
1940  Types.push_back(Spec);
1941  return QualType(Spec, 0);
1942}
1943
1944QualType
1945ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
1946                              NestedNameSpecifier *NNS,
1947                              QualType NamedType) {
1948  llvm::FoldingSetNodeID ID;
1949  ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
1950
1951  void *InsertPos = 0;
1952  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1953  if (T)
1954    return QualType(T, 0);
1955
1956  QualType Canon = NamedType;
1957  if (!Canon.isCanonical()) {
1958    Canon = getCanonicalType(NamedType);
1959    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
1960    assert(!CheckT && "Elaborated canonical type broken");
1961    (void)CheckT;
1962  }
1963
1964  T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
1965  Types.push_back(T);
1966  ElaboratedTypes.InsertNode(T, InsertPos);
1967  return QualType(T, 0);
1968}
1969
1970QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
1971                                          NestedNameSpecifier *NNS,
1972                                          const IdentifierInfo *Name,
1973                                          QualType Canon) {
1974  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
1975
1976  if (Canon.isNull()) {
1977    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
1978    ElaboratedTypeKeyword CanonKeyword = Keyword;
1979    if (Keyword == ETK_None)
1980      CanonKeyword = ETK_Typename;
1981
1982    if (CanonNNS != NNS || CanonKeyword != Keyword)
1983      Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
1984  }
1985
1986  llvm::FoldingSetNodeID ID;
1987  DependentNameType::Profile(ID, Keyword, NNS, Name);
1988
1989  void *InsertPos = 0;
1990  DependentNameType *T
1991    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
1992  if (T)
1993    return QualType(T, 0);
1994
1995  T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
1996  Types.push_back(T);
1997  DependentNameTypes.InsertNode(T, InsertPos);
1998  return QualType(T, 0);
1999}
2000
2001QualType
2002ASTContext::getDependentTemplateSpecializationType(
2003                                 ElaboratedTypeKeyword Keyword,
2004                                 NestedNameSpecifier *NNS,
2005                                 const IdentifierInfo *Name,
2006                                 const TemplateArgumentListInfo &Args) {
2007  // TODO: avoid this copy
2008  llvm::SmallVector<TemplateArgument, 16> ArgCopy;
2009  for (unsigned I = 0, E = Args.size(); I != E; ++I)
2010    ArgCopy.push_back(Args[I].getArgument());
2011  return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2012                                                ArgCopy.size(),
2013                                                ArgCopy.data());
2014}
2015
2016QualType
2017ASTContext::getDependentTemplateSpecializationType(
2018                                 ElaboratedTypeKeyword Keyword,
2019                                 NestedNameSpecifier *NNS,
2020                                 const IdentifierInfo *Name,
2021                                 unsigned NumArgs,
2022                                 const TemplateArgument *Args) {
2023  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2024
2025  llvm::FoldingSetNodeID ID;
2026  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2027                                               Name, NumArgs, Args);
2028
2029  void *InsertPos = 0;
2030  DependentTemplateSpecializationType *T
2031    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2032  if (T)
2033    return QualType(T, 0);
2034
2035  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2036
2037  ElaboratedTypeKeyword CanonKeyword = Keyword;
2038  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2039
2040  bool AnyNonCanonArgs = false;
2041  llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2042  for (unsigned I = 0; I != NumArgs; ++I) {
2043    CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2044    if (!CanonArgs[I].structurallyEquals(Args[I]))
2045      AnyNonCanonArgs = true;
2046  }
2047
2048  QualType Canon;
2049  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2050    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2051                                                   Name, NumArgs,
2052                                                   CanonArgs.data());
2053
2054    // Find the insert position again.
2055    DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2056  }
2057
2058  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2059                        sizeof(TemplateArgument) * NumArgs),
2060                       TypeAlignment);
2061  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2062                                                    Name, NumArgs, Args, Canon);
2063  Types.push_back(T);
2064  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2065  return QualType(T, 0);
2066}
2067
2068/// CmpProtocolNames - Comparison predicate for sorting protocols
2069/// alphabetically.
2070static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2071                            const ObjCProtocolDecl *RHS) {
2072  return LHS->getDeclName() < RHS->getDeclName();
2073}
2074
2075static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2076                                unsigned NumProtocols) {
2077  if (NumProtocols == 0) return true;
2078
2079  for (unsigned i = 1; i != NumProtocols; ++i)
2080    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]))
2081      return false;
2082  return true;
2083}
2084
2085static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2086                                   unsigned &NumProtocols) {
2087  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2088
2089  // Sort protocols, keyed by name.
2090  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2091
2092  // Remove duplicates.
2093  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2094  NumProtocols = ProtocolsEnd-Protocols;
2095}
2096
2097QualType ASTContext::getObjCObjectType(QualType BaseType,
2098                                       ObjCProtocolDecl * const *Protocols,
2099                                       unsigned NumProtocols) {
2100  // If the base type is an interface and there aren't any protocols
2101  // to add, then the interface type will do just fine.
2102  if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2103    return BaseType;
2104
2105  // Look in the folding set for an existing type.
2106  llvm::FoldingSetNodeID ID;
2107  ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2108  void *InsertPos = 0;
2109  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2110    return QualType(QT, 0);
2111
2112  // Build the canonical type, which has the canonical base type and
2113  // a sorted-and-uniqued list of protocols.
2114  QualType Canonical;
2115  bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2116  if (!ProtocolsSorted || !BaseType.isCanonical()) {
2117    if (!ProtocolsSorted) {
2118      llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2119                                                     Protocols + NumProtocols);
2120      unsigned UniqueCount = NumProtocols;
2121
2122      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2123      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2124                                    &Sorted[0], UniqueCount);
2125    } else {
2126      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2127                                    Protocols, NumProtocols);
2128    }
2129
2130    // Regenerate InsertPos.
2131    ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2132  }
2133
2134  unsigned Size = sizeof(ObjCObjectTypeImpl);
2135  Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2136  void *Mem = Allocate(Size, TypeAlignment);
2137  ObjCObjectTypeImpl *T =
2138    new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2139
2140  Types.push_back(T);
2141  ObjCObjectTypes.InsertNode(T, InsertPos);
2142  return QualType(T, 0);
2143}
2144
2145/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2146/// the given object type.
2147QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) {
2148  llvm::FoldingSetNodeID ID;
2149  ObjCObjectPointerType::Profile(ID, ObjectT);
2150
2151  void *InsertPos = 0;
2152  if (ObjCObjectPointerType *QT =
2153              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2154    return QualType(QT, 0);
2155
2156  // Find the canonical object type.
2157  QualType Canonical;
2158  if (!ObjectT.isCanonical()) {
2159    Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2160
2161    // Regenerate InsertPos.
2162    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2163  }
2164
2165  // No match.
2166  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2167  ObjCObjectPointerType *QType =
2168    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2169
2170  Types.push_back(QType);
2171  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2172  return QualType(QType, 0);
2173}
2174
2175/// getObjCInterfaceType - Return the unique reference to the type for the
2176/// specified ObjC interface decl. The list of protocols is optional.
2177QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) {
2178  if (Decl->TypeForDecl)
2179    return QualType(Decl->TypeForDecl, 0);
2180
2181  // FIXME: redeclarations?
2182  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2183  ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2184  Decl->TypeForDecl = T;
2185  Types.push_back(T);
2186  return QualType(T, 0);
2187}
2188
2189/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2190/// TypeOfExprType AST's (since expression's are never shared). For example,
2191/// multiple declarations that refer to "typeof(x)" all contain different
2192/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2193/// on canonical type's (which are always unique).
2194QualType ASTContext::getTypeOfExprType(Expr *tofExpr) {
2195  TypeOfExprType *toe;
2196  if (tofExpr->isTypeDependent()) {
2197    llvm::FoldingSetNodeID ID;
2198    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2199
2200    void *InsertPos = 0;
2201    DependentTypeOfExprType *Canon
2202      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
2203    if (Canon) {
2204      // We already have a "canonical" version of an identical, dependent
2205      // typeof(expr) type. Use that as our canonical type.
2206      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
2207                                          QualType((TypeOfExprType*)Canon, 0));
2208    }
2209    else {
2210      // Build a new, canonical typeof(expr) type.
2211      Canon
2212        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
2213      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
2214      toe = Canon;
2215    }
2216  } else {
2217    QualType Canonical = getCanonicalType(tofExpr->getType());
2218    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
2219  }
2220  Types.push_back(toe);
2221  return QualType(toe, 0);
2222}
2223
2224/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
2225/// TypeOfType AST's. The only motivation to unique these nodes would be
2226/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
2227/// an issue. This doesn't effect the type checker, since it operates
2228/// on canonical type's (which are always unique).
2229QualType ASTContext::getTypeOfType(QualType tofType) {
2230  QualType Canonical = getCanonicalType(tofType);
2231  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
2232  Types.push_back(tot);
2233  return QualType(tot, 0);
2234}
2235
2236/// getDecltypeForExpr - Given an expr, will return the decltype for that
2237/// expression, according to the rules in C++0x [dcl.type.simple]p4
2238static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) {
2239  if (e->isTypeDependent())
2240    return Context.DependentTy;
2241
2242  // If e is an id expression or a class member access, decltype(e) is defined
2243  // as the type of the entity named by e.
2244  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) {
2245    if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
2246      return VD->getType();
2247  }
2248  if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) {
2249    if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2250      return FD->getType();
2251  }
2252  // If e is a function call or an invocation of an overloaded operator,
2253  // (parentheses around e are ignored), decltype(e) is defined as the
2254  // return type of that function.
2255  if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens()))
2256    return CE->getCallReturnType();
2257
2258  QualType T = e->getType();
2259
2260  // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is
2261  // defined as T&, otherwise decltype(e) is defined as T.
2262  if (e->isLvalue(Context) == Expr::LV_Valid)
2263    T = Context.getLValueReferenceType(T);
2264
2265  return T;
2266}
2267
2268/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
2269/// DecltypeType AST's. The only motivation to unique these nodes would be
2270/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
2271/// an issue. This doesn't effect the type checker, since it operates
2272/// on canonical type's (which are always unique).
2273QualType ASTContext::getDecltypeType(Expr *e) {
2274  DecltypeType *dt;
2275  if (e->isTypeDependent()) {
2276    llvm::FoldingSetNodeID ID;
2277    DependentDecltypeType::Profile(ID, *this, e);
2278
2279    void *InsertPos = 0;
2280    DependentDecltypeType *Canon
2281      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
2282    if (Canon) {
2283      // We already have a "canonical" version of an equivalent, dependent
2284      // decltype type. Use that as our canonical type.
2285      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
2286                                       QualType((DecltypeType*)Canon, 0));
2287    }
2288    else {
2289      // Build a new, canonical typeof(expr) type.
2290      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
2291      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
2292      dt = Canon;
2293    }
2294  } else {
2295    QualType T = getDecltypeForExpr(e, *this);
2296    dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T));
2297  }
2298  Types.push_back(dt);
2299  return QualType(dt, 0);
2300}
2301
2302/// getTagDeclType - Return the unique reference to the type for the
2303/// specified TagDecl (struct/union/class/enum) decl.
2304QualType ASTContext::getTagDeclType(const TagDecl *Decl) {
2305  assert (Decl);
2306  // FIXME: What is the design on getTagDeclType when it requires casting
2307  // away const?  mutable?
2308  return getTypeDeclType(const_cast<TagDecl*>(Decl));
2309}
2310
2311/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
2312/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
2313/// needs to agree with the definition in <stddef.h>.
2314CanQualType ASTContext::getSizeType() const {
2315  return getFromTargetType(Target.getSizeType());
2316}
2317
2318/// getSignedWCharType - Return the type of "signed wchar_t".
2319/// Used when in C++, as a GCC extension.
2320QualType ASTContext::getSignedWCharType() const {
2321  // FIXME: derive from "Target" ?
2322  return WCharTy;
2323}
2324
2325/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
2326/// Used when in C++, as a GCC extension.
2327QualType ASTContext::getUnsignedWCharType() const {
2328  // FIXME: derive from "Target" ?
2329  return UnsignedIntTy;
2330}
2331
2332/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?)
2333/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
2334QualType ASTContext::getPointerDiffType() const {
2335  return getFromTargetType(Target.getPtrDiffType(0));
2336}
2337
2338//===----------------------------------------------------------------------===//
2339//                              Type Operators
2340//===----------------------------------------------------------------------===//
2341
2342CanQualType ASTContext::getCanonicalParamType(QualType T) {
2343  // Push qualifiers into arrays, and then discard any remaining
2344  // qualifiers.
2345  T = getCanonicalType(T);
2346  const Type *Ty = T.getTypePtr();
2347
2348  QualType Result;
2349  if (isa<ArrayType>(Ty)) {
2350    Result = getArrayDecayedType(QualType(Ty,0));
2351  } else if (isa<FunctionType>(Ty)) {
2352    Result = getPointerType(QualType(Ty, 0));
2353  } else {
2354    Result = QualType(Ty, 0);
2355  }
2356
2357  return CanQualType::CreateUnsafe(Result);
2358}
2359
2360/// getCanonicalType - Return the canonical (structural) type corresponding to
2361/// the specified potentially non-canonical type.  The non-canonical version
2362/// of a type may have many "decorated" versions of types.  Decorators can
2363/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed
2364/// to be free of any of these, allowing two canonical types to be compared
2365/// for exact equality with a simple pointer comparison.
2366CanQualType ASTContext::getCanonicalType(QualType T) {
2367  QualifierCollector Quals;
2368  const Type *Ptr = Quals.strip(T);
2369  QualType CanType = Ptr->getCanonicalTypeInternal();
2370
2371  // The canonical internal type will be the canonical type *except*
2372  // that we push type qualifiers down through array types.
2373
2374  // If there are no new qualifiers to push down, stop here.
2375  if (!Quals.hasQualifiers())
2376    return CanQualType::CreateUnsafe(CanType);
2377
2378  // If the type qualifiers are on an array type, get the canonical
2379  // type of the array with the qualifiers applied to the element
2380  // type.
2381  ArrayType *AT = dyn_cast<ArrayType>(CanType);
2382  if (!AT)
2383    return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals));
2384
2385  // Get the canonical version of the element with the extra qualifiers on it.
2386  // This can recursively sink qualifiers through multiple levels of arrays.
2387  QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals);
2388  NewEltTy = getCanonicalType(NewEltTy);
2389
2390  if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
2391    return CanQualType::CreateUnsafe(
2392             getConstantArrayType(NewEltTy, CAT->getSize(),
2393                                  CAT->getSizeModifier(),
2394                                  CAT->getIndexTypeCVRQualifiers()));
2395  if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT))
2396    return CanQualType::CreateUnsafe(
2397             getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(),
2398                                    IAT->getIndexTypeCVRQualifiers()));
2399
2400  if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT))
2401    return CanQualType::CreateUnsafe(
2402             getDependentSizedArrayType(NewEltTy,
2403                                        DSAT->getSizeExpr() ?
2404                                          DSAT->getSizeExpr()->Retain() : 0,
2405                                        DSAT->getSizeModifier(),
2406                                        DSAT->getIndexTypeCVRQualifiers(),
2407                        DSAT->getBracketsRange())->getCanonicalTypeInternal());
2408
2409  VariableArrayType *VAT = cast<VariableArrayType>(AT);
2410  return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy,
2411                                                        VAT->getSizeExpr() ?
2412                                              VAT->getSizeExpr()->Retain() : 0,
2413                                                        VAT->getSizeModifier(),
2414                                              VAT->getIndexTypeCVRQualifiers(),
2415                                                     VAT->getBracketsRange()));
2416}
2417
2418QualType ASTContext::getUnqualifiedArrayType(QualType T,
2419                                             Qualifiers &Quals) {
2420  Quals = T.getQualifiers();
2421  const ArrayType *AT = getAsArrayType(T);
2422  if (!AT) {
2423    return T.getUnqualifiedType();
2424  }
2425
2426  QualType Elt = AT->getElementType();
2427  QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals);
2428  if (Elt == UnqualElt)
2429    return T;
2430
2431  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
2432    return getConstantArrayType(UnqualElt, CAT->getSize(),
2433                                CAT->getSizeModifier(), 0);
2434  }
2435
2436  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
2437    return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0);
2438  }
2439
2440  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
2441    return getVariableArrayType(UnqualElt,
2442                                VAT->getSizeExpr() ?
2443                                VAT->getSizeExpr()->Retain() : 0,
2444                                VAT->getSizeModifier(),
2445                                VAT->getIndexTypeCVRQualifiers(),
2446                                VAT->getBracketsRange());
2447  }
2448
2449  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
2450  return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(),
2451                                    DSAT->getSizeModifier(), 0,
2452                                    SourceRange());
2453}
2454
2455/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
2456/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
2457/// they point to and return true. If T1 and T2 aren't pointer types
2458/// or pointer-to-member types, or if they are not similar at this
2459/// level, returns false and leaves T1 and T2 unchanged. Top-level
2460/// qualifiers on T1 and T2 are ignored. This function will typically
2461/// be called in a loop that successively "unwraps" pointer and
2462/// pointer-to-member types to compare them at each level.
2463bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
2464  const PointerType *T1PtrType = T1->getAs<PointerType>(),
2465                    *T2PtrType = T2->getAs<PointerType>();
2466  if (T1PtrType && T2PtrType) {
2467    T1 = T1PtrType->getPointeeType();
2468    T2 = T2PtrType->getPointeeType();
2469    return true;
2470  }
2471
2472  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
2473                          *T2MPType = T2->getAs<MemberPointerType>();
2474  if (T1MPType && T2MPType &&
2475      hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
2476                             QualType(T2MPType->getClass(), 0))) {
2477    T1 = T1MPType->getPointeeType();
2478    T2 = T2MPType->getPointeeType();
2479    return true;
2480  }
2481
2482  if (getLangOptions().ObjC1) {
2483    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
2484                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
2485    if (T1OPType && T2OPType) {
2486      T1 = T1OPType->getPointeeType();
2487      T2 = T2OPType->getPointeeType();
2488      return true;
2489    }
2490  }
2491
2492  // FIXME: Block pointers, too?
2493
2494  return false;
2495}
2496
2497DeclarationName ASTContext::getNameForTemplate(TemplateName Name) {
2498  if (TemplateDecl *TD = Name.getAsTemplateDecl())
2499    return TD->getDeclName();
2500
2501  if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
2502    if (DTN->isIdentifier()) {
2503      return DeclarationNames.getIdentifier(DTN->getIdentifier());
2504    } else {
2505      return DeclarationNames.getCXXOperatorName(DTN->getOperator());
2506    }
2507  }
2508
2509  OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
2510  assert(Storage);
2511  return (*Storage->begin())->getDeclName();
2512}
2513
2514TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) {
2515  if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
2516    if (TemplateTemplateParmDecl *TTP
2517                              = dyn_cast<TemplateTemplateParmDecl>(Template))
2518      Template = getCanonicalTemplateTemplateParmDecl(TTP);
2519
2520    // The canonical template name is the canonical template declaration.
2521    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
2522  }
2523
2524  assert(!Name.getAsOverloadedTemplate());
2525
2526  DependentTemplateName *DTN = Name.getAsDependentTemplateName();
2527  assert(DTN && "Non-dependent template names must refer to template decls.");
2528  return DTN->CanonicalTemplateName;
2529}
2530
2531bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
2532  X = getCanonicalTemplateName(X);
2533  Y = getCanonicalTemplateName(Y);
2534  return X.getAsVoidPointer() == Y.getAsVoidPointer();
2535}
2536
2537TemplateArgument
2538ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) {
2539  switch (Arg.getKind()) {
2540    case TemplateArgument::Null:
2541      return Arg;
2542
2543    case TemplateArgument::Expression:
2544      return Arg;
2545
2546    case TemplateArgument::Declaration:
2547      return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl());
2548
2549    case TemplateArgument::Template:
2550      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
2551
2552    case TemplateArgument::Integral:
2553      return TemplateArgument(*Arg.getAsIntegral(),
2554                              getCanonicalType(Arg.getIntegralType()));
2555
2556    case TemplateArgument::Type:
2557      return TemplateArgument(getCanonicalType(Arg.getAsType()));
2558
2559    case TemplateArgument::Pack: {
2560      // FIXME: Allocate in ASTContext
2561      TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()];
2562      unsigned Idx = 0;
2563      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
2564                                        AEnd = Arg.pack_end();
2565           A != AEnd; (void)++A, ++Idx)
2566        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
2567
2568      TemplateArgument Result;
2569      Result.setArgumentPack(CanonArgs, Arg.pack_size(), false);
2570      return Result;
2571    }
2572  }
2573
2574  // Silence GCC warning
2575  assert(false && "Unhandled template argument kind");
2576  return TemplateArgument();
2577}
2578
2579NestedNameSpecifier *
2580ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) {
2581  if (!NNS)
2582    return 0;
2583
2584  switch (NNS->getKind()) {
2585  case NestedNameSpecifier::Identifier:
2586    // Canonicalize the prefix but keep the identifier the same.
2587    return NestedNameSpecifier::Create(*this,
2588                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
2589                                       NNS->getAsIdentifier());
2590
2591  case NestedNameSpecifier::Namespace:
2592    // A namespace is canonical; build a nested-name-specifier with
2593    // this namespace and no prefix.
2594    return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace());
2595
2596  case NestedNameSpecifier::TypeSpec:
2597  case NestedNameSpecifier::TypeSpecWithTemplate: {
2598    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
2599    return NestedNameSpecifier::Create(*this, 0,
2600                 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate,
2601                                       T.getTypePtr());
2602  }
2603
2604  case NestedNameSpecifier::Global:
2605    // The global specifier is canonical and unique.
2606    return NNS;
2607  }
2608
2609  // Required to silence a GCC warning
2610  return 0;
2611}
2612
2613
2614const ArrayType *ASTContext::getAsArrayType(QualType T) {
2615  // Handle the non-qualified case efficiently.
2616  if (!T.hasLocalQualifiers()) {
2617    // Handle the common positive case fast.
2618    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
2619      return AT;
2620  }
2621
2622  // Handle the common negative case fast.
2623  QualType CType = T->getCanonicalTypeInternal();
2624  if (!isa<ArrayType>(CType))
2625    return 0;
2626
2627  // Apply any qualifiers from the array type to the element type.  This
2628  // implements C99 6.7.3p8: "If the specification of an array type includes
2629  // any type qualifiers, the element type is so qualified, not the array type."
2630
2631  // If we get here, we either have type qualifiers on the type, or we have
2632  // sugar such as a typedef in the way.  If we have type qualifiers on the type
2633  // we must propagate them down into the element type.
2634
2635  QualifierCollector Qs;
2636  const Type *Ty = Qs.strip(T.getDesugaredType());
2637
2638  // If we have a simple case, just return now.
2639  const ArrayType *ATy = dyn_cast<ArrayType>(Ty);
2640  if (ATy == 0 || Qs.empty())
2641    return ATy;
2642
2643  // Otherwise, we have an array and we have qualifiers on it.  Push the
2644  // qualifiers into the array element type and return a new array type.
2645  // Get the canonical version of the element with the extra qualifiers on it.
2646  // This can recursively sink qualifiers through multiple levels of arrays.
2647  QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs);
2648
2649  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
2650    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
2651                                                CAT->getSizeModifier(),
2652                                           CAT->getIndexTypeCVRQualifiers()));
2653  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
2654    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
2655                                                  IAT->getSizeModifier(),
2656                                           IAT->getIndexTypeCVRQualifiers()));
2657
2658  if (const DependentSizedArrayType *DSAT
2659        = dyn_cast<DependentSizedArrayType>(ATy))
2660    return cast<ArrayType>(
2661                     getDependentSizedArrayType(NewEltTy,
2662                                                DSAT->getSizeExpr() ?
2663                                              DSAT->getSizeExpr()->Retain() : 0,
2664                                                DSAT->getSizeModifier(),
2665                                              DSAT->getIndexTypeCVRQualifiers(),
2666                                                DSAT->getBracketsRange()));
2667
2668  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
2669  return cast<ArrayType>(getVariableArrayType(NewEltTy,
2670                                              VAT->getSizeExpr() ?
2671                                              VAT->getSizeExpr()->Retain() : 0,
2672                                              VAT->getSizeModifier(),
2673                                              VAT->getIndexTypeCVRQualifiers(),
2674                                              VAT->getBracketsRange()));
2675}
2676
2677
2678/// getArrayDecayedType - Return the properly qualified result of decaying the
2679/// specified array type to a pointer.  This operation is non-trivial when
2680/// handling typedefs etc.  The canonical type of "T" must be an array type,
2681/// this returns a pointer to a properly qualified element of the array.
2682///
2683/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2684QualType ASTContext::getArrayDecayedType(QualType Ty) {
2685  // Get the element type with 'getAsArrayType' so that we don't lose any
2686  // typedefs in the element type of the array.  This also handles propagation
2687  // of type qualifiers from the array type into the element type if present
2688  // (C99 6.7.3p8).
2689  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
2690  assert(PrettyArrayType && "Not an array type!");
2691
2692  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
2693
2694  // int x[restrict 4] ->  int *restrict
2695  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
2696}
2697
2698QualType ASTContext::getBaseElementType(QualType QT) {
2699  QualifierCollector Qs;
2700  while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2701    QT = AT->getElementType();
2702  return Qs.apply(QT);
2703}
2704
2705QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2706  QualType ElemTy = AT->getElementType();
2707
2708  if (const ArrayType *AT = getAsArrayType(ElemTy))
2709    return getBaseElementType(AT);
2710
2711  return ElemTy;
2712}
2713
2714/// getConstantArrayElementCount - Returns number of constant array elements.
2715uint64_t
2716ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
2717  uint64_t ElementCount = 1;
2718  do {
2719    ElementCount *= CA->getSize().getZExtValue();
2720    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2721  } while (CA);
2722  return ElementCount;
2723}
2724
2725/// getFloatingRank - Return a relative rank for floating point types.
2726/// This routine will assert if passed a built-in type that isn't a float.
2727static FloatingRank getFloatingRank(QualType T) {
2728  if (const ComplexType *CT = T->getAs<ComplexType>())
2729    return getFloatingRank(CT->getElementType());
2730
2731  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2732  switch (T->getAs<BuiltinType>()->getKind()) {
2733  default: assert(0 && "getFloatingRank(): not a floating type");
2734  case BuiltinType::Float:      return FloatRank;
2735  case BuiltinType::Double:     return DoubleRank;
2736  case BuiltinType::LongDouble: return LongDoubleRank;
2737  }
2738}
2739
2740/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2741/// point or a complex type (based on typeDomain/typeSize).
2742/// 'typeDomain' is a real floating point or complex type.
2743/// 'typeSize' is a real floating point or complex type.
2744QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2745                                                       QualType Domain) const {
2746  FloatingRank EltRank = getFloatingRank(Size);
2747  if (Domain->isComplexType()) {
2748    switch (EltRank) {
2749    default: assert(0 && "getFloatingRank(): illegal value for rank");
2750    case FloatRank:      return FloatComplexTy;
2751    case DoubleRank:     return DoubleComplexTy;
2752    case LongDoubleRank: return LongDoubleComplexTy;
2753    }
2754  }
2755
2756  assert(Domain->isRealFloatingType() && "Unknown domain!");
2757  switch (EltRank) {
2758  default: assert(0 && "getFloatingRank(): illegal value for rank");
2759  case FloatRank:      return FloatTy;
2760  case DoubleRank:     return DoubleTy;
2761  case LongDoubleRank: return LongDoubleTy;
2762  }
2763}
2764
2765/// getFloatingTypeOrder - Compare the rank of the two specified floating
2766/// point types, ignoring the domain of the type (i.e. 'double' ==
2767/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2768/// LHS < RHS, return -1.
2769int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2770  FloatingRank LHSR = getFloatingRank(LHS);
2771  FloatingRank RHSR = getFloatingRank(RHS);
2772
2773  if (LHSR == RHSR)
2774    return 0;
2775  if (LHSR > RHSR)
2776    return 1;
2777  return -1;
2778}
2779
2780/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2781/// routine will assert if passed a built-in type that isn't an integer or enum,
2782/// or if it is not canonicalized.
2783unsigned ASTContext::getIntegerRank(Type *T) {
2784  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
2785  if (EnumType* ET = dyn_cast<EnumType>(T))
2786    T = ET->getDecl()->getPromotionType().getTypePtr();
2787
2788  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2789    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2790
2791  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2792    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2793
2794  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2795    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2796
2797  switch (cast<BuiltinType>(T)->getKind()) {
2798  default: assert(0 && "getIntegerRank(): not a built-in integer");
2799  case BuiltinType::Bool:
2800    return 1 + (getIntWidth(BoolTy) << 3);
2801  case BuiltinType::Char_S:
2802  case BuiltinType::Char_U:
2803  case BuiltinType::SChar:
2804  case BuiltinType::UChar:
2805    return 2 + (getIntWidth(CharTy) << 3);
2806  case BuiltinType::Short:
2807  case BuiltinType::UShort:
2808    return 3 + (getIntWidth(ShortTy) << 3);
2809  case BuiltinType::Int:
2810  case BuiltinType::UInt:
2811    return 4 + (getIntWidth(IntTy) << 3);
2812  case BuiltinType::Long:
2813  case BuiltinType::ULong:
2814    return 5 + (getIntWidth(LongTy) << 3);
2815  case BuiltinType::LongLong:
2816  case BuiltinType::ULongLong:
2817    return 6 + (getIntWidth(LongLongTy) << 3);
2818  case BuiltinType::Int128:
2819  case BuiltinType::UInt128:
2820    return 7 + (getIntWidth(Int128Ty) << 3);
2821  }
2822}
2823
2824/// \brief Whether this is a promotable bitfield reference according
2825/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2826///
2827/// \returns the type this bit-field will promote to, or NULL if no
2828/// promotion occurs.
2829QualType ASTContext::isPromotableBitField(Expr *E) {
2830  if (E->isTypeDependent() || E->isValueDependent())
2831    return QualType();
2832
2833  FieldDecl *Field = E->getBitField();
2834  if (!Field)
2835    return QualType();
2836
2837  QualType FT = Field->getType();
2838
2839  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2840  uint64_t BitWidth = BitWidthAP.getZExtValue();
2841  uint64_t IntSize = getTypeSize(IntTy);
2842  // GCC extension compatibility: if the bit-field size is less than or equal
2843  // to the size of int, it gets promoted no matter what its type is.
2844  // For instance, unsigned long bf : 4 gets promoted to signed int.
2845  if (BitWidth < IntSize)
2846    return IntTy;
2847
2848  if (BitWidth == IntSize)
2849    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2850
2851  // Types bigger than int are not subject to promotions, and therefore act
2852  // like the base type.
2853  // FIXME: This doesn't quite match what gcc does, but what gcc does here
2854  // is ridiculous.
2855  return QualType();
2856}
2857
2858/// getPromotedIntegerType - Returns the type that Promotable will
2859/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2860/// integer type.
2861QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2862  assert(!Promotable.isNull());
2863  assert(Promotable->isPromotableIntegerType());
2864  if (const EnumType *ET = Promotable->getAs<EnumType>())
2865    return ET->getDecl()->getPromotionType();
2866  if (Promotable->isSignedIntegerType())
2867    return IntTy;
2868  uint64_t PromotableSize = getTypeSize(Promotable);
2869  uint64_t IntSize = getTypeSize(IntTy);
2870  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2871  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2872}
2873
2874/// getIntegerTypeOrder - Returns the highest ranked integer type:
2875/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2876/// LHS < RHS, return -1.
2877int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2878  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2879  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2880  if (LHSC == RHSC) return 0;
2881
2882  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2883  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2884
2885  unsigned LHSRank = getIntegerRank(LHSC);
2886  unsigned RHSRank = getIntegerRank(RHSC);
2887
2888  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2889    if (LHSRank == RHSRank) return 0;
2890    return LHSRank > RHSRank ? 1 : -1;
2891  }
2892
2893  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2894  if (LHSUnsigned) {
2895    // If the unsigned [LHS] type is larger, return it.
2896    if (LHSRank >= RHSRank)
2897      return 1;
2898
2899    // If the signed type can represent all values of the unsigned type, it
2900    // wins.  Because we are dealing with 2's complement and types that are
2901    // powers of two larger than each other, this is always safe.
2902    return -1;
2903  }
2904
2905  // If the unsigned [RHS] type is larger, return it.
2906  if (RHSRank >= LHSRank)
2907    return -1;
2908
2909  // If the signed type can represent all values of the unsigned type, it
2910  // wins.  Because we are dealing with 2's complement and types that are
2911  // powers of two larger than each other, this is always safe.
2912  return 1;
2913}
2914
2915static RecordDecl *
2916CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2917                 SourceLocation L, IdentifierInfo *Id) {
2918  if (Ctx.getLangOptions().CPlusPlus)
2919    return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2920  else
2921    return RecordDecl::Create(Ctx, TK, DC, L, Id);
2922}
2923
2924// getCFConstantStringType - Return the type used for constant CFStrings.
2925QualType ASTContext::getCFConstantStringType() {
2926  if (!CFConstantStringTypeDecl) {
2927    CFConstantStringTypeDecl =
2928      CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
2929                       &Idents.get("NSConstantString"));
2930    CFConstantStringTypeDecl->startDefinition();
2931
2932    QualType FieldTypes[4];
2933
2934    // const int *isa;
2935    FieldTypes[0] = getPointerType(IntTy.withConst());
2936    // int flags;
2937    FieldTypes[1] = IntTy;
2938    // const char *str;
2939    FieldTypes[2] = getPointerType(CharTy.withConst());
2940    // long length;
2941    FieldTypes[3] = LongTy;
2942
2943    // Create fields
2944    for (unsigned i = 0; i < 4; ++i) {
2945      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2946                                           SourceLocation(), 0,
2947                                           FieldTypes[i], /*TInfo=*/0,
2948                                           /*BitWidth=*/0,
2949                                           /*Mutable=*/false);
2950      Field->setAccess(AS_public);
2951      CFConstantStringTypeDecl->addDecl(Field);
2952    }
2953
2954    CFConstantStringTypeDecl->completeDefinition();
2955  }
2956
2957  return getTagDeclType(CFConstantStringTypeDecl);
2958}
2959
2960void ASTContext::setCFConstantStringType(QualType T) {
2961  const RecordType *Rec = T->getAs<RecordType>();
2962  assert(Rec && "Invalid CFConstantStringType");
2963  CFConstantStringTypeDecl = Rec->getDecl();
2964}
2965
2966// getNSConstantStringType - Return the type used for constant NSStrings.
2967QualType ASTContext::getNSConstantStringType() {
2968  if (!NSConstantStringTypeDecl) {
2969    NSConstantStringTypeDecl =
2970    CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
2971                     &Idents.get("__builtin_NSString"));
2972    NSConstantStringTypeDecl->startDefinition();
2973
2974    QualType FieldTypes[3];
2975
2976    // const int *isa;
2977    FieldTypes[0] = getPointerType(IntTy.withConst());
2978    // const char *str;
2979    FieldTypes[1] = getPointerType(CharTy.withConst());
2980    // unsigned int length;
2981    FieldTypes[2] = UnsignedIntTy;
2982
2983    // Create fields
2984    for (unsigned i = 0; i < 3; ++i) {
2985      FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2986                                           SourceLocation(), 0,
2987                                           FieldTypes[i], /*TInfo=*/0,
2988                                           /*BitWidth=*/0,
2989                                           /*Mutable=*/false);
2990      Field->setAccess(AS_public);
2991      NSConstantStringTypeDecl->addDecl(Field);
2992    }
2993
2994    NSConstantStringTypeDecl->completeDefinition();
2995  }
2996
2997  return getTagDeclType(NSConstantStringTypeDecl);
2998}
2999
3000void ASTContext::setNSConstantStringType(QualType T) {
3001  const RecordType *Rec = T->getAs<RecordType>();
3002  assert(Rec && "Invalid NSConstantStringType");
3003  NSConstantStringTypeDecl = Rec->getDecl();
3004}
3005
3006QualType ASTContext::getObjCFastEnumerationStateType() {
3007  if (!ObjCFastEnumerationStateTypeDecl) {
3008    ObjCFastEnumerationStateTypeDecl =
3009      CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3010                       &Idents.get("__objcFastEnumerationState"));
3011    ObjCFastEnumerationStateTypeDecl->startDefinition();
3012
3013    QualType FieldTypes[] = {
3014      UnsignedLongTy,
3015      getPointerType(ObjCIdTypedefType),
3016      getPointerType(UnsignedLongTy),
3017      getConstantArrayType(UnsignedLongTy,
3018                           llvm::APInt(32, 5), ArrayType::Normal, 0)
3019    };
3020
3021    for (size_t i = 0; i < 4; ++i) {
3022      FieldDecl *Field = FieldDecl::Create(*this,
3023                                           ObjCFastEnumerationStateTypeDecl,
3024                                           SourceLocation(), 0,
3025                                           FieldTypes[i], /*TInfo=*/0,
3026                                           /*BitWidth=*/0,
3027                                           /*Mutable=*/false);
3028      Field->setAccess(AS_public);
3029      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
3030    }
3031    if (getLangOptions().CPlusPlus)
3032      if (CXXRecordDecl *CXXRD =
3033            dyn_cast<CXXRecordDecl>(ObjCFastEnumerationStateTypeDecl))
3034        CXXRD->setEmpty(false);
3035
3036    ObjCFastEnumerationStateTypeDecl->completeDefinition();
3037  }
3038
3039  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
3040}
3041
3042QualType ASTContext::getBlockDescriptorType() {
3043  if (BlockDescriptorType)
3044    return getTagDeclType(BlockDescriptorType);
3045
3046  RecordDecl *T;
3047  // FIXME: Needs the FlagAppleBlock bit.
3048  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3049                       &Idents.get("__block_descriptor"));
3050  T->startDefinition();
3051
3052  QualType FieldTypes[] = {
3053    UnsignedLongTy,
3054    UnsignedLongTy,
3055  };
3056
3057  const char *FieldNames[] = {
3058    "reserved",
3059    "Size"
3060  };
3061
3062  for (size_t i = 0; i < 2; ++i) {
3063    FieldDecl *Field = FieldDecl::Create(*this,
3064                                         T,
3065                                         SourceLocation(),
3066                                         &Idents.get(FieldNames[i]),
3067                                         FieldTypes[i], /*TInfo=*/0,
3068                                         /*BitWidth=*/0,
3069                                         /*Mutable=*/false);
3070    Field->setAccess(AS_public);
3071    T->addDecl(Field);
3072  }
3073
3074  T->completeDefinition();
3075
3076  BlockDescriptorType = T;
3077
3078  return getTagDeclType(BlockDescriptorType);
3079}
3080
3081void ASTContext::setBlockDescriptorType(QualType T) {
3082  const RecordType *Rec = T->getAs<RecordType>();
3083  assert(Rec && "Invalid BlockDescriptorType");
3084  BlockDescriptorType = Rec->getDecl();
3085}
3086
3087QualType ASTContext::getBlockDescriptorExtendedType() {
3088  if (BlockDescriptorExtendedType)
3089    return getTagDeclType(BlockDescriptorExtendedType);
3090
3091  RecordDecl *T;
3092  // FIXME: Needs the FlagAppleBlock bit.
3093  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3094                       &Idents.get("__block_descriptor_withcopydispose"));
3095  T->startDefinition();
3096
3097  QualType FieldTypes[] = {
3098    UnsignedLongTy,
3099    UnsignedLongTy,
3100    getPointerType(VoidPtrTy),
3101    getPointerType(VoidPtrTy)
3102  };
3103
3104  const char *FieldNames[] = {
3105    "reserved",
3106    "Size",
3107    "CopyFuncPtr",
3108    "DestroyFuncPtr"
3109  };
3110
3111  for (size_t i = 0; i < 4; ++i) {
3112    FieldDecl *Field = FieldDecl::Create(*this,
3113                                         T,
3114                                         SourceLocation(),
3115                                         &Idents.get(FieldNames[i]),
3116                                         FieldTypes[i], /*TInfo=*/0,
3117                                         /*BitWidth=*/0,
3118                                         /*Mutable=*/false);
3119    Field->setAccess(AS_public);
3120    T->addDecl(Field);
3121  }
3122
3123  T->completeDefinition();
3124
3125  BlockDescriptorExtendedType = T;
3126
3127  return getTagDeclType(BlockDescriptorExtendedType);
3128}
3129
3130void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3131  const RecordType *Rec = T->getAs<RecordType>();
3132  assert(Rec && "Invalid BlockDescriptorType");
3133  BlockDescriptorExtendedType = Rec->getDecl();
3134}
3135
3136bool ASTContext::BlockRequiresCopying(QualType Ty) {
3137  if (Ty->isBlockPointerType())
3138    return true;
3139  if (isObjCNSObjectType(Ty))
3140    return true;
3141  if (Ty->isObjCObjectPointerType())
3142    return true;
3143  return false;
3144}
3145
3146QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3147  //  type = struct __Block_byref_1_X {
3148  //    void *__isa;
3149  //    struct __Block_byref_1_X *__forwarding;
3150  //    unsigned int __flags;
3151  //    unsigned int __size;
3152  //    void *__copy_helper;		// as needed
3153  //    void *__destroy_help		// as needed
3154  //    int X;
3155  //  } *
3156
3157  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3158
3159  // FIXME: Move up
3160  llvm::SmallString<36> Name;
3161  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3162                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3163  RecordDecl *T;
3164  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3165                       &Idents.get(Name.str()));
3166  T->startDefinition();
3167  QualType Int32Ty = IntTy;
3168  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3169  QualType FieldTypes[] = {
3170    getPointerType(VoidPtrTy),
3171    getPointerType(getTagDeclType(T)),
3172    Int32Ty,
3173    Int32Ty,
3174    getPointerType(VoidPtrTy),
3175    getPointerType(VoidPtrTy),
3176    Ty
3177  };
3178
3179  const char *FieldNames[] = {
3180    "__isa",
3181    "__forwarding",
3182    "__flags",
3183    "__size",
3184    "__copy_helper",
3185    "__destroy_helper",
3186    DeclName,
3187  };
3188
3189  for (size_t i = 0; i < 7; ++i) {
3190    if (!HasCopyAndDispose && i >=4 && i <= 5)
3191      continue;
3192    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3193                                         &Idents.get(FieldNames[i]),
3194                                         FieldTypes[i], /*TInfo=*/0,
3195                                         /*BitWidth=*/0, /*Mutable=*/false);
3196    Field->setAccess(AS_public);
3197    T->addDecl(Field);
3198  }
3199
3200  T->completeDefinition();
3201
3202  return getPointerType(getTagDeclType(T));
3203}
3204
3205
3206QualType ASTContext::getBlockParmType(
3207  bool BlockHasCopyDispose,
3208  llvm::SmallVectorImpl<const Expr *> &Layout) {
3209
3210  // FIXME: Move up
3211  llvm::SmallString<36> Name;
3212  llvm::raw_svector_ostream(Name) << "__block_literal_"
3213                                  << ++UniqueBlockParmTypeID;
3214  RecordDecl *T;
3215  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(),
3216                       &Idents.get(Name.str()));
3217  T->startDefinition();
3218  QualType FieldTypes[] = {
3219    getPointerType(VoidPtrTy),
3220    IntTy,
3221    IntTy,
3222    getPointerType(VoidPtrTy),
3223    (BlockHasCopyDispose ?
3224     getPointerType(getBlockDescriptorExtendedType()) :
3225     getPointerType(getBlockDescriptorType()))
3226  };
3227
3228  const char *FieldNames[] = {
3229    "__isa",
3230    "__flags",
3231    "__reserved",
3232    "__FuncPtr",
3233    "__descriptor"
3234  };
3235
3236  for (size_t i = 0; i < 5; ++i) {
3237    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3238                                         &Idents.get(FieldNames[i]),
3239                                         FieldTypes[i], /*TInfo=*/0,
3240                                         /*BitWidth=*/0, /*Mutable=*/false);
3241    Field->setAccess(AS_public);
3242    T->addDecl(Field);
3243  }
3244
3245  for (unsigned i = 0; i < Layout.size(); ++i) {
3246    const Expr *E = Layout[i];
3247
3248    QualType FieldType = E->getType();
3249    IdentifierInfo *FieldName = 0;
3250    if (isa<CXXThisExpr>(E)) {
3251      FieldName = &Idents.get("this");
3252    } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) {
3253      const ValueDecl *D = BDRE->getDecl();
3254      FieldName = D->getIdentifier();
3255      if (BDRE->isByRef())
3256        FieldType = BuildByRefType(D->getNameAsCString(), FieldType);
3257    } else {
3258      // Padding.
3259      assert(isa<ConstantArrayType>(FieldType) &&
3260             isa<DeclRefExpr>(E) &&
3261             !cast<DeclRefExpr>(E)->getDecl()->getDeclName() &&
3262             "doesn't match characteristics of padding decl");
3263    }
3264
3265    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3266                                         FieldName, FieldType, /*TInfo=*/0,
3267                                         /*BitWidth=*/0, /*Mutable=*/false);
3268    Field->setAccess(AS_public);
3269    T->addDecl(Field);
3270  }
3271
3272  T->completeDefinition();
3273
3274  return getPointerType(getTagDeclType(T));
3275}
3276
3277void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3278  const RecordType *Rec = T->getAs<RecordType>();
3279  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3280  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3281}
3282
3283// This returns true if a type has been typedefed to BOOL:
3284// typedef <type> BOOL;
3285static bool isTypeTypedefedAsBOOL(QualType T) {
3286  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3287    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3288      return II->isStr("BOOL");
3289
3290  return false;
3291}
3292
3293/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3294/// purpose.
3295CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
3296  CharUnits sz = getTypeSizeInChars(type);
3297
3298  // Make all integer and enum types at least as large as an int
3299  if (sz.isPositive() && type->isIntegralOrEnumerationType())
3300    sz = std::max(sz, getTypeSizeInChars(IntTy));
3301  // Treat arrays as pointers, since that's how they're passed in.
3302  else if (type->isArrayType())
3303    sz = getTypeSizeInChars(VoidPtrTy);
3304  return sz;
3305}
3306
3307static inline
3308std::string charUnitsToString(const CharUnits &CU) {
3309  return llvm::itostr(CU.getQuantity());
3310}
3311
3312/// getObjCEncodingForBlockDecl - Return the encoded type for this block
3313/// declaration.
3314void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3315                                             std::string& S) {
3316  const BlockDecl *Decl = Expr->getBlockDecl();
3317  QualType BlockTy =
3318      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3319  // Encode result type.
3320  getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
3321  // Compute size of all parameters.
3322  // Start with computing size of a pointer in number of bytes.
3323  // FIXME: There might(should) be a better way of doing this computation!
3324  SourceLocation Loc;
3325  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3326  CharUnits ParmOffset = PtrSize;
3327  for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
3328       E = Decl->param_end(); PI != E; ++PI) {
3329    QualType PType = (*PI)->getType();
3330    CharUnits sz = getObjCEncodingTypeSize(PType);
3331    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3332    ParmOffset += sz;
3333  }
3334  // Size of the argument frame
3335  S += charUnitsToString(ParmOffset);
3336  // Block pointer and offset.
3337  S += "@?0";
3338  ParmOffset = PtrSize;
3339
3340  // Argument types.
3341  ParmOffset = PtrSize;
3342  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3343       Decl->param_end(); PI != E; ++PI) {
3344    ParmVarDecl *PVDecl = *PI;
3345    QualType PType = PVDecl->getOriginalType();
3346    if (const ArrayType *AT =
3347          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3348      // Use array's original type only if it has known number of
3349      // elements.
3350      if (!isa<ConstantArrayType>(AT))
3351        PType = PVDecl->getType();
3352    } else if (PType->isFunctionType())
3353      PType = PVDecl->getType();
3354    getObjCEncodingForType(PType, S);
3355    S += charUnitsToString(ParmOffset);
3356    ParmOffset += getObjCEncodingTypeSize(PType);
3357  }
3358}
3359
3360/// getObjCEncodingForMethodDecl - Return the encoded type for this method
3361/// declaration.
3362void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3363                                              std::string& S) {
3364  // FIXME: This is not very efficient.
3365  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3366  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3367  // Encode result type.
3368  getObjCEncodingForType(Decl->getResultType(), S);
3369  // Compute size of all parameters.
3370  // Start with computing size of a pointer in number of bytes.
3371  // FIXME: There might(should) be a better way of doing this computation!
3372  SourceLocation Loc;
3373  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3374  // The first two arguments (self and _cmd) are pointers; account for
3375  // their size.
3376  CharUnits ParmOffset = 2 * PtrSize;
3377  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3378       E = Decl->sel_param_end(); PI != E; ++PI) {
3379    QualType PType = (*PI)->getType();
3380    CharUnits sz = getObjCEncodingTypeSize(PType);
3381    assert (sz.isPositive() &&
3382        "getObjCEncodingForMethodDecl - Incomplete param type");
3383    ParmOffset += sz;
3384  }
3385  S += charUnitsToString(ParmOffset);
3386  S += "@0:";
3387  S += charUnitsToString(PtrSize);
3388
3389  // Argument types.
3390  ParmOffset = 2 * PtrSize;
3391  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3392       E = Decl->sel_param_end(); PI != E; ++PI) {
3393    ParmVarDecl *PVDecl = *PI;
3394    QualType PType = PVDecl->getOriginalType();
3395    if (const ArrayType *AT =
3396          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3397      // Use array's original type only if it has known number of
3398      // elements.
3399      if (!isa<ConstantArrayType>(AT))
3400        PType = PVDecl->getType();
3401    } else if (PType->isFunctionType())
3402      PType = PVDecl->getType();
3403    // Process argument qualifiers for user supplied arguments; such as,
3404    // 'in', 'inout', etc.
3405    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3406    getObjCEncodingForType(PType, S);
3407    S += charUnitsToString(ParmOffset);
3408    ParmOffset += getObjCEncodingTypeSize(PType);
3409  }
3410}
3411
3412/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3413/// property declaration. If non-NULL, Container must be either an
3414/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3415/// NULL when getting encodings for protocol properties.
3416/// Property attributes are stored as a comma-delimited C string. The simple
3417/// attributes readonly and bycopy are encoded as single characters. The
3418/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3419/// encoded as single characters, followed by an identifier. Property types
3420/// are also encoded as a parametrized attribute. The characters used to encode
3421/// these attributes are defined by the following enumeration:
3422/// @code
3423/// enum PropertyAttributes {
3424/// kPropertyReadOnly = 'R',   // property is read-only.
3425/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3426/// kPropertyByref = '&',  // property is a reference to the value last assigned
3427/// kPropertyDynamic = 'D',    // property is dynamic
3428/// kPropertyGetter = 'G',     // followed by getter selector name
3429/// kPropertySetter = 'S',     // followed by setter selector name
3430/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3431/// kPropertyType = 't'              // followed by old-style type encoding.
3432/// kPropertyWeak = 'W'              // 'weak' property
3433/// kPropertyStrong = 'P'            // property GC'able
3434/// kPropertyNonAtomic = 'N'         // property non-atomic
3435/// };
3436/// @endcode
3437void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3438                                                const Decl *Container,
3439                                                std::string& S) {
3440  // Collect information from the property implementation decl(s).
3441  bool Dynamic = false;
3442  ObjCPropertyImplDecl *SynthesizePID = 0;
3443
3444  // FIXME: Duplicated code due to poor abstraction.
3445  if (Container) {
3446    if (const ObjCCategoryImplDecl *CID =
3447        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3448      for (ObjCCategoryImplDecl::propimpl_iterator
3449             i = CID->propimpl_begin(), e = CID->propimpl_end();
3450           i != e; ++i) {
3451        ObjCPropertyImplDecl *PID = *i;
3452        if (PID->getPropertyDecl() == PD) {
3453          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3454            Dynamic = true;
3455          } else {
3456            SynthesizePID = PID;
3457          }
3458        }
3459      }
3460    } else {
3461      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3462      for (ObjCCategoryImplDecl::propimpl_iterator
3463             i = OID->propimpl_begin(), e = OID->propimpl_end();
3464           i != e; ++i) {
3465        ObjCPropertyImplDecl *PID = *i;
3466        if (PID->getPropertyDecl() == PD) {
3467          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3468            Dynamic = true;
3469          } else {
3470            SynthesizePID = PID;
3471          }
3472        }
3473      }
3474    }
3475  }
3476
3477  // FIXME: This is not very efficient.
3478  S = "T";
3479
3480  // Encode result type.
3481  // GCC has some special rules regarding encoding of properties which
3482  // closely resembles encoding of ivars.
3483  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3484                             true /* outermost type */,
3485                             true /* encoding for property */);
3486
3487  if (PD->isReadOnly()) {
3488    S += ",R";
3489  } else {
3490    switch (PD->getSetterKind()) {
3491    case ObjCPropertyDecl::Assign: break;
3492    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3493    case ObjCPropertyDecl::Retain: S += ",&"; break;
3494    }
3495  }
3496
3497  // It really isn't clear at all what this means, since properties
3498  // are "dynamic by default".
3499  if (Dynamic)
3500    S += ",D";
3501
3502  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3503    S += ",N";
3504
3505  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3506    S += ",G";
3507    S += PD->getGetterName().getAsString();
3508  }
3509
3510  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3511    S += ",S";
3512    S += PD->getSetterName().getAsString();
3513  }
3514
3515  if (SynthesizePID) {
3516    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3517    S += ",V";
3518    S += OID->getNameAsString();
3519  }
3520
3521  // FIXME: OBJCGC: weak & strong
3522}
3523
3524/// getLegacyIntegralTypeEncoding -
3525/// Another legacy compatibility encoding: 32-bit longs are encoded as
3526/// 'l' or 'L' , but not always.  For typedefs, we need to use
3527/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3528///
3529void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3530  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3531    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3532      if (BT->getKind() == BuiltinType::ULong &&
3533          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3534        PointeeTy = UnsignedIntTy;
3535      else
3536        if (BT->getKind() == BuiltinType::Long &&
3537            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3538          PointeeTy = IntTy;
3539    }
3540  }
3541}
3542
3543void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3544                                        const FieldDecl *Field) {
3545  // We follow the behavior of gcc, expanding structures which are
3546  // directly pointed to, and expanding embedded structures. Note that
3547  // these rules are sufficient to prevent recursive encoding of the
3548  // same type.
3549  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3550                             true /* outermost type */);
3551}
3552
3553static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
3554    switch (T->getAs<BuiltinType>()->getKind()) {
3555    default: assert(0 && "Unhandled builtin type kind");
3556    case BuiltinType::Void:       return 'v';
3557    case BuiltinType::Bool:       return 'B';
3558    case BuiltinType::Char_U:
3559    case BuiltinType::UChar:      return 'C';
3560    case BuiltinType::UShort:     return 'S';
3561    case BuiltinType::UInt:       return 'I';
3562    case BuiltinType::ULong:
3563        return
3564          (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q';
3565    case BuiltinType::UInt128:    return 'T';
3566    case BuiltinType::ULongLong:  return 'Q';
3567    case BuiltinType::Char_S:
3568    case BuiltinType::SChar:      return 'c';
3569    case BuiltinType::Short:      return 's';
3570    case BuiltinType::WChar:
3571    case BuiltinType::Int:        return 'i';
3572    case BuiltinType::Long:
3573      return
3574        (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q';
3575    case BuiltinType::LongLong:   return 'q';
3576    case BuiltinType::Int128:     return 't';
3577    case BuiltinType::Float:      return 'f';
3578    case BuiltinType::Double:     return 'd';
3579    case BuiltinType::LongDouble: return 'd';
3580    }
3581}
3582
3583static void EncodeBitField(const ASTContext *Context, std::string& S,
3584                           QualType T, const FieldDecl *FD) {
3585  const Expr *E = FD->getBitWidth();
3586  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3587  ASTContext *Ctx = const_cast<ASTContext*>(Context);
3588  S += 'b';
3589  // The NeXT runtime encodes bit fields as b followed by the number of bits.
3590  // The GNU runtime requires more information; bitfields are encoded as b,
3591  // then the offset (in bits) of the first element, then the type of the
3592  // bitfield, then the size in bits.  For example, in this structure:
3593  //
3594  // struct
3595  // {
3596  //    int integer;
3597  //    int flags:2;
3598  // };
3599  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
3600  // runtime, but b32i2 for the GNU runtime.  The reason for this extra
3601  // information is not especially sensible, but we're stuck with it for
3602  // compatibility with GCC, although providing it breaks anything that
3603  // actually uses runtime introspection and wants to work on both runtimes...
3604  if (!Ctx->getLangOptions().NeXTRuntime) {
3605    const RecordDecl *RD = FD->getParent();
3606    const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
3607    // FIXME: This same linear search is also used in ExprConstant - it might
3608    // be better if the FieldDecl stored its offset.  We'd be increasing the
3609    // size of the object slightly, but saving some time every time it is used.
3610    unsigned i = 0;
3611    for (RecordDecl::field_iterator Field = RD->field_begin(),
3612                                 FieldEnd = RD->field_end();
3613         Field != FieldEnd; (void)++Field, ++i) {
3614      if (*Field == FD)
3615        break;
3616    }
3617    S += llvm::utostr(RL.getFieldOffset(i));
3618    S += ObjCEncodingForPrimitiveKind(Context, T);
3619  }
3620  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
3621  S += llvm::utostr(N);
3622}
3623
3624// FIXME: Use SmallString for accumulating string.
3625void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3626                                            bool ExpandPointedToStructures,
3627                                            bool ExpandStructures,
3628                                            const FieldDecl *FD,
3629                                            bool OutermostType,
3630                                            bool EncodingProperty) {
3631  if (T->getAs<BuiltinType>()) {
3632    if (FD && FD->isBitField())
3633      return EncodeBitField(this, S, T, FD);
3634    S += ObjCEncodingForPrimitiveKind(this, T);
3635    return;
3636  }
3637
3638  if (const ComplexType *CT = T->getAs<ComplexType>()) {
3639    S += 'j';
3640    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
3641                               false);
3642    return;
3643  }
3644
3645  // encoding for pointer or r3eference types.
3646  QualType PointeeTy;
3647  if (const PointerType *PT = T->getAs<PointerType>()) {
3648    if (PT->isObjCSelType()) {
3649      S += ':';
3650      return;
3651    }
3652    PointeeTy = PT->getPointeeType();
3653  }
3654  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3655    PointeeTy = RT->getPointeeType();
3656  if (!PointeeTy.isNull()) {
3657    bool isReadOnly = false;
3658    // For historical/compatibility reasons, the read-only qualifier of the
3659    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
3660    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
3661    // Also, do not emit the 'r' for anything but the outermost type!
3662    if (isa<TypedefType>(T.getTypePtr())) {
3663      if (OutermostType && T.isConstQualified()) {
3664        isReadOnly = true;
3665        S += 'r';
3666      }
3667    } else if (OutermostType) {
3668      QualType P = PointeeTy;
3669      while (P->getAs<PointerType>())
3670        P = P->getAs<PointerType>()->getPointeeType();
3671      if (P.isConstQualified()) {
3672        isReadOnly = true;
3673        S += 'r';
3674      }
3675    }
3676    if (isReadOnly) {
3677      // Another legacy compatibility encoding. Some ObjC qualifier and type
3678      // combinations need to be rearranged.
3679      // Rewrite "in const" from "nr" to "rn"
3680      if (llvm::StringRef(S).endswith("nr"))
3681        S.replace(S.end()-2, S.end(), "rn");
3682    }
3683
3684    if (PointeeTy->isCharType()) {
3685      // char pointer types should be encoded as '*' unless it is a
3686      // type that has been typedef'd to 'BOOL'.
3687      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
3688        S += '*';
3689        return;
3690      }
3691    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
3692      // GCC binary compat: Need to convert "struct objc_class *" to "#".
3693      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3694        S += '#';
3695        return;
3696      }
3697      // GCC binary compat: Need to convert "struct objc_object *" to "@".
3698      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3699        S += '@';
3700        return;
3701      }
3702      // fall through...
3703    }
3704    S += '^';
3705    getLegacyIntegralTypeEncoding(PointeeTy);
3706
3707    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
3708                               NULL);
3709    return;
3710  }
3711
3712  if (const ArrayType *AT =
3713      // Ignore type qualifiers etc.
3714        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
3715    if (isa<IncompleteArrayType>(AT)) {
3716      // Incomplete arrays are encoded as a pointer to the array element.
3717      S += '^';
3718
3719      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3720                                 false, ExpandStructures, FD);
3721    } else {
3722      S += '[';
3723
3724      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3725        S += llvm::utostr(CAT->getSize().getZExtValue());
3726      else {
3727        //Variable length arrays are encoded as a regular array with 0 elements.
3728        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3729        S += '0';
3730      }
3731
3732      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3733                                 false, ExpandStructures, FD);
3734      S += ']';
3735    }
3736    return;
3737  }
3738
3739  if (T->getAs<FunctionType>()) {
3740    S += '?';
3741    return;
3742  }
3743
3744  if (const RecordType *RTy = T->getAs<RecordType>()) {
3745    RecordDecl *RDecl = RTy->getDecl();
3746    S += RDecl->isUnion() ? '(' : '{';
3747    // Anonymous structures print as '?'
3748    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3749      S += II->getName();
3750      if (ClassTemplateSpecializationDecl *Spec
3751          = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
3752        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3753        std::string TemplateArgsStr
3754          = TemplateSpecializationType::PrintTemplateArgumentList(
3755                                            TemplateArgs.getFlatArgumentList(),
3756                                            TemplateArgs.flat_size(),
3757                                            (*this).PrintingPolicy);
3758
3759        S += TemplateArgsStr;
3760      }
3761    } else {
3762      S += '?';
3763    }
3764    if (ExpandStructures) {
3765      S += '=';
3766      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3767                                   FieldEnd = RDecl->field_end();
3768           Field != FieldEnd; ++Field) {
3769        if (FD) {
3770          S += '"';
3771          S += Field->getNameAsString();
3772          S += '"';
3773        }
3774
3775        // Special case bit-fields.
3776        if (Field->isBitField()) {
3777          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3778                                     (*Field));
3779        } else {
3780          QualType qt = Field->getType();
3781          getLegacyIntegralTypeEncoding(qt);
3782          getObjCEncodingForTypeImpl(qt, S, false, true,
3783                                     FD);
3784        }
3785      }
3786    }
3787    S += RDecl->isUnion() ? ')' : '}';
3788    return;
3789  }
3790
3791  if (T->isEnumeralType()) {
3792    if (FD && FD->isBitField())
3793      EncodeBitField(this, S, T, FD);
3794    else
3795      S += 'i';
3796    return;
3797  }
3798
3799  if (T->isBlockPointerType()) {
3800    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3801    return;
3802  }
3803
3804  // Ignore protocol qualifiers when mangling at this level.
3805  if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
3806    T = OT->getBaseType();
3807
3808  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3809    // @encode(class_name)
3810    ObjCInterfaceDecl *OI = OIT->getDecl();
3811    S += '{';
3812    const IdentifierInfo *II = OI->getIdentifier();
3813    S += II->getName();
3814    S += '=';
3815    llvm::SmallVector<FieldDecl*, 32> RecFields;
3816    CollectObjCIvars(OI, RecFields);
3817    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3818      if (RecFields[i]->isBitField())
3819        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3820                                   RecFields[i]);
3821      else
3822        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3823                                   FD);
3824    }
3825    S += '}';
3826    return;
3827  }
3828
3829  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
3830    if (OPT->isObjCIdType()) {
3831      S += '@';
3832      return;
3833    }
3834
3835    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3836      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3837      // Since this is a binary compatibility issue, need to consult with runtime
3838      // folks. Fortunately, this is a *very* obsure construct.
3839      S += '#';
3840      return;
3841    }
3842
3843    if (OPT->isObjCQualifiedIdType()) {
3844      getObjCEncodingForTypeImpl(getObjCIdType(), S,
3845                                 ExpandPointedToStructures,
3846                                 ExpandStructures, FD);
3847      if (FD || EncodingProperty) {
3848        // Note that we do extended encoding of protocol qualifer list
3849        // Only when doing ivar or property encoding.
3850        S += '"';
3851        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3852             E = OPT->qual_end(); I != E; ++I) {
3853          S += '<';
3854          S += (*I)->getNameAsString();
3855          S += '>';
3856        }
3857        S += '"';
3858      }
3859      return;
3860    }
3861
3862    QualType PointeeTy = OPT->getPointeeType();
3863    if (!EncodingProperty &&
3864        isa<TypedefType>(PointeeTy.getTypePtr())) {
3865      // Another historical/compatibility reason.
3866      // We encode the underlying type which comes out as
3867      // {...};
3868      S += '^';
3869      getObjCEncodingForTypeImpl(PointeeTy, S,
3870                                 false, ExpandPointedToStructures,
3871                                 NULL);
3872      return;
3873    }
3874
3875    S += '@';
3876    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
3877      S += '"';
3878      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
3879      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3880           E = OPT->qual_end(); I != E; ++I) {
3881        S += '<';
3882        S += (*I)->getNameAsString();
3883        S += '>';
3884      }
3885      S += '"';
3886    }
3887    return;
3888  }
3889
3890  // gcc just blithely ignores member pointers.
3891  // TODO: maybe there should be a mangling for these
3892  if (T->getAs<MemberPointerType>())
3893    return;
3894
3895  assert(0 && "@encode for type not implemented!");
3896}
3897
3898void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
3899                                                 std::string& S) const {
3900  if (QT & Decl::OBJC_TQ_In)
3901    S += 'n';
3902  if (QT & Decl::OBJC_TQ_Inout)
3903    S += 'N';
3904  if (QT & Decl::OBJC_TQ_Out)
3905    S += 'o';
3906  if (QT & Decl::OBJC_TQ_Bycopy)
3907    S += 'O';
3908  if (QT & Decl::OBJC_TQ_Byref)
3909    S += 'R';
3910  if (QT & Decl::OBJC_TQ_Oneway)
3911    S += 'V';
3912}
3913
3914void ASTContext::setBuiltinVaListType(QualType T) {
3915  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3916
3917  BuiltinVaListType = T;
3918}
3919
3920void ASTContext::setObjCIdType(QualType T) {
3921  ObjCIdTypedefType = T;
3922}
3923
3924void ASTContext::setObjCSelType(QualType T) {
3925  ObjCSelTypedefType = T;
3926}
3927
3928void ASTContext::setObjCProtoType(QualType QT) {
3929  ObjCProtoType = QT;
3930}
3931
3932void ASTContext::setObjCClassType(QualType T) {
3933  ObjCClassTypedefType = T;
3934}
3935
3936void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3937  assert(ObjCConstantStringType.isNull() &&
3938         "'NSConstantString' type already set!");
3939
3940  ObjCConstantStringType = getObjCInterfaceType(Decl);
3941}
3942
3943/// \brief Retrieve the template name that corresponds to a non-empty
3944/// lookup.
3945TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3946                                                   UnresolvedSetIterator End) {
3947  unsigned size = End - Begin;
3948  assert(size > 1 && "set is not overloaded!");
3949
3950  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3951                          size * sizeof(FunctionTemplateDecl*));
3952  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3953
3954  NamedDecl **Storage = OT->getStorage();
3955  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
3956    NamedDecl *D = *I;
3957    assert(isa<FunctionTemplateDecl>(D) ||
3958           (isa<UsingShadowDecl>(D) &&
3959            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3960    *Storage++ = D;
3961  }
3962
3963  return TemplateName(OT);
3964}
3965
3966/// \brief Retrieve the template name that represents a qualified
3967/// template name such as \c std::vector.
3968TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3969                                                  bool TemplateKeyword,
3970                                                  TemplateDecl *Template) {
3971  // FIXME: Canonicalization?
3972  llvm::FoldingSetNodeID ID;
3973  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3974
3975  void *InsertPos = 0;
3976  QualifiedTemplateName *QTN =
3977    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3978  if (!QTN) {
3979    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3980    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3981  }
3982
3983  return TemplateName(QTN);
3984}
3985
3986/// \brief Retrieve the template name that represents a dependent
3987/// template name such as \c MetaFun::template apply.
3988TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3989                                                  const IdentifierInfo *Name) {
3990  assert((!NNS || NNS->isDependent()) &&
3991         "Nested name specifier must be dependent");
3992
3993  llvm::FoldingSetNodeID ID;
3994  DependentTemplateName::Profile(ID, NNS, Name);
3995
3996  void *InsertPos = 0;
3997  DependentTemplateName *QTN =
3998    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3999
4000  if (QTN)
4001    return TemplateName(QTN);
4002
4003  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4004  if (CanonNNS == NNS) {
4005    QTN = new (*this,4) DependentTemplateName(NNS, Name);
4006  } else {
4007    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
4008    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
4009    DependentTemplateName *CheckQTN =
4010      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4011    assert(!CheckQTN && "Dependent type name canonicalization broken");
4012    (void)CheckQTN;
4013  }
4014
4015  DependentTemplateNames.InsertNode(QTN, InsertPos);
4016  return TemplateName(QTN);
4017}
4018
4019/// \brief Retrieve the template name that represents a dependent
4020/// template name such as \c MetaFun::template operator+.
4021TemplateName
4022ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
4023                                     OverloadedOperatorKind Operator) {
4024  assert((!NNS || NNS->isDependent()) &&
4025         "Nested name specifier must be dependent");
4026
4027  llvm::FoldingSetNodeID ID;
4028  DependentTemplateName::Profile(ID, NNS, Operator);
4029
4030  void *InsertPos = 0;
4031  DependentTemplateName *QTN
4032    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4033
4034  if (QTN)
4035    return TemplateName(QTN);
4036
4037  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
4038  if (CanonNNS == NNS) {
4039    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
4040  } else {
4041    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
4042    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
4043
4044    DependentTemplateName *CheckQTN
4045      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
4046    assert(!CheckQTN && "Dependent template name canonicalization broken");
4047    (void)CheckQTN;
4048  }
4049
4050  DependentTemplateNames.InsertNode(QTN, InsertPos);
4051  return TemplateName(QTN);
4052}
4053
4054/// getFromTargetType - Given one of the integer types provided by
4055/// TargetInfo, produce the corresponding type. The unsigned @p Type
4056/// is actually a value of type @c TargetInfo::IntType.
4057CanQualType ASTContext::getFromTargetType(unsigned Type) const {
4058  switch (Type) {
4059  case TargetInfo::NoInt: return CanQualType();
4060  case TargetInfo::SignedShort: return ShortTy;
4061  case TargetInfo::UnsignedShort: return UnsignedShortTy;
4062  case TargetInfo::SignedInt: return IntTy;
4063  case TargetInfo::UnsignedInt: return UnsignedIntTy;
4064  case TargetInfo::SignedLong: return LongTy;
4065  case TargetInfo::UnsignedLong: return UnsignedLongTy;
4066  case TargetInfo::SignedLongLong: return LongLongTy;
4067  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
4068  }
4069
4070  assert(false && "Unhandled TargetInfo::IntType value");
4071  return CanQualType();
4072}
4073
4074//===----------------------------------------------------------------------===//
4075//                        Type Predicates.
4076//===----------------------------------------------------------------------===//
4077
4078/// isObjCNSObjectType - Return true if this is an NSObject object using
4079/// NSObject attribute on a c-style pointer type.
4080/// FIXME - Make it work directly on types.
4081/// FIXME: Move to Type.
4082///
4083bool ASTContext::isObjCNSObjectType(QualType Ty) const {
4084  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
4085    if (TypedefDecl *TD = TDT->getDecl())
4086      if (TD->getAttr<ObjCNSObjectAttr>())
4087        return true;
4088  }
4089  return false;
4090}
4091
4092/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
4093/// garbage collection attribute.
4094///
4095Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
4096  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
4097  if (getLangOptions().ObjC1 &&
4098      getLangOptions().getGCMode() != LangOptions::NonGC) {
4099    GCAttrs = Ty.getObjCGCAttr();
4100    // Default behavious under objective-c's gc is for objective-c pointers
4101    // (or pointers to them) be treated as though they were declared
4102    // as __strong.
4103    if (GCAttrs == Qualifiers::GCNone) {
4104      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4105        GCAttrs = Qualifiers::Strong;
4106      else if (Ty->isPointerType())
4107        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
4108    }
4109    // Non-pointers have none gc'able attribute regardless of the attribute
4110    // set on them.
4111    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
4112      return Qualifiers::GCNone;
4113  }
4114  return GCAttrs;
4115}
4116
4117//===----------------------------------------------------------------------===//
4118//                        Type Compatibility Testing
4119//===----------------------------------------------------------------------===//
4120
4121/// areCompatVectorTypes - Return true if the two specified vector types are
4122/// compatible.
4123static bool areCompatVectorTypes(const VectorType *LHS,
4124                                 const VectorType *RHS) {
4125  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
4126  return LHS->getElementType() == RHS->getElementType() &&
4127         LHS->getNumElements() == RHS->getNumElements();
4128}
4129
4130//===----------------------------------------------------------------------===//
4131// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4132//===----------------------------------------------------------------------===//
4133
4134/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4135/// inheritance hierarchy of 'rProto'.
4136bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4137                                                ObjCProtocolDecl *rProto) {
4138  if (lProto == rProto)
4139    return true;
4140  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4141       E = rProto->protocol_end(); PI != E; ++PI)
4142    if (ProtocolCompatibleWithProtocol(lProto, *PI))
4143      return true;
4144  return false;
4145}
4146
4147/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4148/// return true if lhs's protocols conform to rhs's protocol; false
4149/// otherwise.
4150bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4151  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4152    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4153  return false;
4154}
4155
4156/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4157/// ObjCQualifiedIDType.
4158bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4159                                                   bool compare) {
4160  // Allow id<P..> and an 'id' or void* type in all cases.
4161  if (lhs->isVoidPointerType() ||
4162      lhs->isObjCIdType() || lhs->isObjCClassType())
4163    return true;
4164  else if (rhs->isVoidPointerType() ||
4165           rhs->isObjCIdType() || rhs->isObjCClassType())
4166    return true;
4167
4168  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
4169    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4170
4171    if (!rhsOPT) return false;
4172
4173    if (rhsOPT->qual_empty()) {
4174      // If the RHS is a unqualified interface pointer "NSString*",
4175      // make sure we check the class hierarchy.
4176      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4177        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4178             E = lhsQID->qual_end(); I != E; ++I) {
4179          // when comparing an id<P> on lhs with a static type on rhs,
4180          // see if static class implements all of id's protocols, directly or
4181          // through its super class and categories.
4182          if (!rhsID->ClassImplementsProtocol(*I, true))
4183            return false;
4184        }
4185      }
4186      // If there are no qualifiers and no interface, we have an 'id'.
4187      return true;
4188    }
4189    // Both the right and left sides have qualifiers.
4190    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4191         E = lhsQID->qual_end(); I != E; ++I) {
4192      ObjCProtocolDecl *lhsProto = *I;
4193      bool match = false;
4194
4195      // when comparing an id<P> on lhs with a static type on rhs,
4196      // see if static class implements all of id's protocols, directly or
4197      // through its super class and categories.
4198      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4199           E = rhsOPT->qual_end(); J != E; ++J) {
4200        ObjCProtocolDecl *rhsProto = *J;
4201        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4202            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4203          match = true;
4204          break;
4205        }
4206      }
4207      // If the RHS is a qualified interface pointer "NSString<P>*",
4208      // make sure we check the class hierarchy.
4209      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4210        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4211             E = lhsQID->qual_end(); I != E; ++I) {
4212          // when comparing an id<P> on lhs with a static type on rhs,
4213          // see if static class implements all of id's protocols, directly or
4214          // through its super class and categories.
4215          if (rhsID->ClassImplementsProtocol(*I, true)) {
4216            match = true;
4217            break;
4218          }
4219        }
4220      }
4221      if (!match)
4222        return false;
4223    }
4224
4225    return true;
4226  }
4227
4228  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4229  assert(rhsQID && "One of the LHS/RHS should be id<x>");
4230
4231  if (const ObjCObjectPointerType *lhsOPT =
4232        lhs->getAsObjCInterfacePointerType()) {
4233    if (lhsOPT->qual_empty()) {
4234      bool match = false;
4235      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4236        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4237             E = rhsQID->qual_end(); I != E; ++I) {
4238          // when comparing an id<P> on lhs with a static type on rhs,
4239          // see if static class implements all of id's protocols, directly or
4240          // through its super class and categories.
4241          if (lhsID->ClassImplementsProtocol(*I, true)) {
4242            match = true;
4243            break;
4244          }
4245        }
4246        if (!match)
4247          return false;
4248      }
4249      return true;
4250    }
4251    // Both the right and left sides have qualifiers.
4252    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4253         E = lhsOPT->qual_end(); I != E; ++I) {
4254      ObjCProtocolDecl *lhsProto = *I;
4255      bool match = false;
4256
4257      // when comparing an id<P> on lhs with a static type on rhs,
4258      // see if static class implements all of id's protocols, directly or
4259      // through its super class and categories.
4260      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4261           E = rhsQID->qual_end(); J != E; ++J) {
4262        ObjCProtocolDecl *rhsProto = *J;
4263        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4264            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4265          match = true;
4266          break;
4267        }
4268      }
4269      if (!match)
4270        return false;
4271    }
4272    return true;
4273  }
4274  return false;
4275}
4276
4277/// canAssignObjCInterfaces - Return true if the two interface types are
4278/// compatible for assignment from RHS to LHS.  This handles validation of any
4279/// protocol qualifiers on the LHS or RHS.
4280///
4281bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4282                                         const ObjCObjectPointerType *RHSOPT) {
4283  const ObjCObjectType* LHS = LHSOPT->getObjectType();
4284  const ObjCObjectType* RHS = RHSOPT->getObjectType();
4285
4286  // If either type represents the built-in 'id' or 'Class' types, return true.
4287  if (LHS->isObjCUnqualifiedIdOrClass() ||
4288      RHS->isObjCUnqualifiedIdOrClass())
4289    return true;
4290
4291  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
4292    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4293                                             QualType(RHSOPT,0),
4294                                             false);
4295
4296  // If we have 2 user-defined types, fall into that path.
4297  if (LHS->getInterface() && RHS->getInterface())
4298    return canAssignObjCInterfaces(LHS, RHS);
4299
4300  return false;
4301}
4302
4303/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4304/// for providing type-safty for objective-c pointers used to pass/return
4305/// arguments in block literals. When passed as arguments, passing 'A*' where
4306/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4307/// not OK. For the return type, the opposite is not OK.
4308bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4309                                         const ObjCObjectPointerType *LHSOPT,
4310                                         const ObjCObjectPointerType *RHSOPT) {
4311  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
4312    return true;
4313
4314  if (LHSOPT->isObjCBuiltinType()) {
4315    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4316  }
4317
4318  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4319    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4320                                             QualType(RHSOPT,0),
4321                                             false);
4322
4323  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4324  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4325  if (LHS && RHS)  { // We have 2 user-defined types.
4326    if (LHS != RHS) {
4327      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4328        return false;
4329      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4330        return true;
4331    }
4332    else
4333      return true;
4334  }
4335  return false;
4336}
4337
4338/// getIntersectionOfProtocols - This routine finds the intersection of set
4339/// of protocols inherited from two distinct objective-c pointer objects.
4340/// It is used to build composite qualifier list of the composite type of
4341/// the conditional expression involving two objective-c pointer objects.
4342static
4343void getIntersectionOfProtocols(ASTContext &Context,
4344                                const ObjCObjectPointerType *LHSOPT,
4345                                const ObjCObjectPointerType *RHSOPT,
4346      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4347
4348  const ObjCObjectType* LHS = LHSOPT->getObjectType();
4349  const ObjCObjectType* RHS = RHSOPT->getObjectType();
4350  assert(LHS->getInterface() && "LHS must have an interface base");
4351  assert(RHS->getInterface() && "RHS must have an interface base");
4352
4353  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4354  unsigned LHSNumProtocols = LHS->getNumProtocols();
4355  if (LHSNumProtocols > 0)
4356    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4357  else {
4358    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4359    Context.CollectInheritedProtocols(LHS->getInterface(),
4360                                      LHSInheritedProtocols);
4361    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4362                                LHSInheritedProtocols.end());
4363  }
4364
4365  unsigned RHSNumProtocols = RHS->getNumProtocols();
4366  if (RHSNumProtocols > 0) {
4367    ObjCProtocolDecl **RHSProtocols =
4368      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
4369    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4370      if (InheritedProtocolSet.count(RHSProtocols[i]))
4371        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4372  }
4373  else {
4374    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4375    Context.CollectInheritedProtocols(RHS->getInterface(),
4376                                      RHSInheritedProtocols);
4377    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4378         RHSInheritedProtocols.begin(),
4379         E = RHSInheritedProtocols.end(); I != E; ++I)
4380      if (InheritedProtocolSet.count((*I)))
4381        IntersectionOfProtocols.push_back((*I));
4382  }
4383}
4384
4385/// areCommonBaseCompatible - Returns common base class of the two classes if
4386/// one found. Note that this is O'2 algorithm. But it will be called as the
4387/// last type comparison in a ?-exp of ObjC pointer types before a
4388/// warning is issued. So, its invokation is extremely rare.
4389QualType ASTContext::areCommonBaseCompatible(
4390                                          const ObjCObjectPointerType *Lptr,
4391                                          const ObjCObjectPointerType *Rptr) {
4392  const ObjCObjectType *LHS = Lptr->getObjectType();
4393  const ObjCObjectType *RHS = Rptr->getObjectType();
4394  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
4395  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
4396  if (!LDecl || !RDecl)
4397    return QualType();
4398
4399  while ((LDecl = LDecl->getSuperClass())) {
4400    LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
4401    if (canAssignObjCInterfaces(LHS, RHS)) {
4402      llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols;
4403      getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
4404
4405      QualType Result = QualType(LHS, 0);
4406      if (!Protocols.empty())
4407        Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
4408      Result = getObjCObjectPointerType(Result);
4409      return Result;
4410    }
4411  }
4412
4413  return QualType();
4414}
4415
4416bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
4417                                         const ObjCObjectType *RHS) {
4418  assert(LHS->getInterface() && "LHS is not an interface type");
4419  assert(RHS->getInterface() && "RHS is not an interface type");
4420
4421  // Verify that the base decls are compatible: the RHS must be a subclass of
4422  // the LHS.
4423  if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
4424    return false;
4425
4426  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
4427  // protocol qualified at all, then we are good.
4428  if (LHS->getNumProtocols() == 0)
4429    return true;
4430
4431  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
4432  // isn't a superset.
4433  if (RHS->getNumProtocols() == 0)
4434    return true;  // FIXME: should return false!
4435
4436  for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
4437                                     LHSPE = LHS->qual_end();
4438       LHSPI != LHSPE; LHSPI++) {
4439    bool RHSImplementsProtocol = false;
4440
4441    // If the RHS doesn't implement the protocol on the left, the types
4442    // are incompatible.
4443    for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
4444                                       RHSPE = RHS->qual_end();
4445         RHSPI != RHSPE; RHSPI++) {
4446      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
4447        RHSImplementsProtocol = true;
4448        break;
4449      }
4450    }
4451    // FIXME: For better diagnostics, consider passing back the protocol name.
4452    if (!RHSImplementsProtocol)
4453      return false;
4454  }
4455  // The RHS implements all protocols listed on the LHS.
4456  return true;
4457}
4458
4459bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4460  // get the "pointed to" types
4461  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4462  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
4463
4464  if (!LHSOPT || !RHSOPT)
4465    return false;
4466
4467  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4468         canAssignObjCInterfaces(RHSOPT, LHSOPT);
4469}
4470
4471/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
4472/// both shall have the identically qualified version of a compatible type.
4473/// C99 6.2.7p1: Two types have compatible types if their types are the
4474/// same. See 6.7.[2,3,5] for additional rules.
4475bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4476  if (getLangOptions().CPlusPlus)
4477    return hasSameType(LHS, RHS);
4478
4479  return !mergeTypes(LHS, RHS).isNull();
4480}
4481
4482bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4483  return !mergeTypes(LHS, RHS, true).isNull();
4484}
4485
4486QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4487                                        bool OfBlockPointer) {
4488  const FunctionType *lbase = lhs->getAs<FunctionType>();
4489  const FunctionType *rbase = rhs->getAs<FunctionType>();
4490  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4491  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
4492  bool allLTypes = true;
4493  bool allRTypes = true;
4494
4495  // Check return type
4496  QualType retType;
4497  if (OfBlockPointer)
4498    retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4499  else
4500   retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4501  if (retType.isNull()) return QualType();
4502  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4503    allLTypes = false;
4504  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4505    allRTypes = false;
4506  // FIXME: double check this
4507  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4508  //                           rbase->getRegParmAttr() != 0 &&
4509  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
4510  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4511  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
4512  unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4513      lbaseInfo.getRegParm();
4514  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4515  if (NoReturn != lbaseInfo.getNoReturn() ||
4516      RegParm != lbaseInfo.getRegParm())
4517    allLTypes = false;
4518  if (NoReturn != rbaseInfo.getNoReturn() ||
4519      RegParm != rbaseInfo.getRegParm())
4520    allRTypes = false;
4521  CallingConv lcc = lbaseInfo.getCC();
4522  CallingConv rcc = rbaseInfo.getCC();
4523  // Compatible functions must have compatible calling conventions
4524  if (!isSameCallConv(lcc, rcc))
4525    return QualType();
4526
4527  if (lproto && rproto) { // two C99 style function prototypes
4528    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4529           "C++ shouldn't be here");
4530    unsigned lproto_nargs = lproto->getNumArgs();
4531    unsigned rproto_nargs = rproto->getNumArgs();
4532
4533    // Compatible functions must have the same number of arguments
4534    if (lproto_nargs != rproto_nargs)
4535      return QualType();
4536
4537    // Variadic and non-variadic functions aren't compatible
4538    if (lproto->isVariadic() != rproto->isVariadic())
4539      return QualType();
4540
4541    if (lproto->getTypeQuals() != rproto->getTypeQuals())
4542      return QualType();
4543
4544    // Check argument compatibility
4545    llvm::SmallVector<QualType, 10> types;
4546    for (unsigned i = 0; i < lproto_nargs; i++) {
4547      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4548      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4549      QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
4550      if (argtype.isNull()) return QualType();
4551      types.push_back(argtype);
4552      if (getCanonicalType(argtype) != getCanonicalType(largtype))
4553        allLTypes = false;
4554      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4555        allRTypes = false;
4556    }
4557    if (allLTypes) return lhs;
4558    if (allRTypes) return rhs;
4559    return getFunctionType(retType, types.begin(), types.size(),
4560                           lproto->isVariadic(), lproto->getTypeQuals(),
4561                           false, false, 0, 0,
4562                           FunctionType::ExtInfo(NoReturn, RegParm, lcc));
4563  }
4564
4565  if (lproto) allRTypes = false;
4566  if (rproto) allLTypes = false;
4567
4568  const FunctionProtoType *proto = lproto ? lproto : rproto;
4569  if (proto) {
4570    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
4571    if (proto->isVariadic()) return QualType();
4572    // Check that the types are compatible with the types that
4573    // would result from default argument promotions (C99 6.7.5.3p15).
4574    // The only types actually affected are promotable integer
4575    // types and floats, which would be passed as a different
4576    // type depending on whether the prototype is visible.
4577    unsigned proto_nargs = proto->getNumArgs();
4578    for (unsigned i = 0; i < proto_nargs; ++i) {
4579      QualType argTy = proto->getArgType(i);
4580
4581      // Look at the promotion type of enum types, since that is the type used
4582      // to pass enum values.
4583      if (const EnumType *Enum = argTy->getAs<EnumType>())
4584        argTy = Enum->getDecl()->getPromotionType();
4585
4586      if (argTy->isPromotableIntegerType() ||
4587          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4588        return QualType();
4589    }
4590
4591    if (allLTypes) return lhs;
4592    if (allRTypes) return rhs;
4593    return getFunctionType(retType, proto->arg_type_begin(),
4594                           proto->getNumArgs(), proto->isVariadic(),
4595                           proto->getTypeQuals(),
4596                           false, false, 0, 0,
4597                           FunctionType::ExtInfo(NoReturn, RegParm, lcc));
4598  }
4599
4600  if (allLTypes) return lhs;
4601  if (allRTypes) return rhs;
4602  FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
4603  return getFunctionNoProtoType(retType, Info);
4604}
4605
4606QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4607                                bool OfBlockPointer) {
4608  // C++ [expr]: If an expression initially has the type "reference to T", the
4609  // type is adjusted to "T" prior to any further analysis, the expression
4610  // designates the object or function denoted by the reference, and the
4611  // expression is an lvalue unless the reference is an rvalue reference and
4612  // the expression is a function call (possibly inside parentheses).
4613  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4614  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4615
4616  QualType LHSCan = getCanonicalType(LHS),
4617           RHSCan = getCanonicalType(RHS);
4618
4619  // If two types are identical, they are compatible.
4620  if (LHSCan == RHSCan)
4621    return LHS;
4622
4623  // If the qualifiers are different, the types aren't compatible... mostly.
4624  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4625  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4626  if (LQuals != RQuals) {
4627    // If any of these qualifiers are different, we have a type
4628    // mismatch.
4629    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4630        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4631      return QualType();
4632
4633    // Exactly one GC qualifier difference is allowed: __strong is
4634    // okay if the other type has no GC qualifier but is an Objective
4635    // C object pointer (i.e. implicitly strong by default).  We fix
4636    // this by pretending that the unqualified type was actually
4637    // qualified __strong.
4638    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4639    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4640    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4641
4642    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4643      return QualType();
4644
4645    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4646      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4647    }
4648    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4649      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4650    }
4651    return QualType();
4652  }
4653
4654  // Okay, qualifiers are equal.
4655
4656  Type::TypeClass LHSClass = LHSCan->getTypeClass();
4657  Type::TypeClass RHSClass = RHSCan->getTypeClass();
4658
4659  // We want to consider the two function types to be the same for these
4660  // comparisons, just force one to the other.
4661  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4662  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
4663
4664  // Same as above for arrays
4665  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4666    LHSClass = Type::ConstantArray;
4667  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4668    RHSClass = Type::ConstantArray;
4669
4670  // ObjCInterfaces are just specialized ObjCObjects.
4671  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
4672  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
4673
4674  // Canonicalize ExtVector -> Vector.
4675  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4676  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
4677
4678  // If the canonical type classes don't match.
4679  if (LHSClass != RHSClass) {
4680    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
4681    // a signed integer type, or an unsigned integer type.
4682    // Compatibility is based on the underlying type, not the promotion
4683    // type.
4684    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
4685      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4686        return RHS;
4687    }
4688    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
4689      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4690        return LHS;
4691    }
4692
4693    return QualType();
4694  }
4695
4696  // The canonical type classes match.
4697  switch (LHSClass) {
4698#define TYPE(Class, Base)
4699#define ABSTRACT_TYPE(Class, Base)
4700#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4701#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4702#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4703#include "clang/AST/TypeNodes.def"
4704    assert(false && "Non-canonical and dependent types shouldn't get here");
4705    return QualType();
4706
4707  case Type::LValueReference:
4708  case Type::RValueReference:
4709  case Type::MemberPointer:
4710    assert(false && "C++ should never be in mergeTypes");
4711    return QualType();
4712
4713  case Type::ObjCInterface:
4714  case Type::IncompleteArray:
4715  case Type::VariableArray:
4716  case Type::FunctionProto:
4717  case Type::ExtVector:
4718    assert(false && "Types are eliminated above");
4719    return QualType();
4720
4721  case Type::Pointer:
4722  {
4723    // Merge two pointer types, while trying to preserve typedef info
4724    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4725    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
4726    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4727    if (ResultType.isNull()) return QualType();
4728    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4729      return LHS;
4730    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4731      return RHS;
4732    return getPointerType(ResultType);
4733  }
4734  case Type::BlockPointer:
4735  {
4736    // Merge two block pointer types, while trying to preserve typedef info
4737    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4738    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
4739    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
4740    if (ResultType.isNull()) return QualType();
4741    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4742      return LHS;
4743    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4744      return RHS;
4745    return getBlockPointerType(ResultType);
4746  }
4747  case Type::ConstantArray:
4748  {
4749    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4750    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4751    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4752      return QualType();
4753
4754    QualType LHSElem = getAsArrayType(LHS)->getElementType();
4755    QualType RHSElem = getAsArrayType(RHS)->getElementType();
4756    QualType ResultType = mergeTypes(LHSElem, RHSElem);
4757    if (ResultType.isNull()) return QualType();
4758    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4759      return LHS;
4760    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4761      return RHS;
4762    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4763                                          ArrayType::ArraySizeModifier(), 0);
4764    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4765                                          ArrayType::ArraySizeModifier(), 0);
4766    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4767    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
4768    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4769      return LHS;
4770    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4771      return RHS;
4772    if (LVAT) {
4773      // FIXME: This isn't correct! But tricky to implement because
4774      // the array's size has to be the size of LHS, but the type
4775      // has to be different.
4776      return LHS;
4777    }
4778    if (RVAT) {
4779      // FIXME: This isn't correct! But tricky to implement because
4780      // the array's size has to be the size of RHS, but the type
4781      // has to be different.
4782      return RHS;
4783    }
4784    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4785    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
4786    return getIncompleteArrayType(ResultType,
4787                                  ArrayType::ArraySizeModifier(), 0);
4788  }
4789  case Type::FunctionNoProto:
4790    return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
4791  case Type::Record:
4792  case Type::Enum:
4793    return QualType();
4794  case Type::Builtin:
4795    // Only exactly equal builtin types are compatible, which is tested above.
4796    return QualType();
4797  case Type::Complex:
4798    // Distinct complex types are incompatible.
4799    return QualType();
4800  case Type::Vector:
4801    // FIXME: The merged type should be an ExtVector!
4802    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4803                             RHSCan->getAs<VectorType>()))
4804      return LHS;
4805    return QualType();
4806  case Type::ObjCObject: {
4807    // Check if the types are assignment compatible.
4808    // FIXME: This should be type compatibility, e.g. whether
4809    // "LHS x; RHS x;" at global scope is legal.
4810    const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
4811    const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
4812    if (canAssignObjCInterfaces(LHSIface, RHSIface))
4813      return LHS;
4814
4815    return QualType();
4816  }
4817  case Type::ObjCObjectPointer: {
4818    if (OfBlockPointer) {
4819      if (canAssignObjCInterfacesInBlockPointer(
4820                                          LHS->getAs<ObjCObjectPointerType>(),
4821                                          RHS->getAs<ObjCObjectPointerType>()))
4822      return LHS;
4823      return QualType();
4824    }
4825    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4826                                RHS->getAs<ObjCObjectPointerType>()))
4827      return LHS;
4828
4829    return QualType();
4830    }
4831  }
4832
4833  return QualType();
4834}
4835
4836/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
4837/// 'RHS' attributes and returns the merged version; including for function
4838/// return types.
4839QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
4840  QualType LHSCan = getCanonicalType(LHS),
4841  RHSCan = getCanonicalType(RHS);
4842  // If two types are identical, they are compatible.
4843  if (LHSCan == RHSCan)
4844    return LHS;
4845  if (RHSCan->isFunctionType()) {
4846    if (!LHSCan->isFunctionType())
4847      return QualType();
4848    QualType OldReturnType =
4849      cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
4850    QualType NewReturnType =
4851      cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
4852    QualType ResReturnType =
4853      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
4854    if (ResReturnType.isNull())
4855      return QualType();
4856    if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
4857      // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
4858      // In either case, use OldReturnType to build the new function type.
4859      const FunctionType *F = LHS->getAs<FunctionType>();
4860      if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
4861        FunctionType::ExtInfo Info = getFunctionExtInfo(LHS);
4862        QualType ResultType
4863          = getFunctionType(OldReturnType, FPT->arg_type_begin(),
4864                                  FPT->getNumArgs(), FPT->isVariadic(),
4865                                  FPT->getTypeQuals(),
4866                                  FPT->hasExceptionSpec(),
4867                                  FPT->hasAnyExceptionSpec(),
4868                                  FPT->getNumExceptions(),
4869                                  FPT->exception_begin(),
4870                                  Info);
4871        return ResultType;
4872      }
4873    }
4874    return QualType();
4875  }
4876
4877  // If the qualifiers are different, the types can still be merged.
4878  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4879  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4880  if (LQuals != RQuals) {
4881    // If any of these qualifiers are different, we have a type mismatch.
4882    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4883        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4884      return QualType();
4885
4886    // Exactly one GC qualifier difference is allowed: __strong is
4887    // okay if the other type has no GC qualifier but is an Objective
4888    // C object pointer (i.e. implicitly strong by default).  We fix
4889    // this by pretending that the unqualified type was actually
4890    // qualified __strong.
4891    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4892    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4893    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4894
4895    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4896      return QualType();
4897
4898    if (GC_L == Qualifiers::Strong)
4899      return LHS;
4900    if (GC_R == Qualifiers::Strong)
4901      return RHS;
4902    return QualType();
4903  }
4904
4905  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
4906    QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4907    QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
4908    QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
4909    if (ResQT == LHSBaseQT)
4910      return LHS;
4911    if (ResQT == RHSBaseQT)
4912      return RHS;
4913  }
4914  return QualType();
4915}
4916
4917//===----------------------------------------------------------------------===//
4918//                         Integer Predicates
4919//===----------------------------------------------------------------------===//
4920
4921unsigned ASTContext::getIntWidth(QualType T) {
4922  if (T->isBooleanType())
4923    return 1;
4924  if (EnumType *ET = dyn_cast<EnumType>(T))
4925    T = ET->getDecl()->getIntegerType();
4926  // For builtin types, just use the standard type sizing method
4927  return (unsigned)getTypeSize(T);
4928}
4929
4930QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4931  assert(T->isSignedIntegerType() && "Unexpected type");
4932
4933  // Turn <4 x signed int> -> <4 x unsigned int>
4934  if (const VectorType *VTy = T->getAs<VectorType>())
4935    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4936             VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
4937
4938  // For enums, we return the unsigned version of the base type.
4939  if (const EnumType *ETy = T->getAs<EnumType>())
4940    T = ETy->getDecl()->getIntegerType();
4941
4942  const BuiltinType *BTy = T->getAs<BuiltinType>();
4943  assert(BTy && "Unexpected signed integer type");
4944  switch (BTy->getKind()) {
4945  case BuiltinType::Char_S:
4946  case BuiltinType::SChar:
4947    return UnsignedCharTy;
4948  case BuiltinType::Short:
4949    return UnsignedShortTy;
4950  case BuiltinType::Int:
4951    return UnsignedIntTy;
4952  case BuiltinType::Long:
4953    return UnsignedLongTy;
4954  case BuiltinType::LongLong:
4955    return UnsignedLongLongTy;
4956  case BuiltinType::Int128:
4957    return UnsignedInt128Ty;
4958  default:
4959    assert(0 && "Unexpected signed integer type");
4960    return QualType();
4961  }
4962}
4963
4964ExternalASTSource::~ExternalASTSource() { }
4965
4966void ExternalASTSource::PrintStats() { }
4967
4968
4969//===----------------------------------------------------------------------===//
4970//                          Builtin Type Computation
4971//===----------------------------------------------------------------------===//
4972
4973/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4974/// pointer over the consumed characters.  This returns the resultant type.
4975static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4976                                  ASTContext::GetBuiltinTypeError &Error,
4977                                  bool AllowTypeModifiers = true) {
4978  // Modifiers.
4979  int HowLong = 0;
4980  bool Signed = false, Unsigned = false;
4981
4982  // Read the modifiers first.
4983  bool Done = false;
4984  while (!Done) {
4985    switch (*Str++) {
4986    default: Done = true; --Str; break;
4987    case 'S':
4988      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4989      assert(!Signed && "Can't use 'S' modifier multiple times!");
4990      Signed = true;
4991      break;
4992    case 'U':
4993      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4994      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4995      Unsigned = true;
4996      break;
4997    case 'L':
4998      assert(HowLong <= 2 && "Can't have LLLL modifier");
4999      ++HowLong;
5000      break;
5001    }
5002  }
5003
5004  QualType Type;
5005
5006  // Read the base type.
5007  switch (*Str++) {
5008  default: assert(0 && "Unknown builtin type letter!");
5009  case 'v':
5010    assert(HowLong == 0 && !Signed && !Unsigned &&
5011           "Bad modifiers used with 'v'!");
5012    Type = Context.VoidTy;
5013    break;
5014  case 'f':
5015    assert(HowLong == 0 && !Signed && !Unsigned &&
5016           "Bad modifiers used with 'f'!");
5017    Type = Context.FloatTy;
5018    break;
5019  case 'd':
5020    assert(HowLong < 2 && !Signed && !Unsigned &&
5021           "Bad modifiers used with 'd'!");
5022    if (HowLong)
5023      Type = Context.LongDoubleTy;
5024    else
5025      Type = Context.DoubleTy;
5026    break;
5027  case 's':
5028    assert(HowLong == 0 && "Bad modifiers used with 's'!");
5029    if (Unsigned)
5030      Type = Context.UnsignedShortTy;
5031    else
5032      Type = Context.ShortTy;
5033    break;
5034  case 'i':
5035    if (HowLong == 3)
5036      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
5037    else if (HowLong == 2)
5038      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
5039    else if (HowLong == 1)
5040      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
5041    else
5042      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
5043    break;
5044  case 'c':
5045    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
5046    if (Signed)
5047      Type = Context.SignedCharTy;
5048    else if (Unsigned)
5049      Type = Context.UnsignedCharTy;
5050    else
5051      Type = Context.CharTy;
5052    break;
5053  case 'b': // boolean
5054    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
5055    Type = Context.BoolTy;
5056    break;
5057  case 'z':  // size_t.
5058    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
5059    Type = Context.getSizeType();
5060    break;
5061  case 'F':
5062    Type = Context.getCFConstantStringType();
5063    break;
5064  case 'a':
5065    Type = Context.getBuiltinVaListType();
5066    assert(!Type.isNull() && "builtin va list type not initialized!");
5067    break;
5068  case 'A':
5069    // This is a "reference" to a va_list; however, what exactly
5070    // this means depends on how va_list is defined. There are two
5071    // different kinds of va_list: ones passed by value, and ones
5072    // passed by reference.  An example of a by-value va_list is
5073    // x86, where va_list is a char*. An example of by-ref va_list
5074    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
5075    // we want this argument to be a char*&; for x86-64, we want
5076    // it to be a __va_list_tag*.
5077    Type = Context.getBuiltinVaListType();
5078    assert(!Type.isNull() && "builtin va list type not initialized!");
5079    if (Type->isArrayType()) {
5080      Type = Context.getArrayDecayedType(Type);
5081    } else {
5082      Type = Context.getLValueReferenceType(Type);
5083    }
5084    break;
5085  case 'V': {
5086    char *End;
5087    unsigned NumElements = strtoul(Str, &End, 10);
5088    assert(End != Str && "Missing vector size");
5089
5090    Str = End;
5091
5092    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5093    // FIXME: Don't know what to do about AltiVec.
5094    Type = Context.getVectorType(ElementType, NumElements, false, false);
5095    break;
5096  }
5097  case 'X': {
5098    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
5099    Type = Context.getComplexType(ElementType);
5100    break;
5101  }
5102  case 'P':
5103    Type = Context.getFILEType();
5104    if (Type.isNull()) {
5105      Error = ASTContext::GE_Missing_stdio;
5106      return QualType();
5107    }
5108    break;
5109  case 'J':
5110    if (Signed)
5111      Type = Context.getsigjmp_bufType();
5112    else
5113      Type = Context.getjmp_bufType();
5114
5115    if (Type.isNull()) {
5116      Error = ASTContext::GE_Missing_setjmp;
5117      return QualType();
5118    }
5119    break;
5120  }
5121
5122  if (!AllowTypeModifiers)
5123    return Type;
5124
5125  Done = false;
5126  while (!Done) {
5127    switch (char c = *Str++) {
5128      default: Done = true; --Str; break;
5129      case '*':
5130      case '&':
5131        {
5132          // Both pointers and references can have their pointee types
5133          // qualified with an address space.
5134          char *End;
5135          unsigned AddrSpace = strtoul(Str, &End, 10);
5136          if (End != Str && AddrSpace != 0) {
5137            Type = Context.getAddrSpaceQualType(Type, AddrSpace);
5138            Str = End;
5139          }
5140        }
5141        if (c == '*')
5142          Type = Context.getPointerType(Type);
5143        else
5144          Type = Context.getLValueReferenceType(Type);
5145        break;
5146      // FIXME: There's no way to have a built-in with an rvalue ref arg.
5147      case 'C':
5148        Type = Type.withConst();
5149        break;
5150      case 'D':
5151        Type = Context.getVolatileType(Type);
5152        break;
5153    }
5154  }
5155
5156  return Type;
5157}
5158
5159/// GetBuiltinType - Return the type for the specified builtin.
5160QualType ASTContext::GetBuiltinType(unsigned id,
5161                                    GetBuiltinTypeError &Error) {
5162  const char *TypeStr = BuiltinInfo.GetTypeString(id);
5163
5164  llvm::SmallVector<QualType, 8> ArgTypes;
5165
5166  Error = GE_None;
5167  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
5168  if (Error != GE_None)
5169    return QualType();
5170  while (TypeStr[0] && TypeStr[0] != '.') {
5171    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
5172    if (Error != GE_None)
5173      return QualType();
5174
5175    // Do array -> pointer decay.  The builtin should use the decayed type.
5176    if (Ty->isArrayType())
5177      Ty = getArrayDecayedType(Ty);
5178
5179    ArgTypes.push_back(Ty);
5180  }
5181
5182  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
5183         "'.' should only occur at end of builtin type list!");
5184
5185  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
5186  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
5187    return getFunctionNoProtoType(ResType);
5188
5189  // FIXME: Should we create noreturn types?
5190  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
5191                         TypeStr[0] == '.', 0, false, false, 0, 0,
5192                         FunctionType::ExtInfo());
5193}
5194
5195QualType
5196ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
5197  // Perform the usual unary conversions. We do this early so that
5198  // integral promotions to "int" can allow us to exit early, in the
5199  // lhs == rhs check. Also, for conversion purposes, we ignore any
5200  // qualifiers.  For example, "const float" and "float" are
5201  // equivalent.
5202  if (lhs->isPromotableIntegerType())
5203    lhs = getPromotedIntegerType(lhs);
5204  else
5205    lhs = lhs.getUnqualifiedType();
5206  if (rhs->isPromotableIntegerType())
5207    rhs = getPromotedIntegerType(rhs);
5208  else
5209    rhs = rhs.getUnqualifiedType();
5210
5211  // If both types are identical, no conversion is needed.
5212  if (lhs == rhs)
5213    return lhs;
5214
5215  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
5216  // The caller can deal with this (e.g. pointer + int).
5217  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5218    return lhs;
5219
5220  // At this point, we have two different arithmetic types.
5221
5222  // Handle complex types first (C99 6.3.1.8p1).
5223  if (lhs->isComplexType() || rhs->isComplexType()) {
5224    // if we have an integer operand, the result is the complex type.
5225    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
5226      // convert the rhs to the lhs complex type.
5227      return lhs;
5228    }
5229    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
5230      // convert the lhs to the rhs complex type.
5231      return rhs;
5232    }
5233    // This handles complex/complex, complex/float, or float/complex.
5234    // When both operands are complex, the shorter operand is converted to the
5235    // type of the longer, and that is the type of the result. This corresponds
5236    // to what is done when combining two real floating-point operands.
5237    // The fun begins when size promotion occur across type domains.
5238    // From H&S 6.3.4: When one operand is complex and the other is a real
5239    // floating-point type, the less precise type is converted, within it's
5240    // real or complex domain, to the precision of the other type. For example,
5241    // when combining a "long double" with a "double _Complex", the
5242    // "double _Complex" is promoted to "long double _Complex".
5243    int result = getFloatingTypeOrder(lhs, rhs);
5244
5245    if (result > 0) { // The left side is bigger, convert rhs.
5246      rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
5247    } else if (result < 0) { // The right side is bigger, convert lhs.
5248      lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
5249    }
5250    // At this point, lhs and rhs have the same rank/size. Now, make sure the
5251    // domains match. This is a requirement for our implementation, C99
5252    // does not require this promotion.
5253    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5254      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5255        return rhs;
5256      } else { // handle "_Complex double, double".
5257        return lhs;
5258      }
5259    }
5260    return lhs; // The domain/size match exactly.
5261  }
5262  // Now handle "real" floating types (i.e. float, double, long double).
5263  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5264    // if we have an integer operand, the result is the real floating type.
5265    if (rhs->isIntegerType()) {
5266      // convert rhs to the lhs floating point type.
5267      return lhs;
5268    }
5269    if (rhs->isComplexIntegerType()) {
5270      // convert rhs to the complex floating point type.
5271      return getComplexType(lhs);
5272    }
5273    if (lhs->isIntegerType()) {
5274      // convert lhs to the rhs floating point type.
5275      return rhs;
5276    }
5277    if (lhs->isComplexIntegerType()) {
5278      // convert lhs to the complex floating point type.
5279      return getComplexType(rhs);
5280    }
5281    // We have two real floating types, float/complex combos were handled above.
5282    // Convert the smaller operand to the bigger result.
5283    int result = getFloatingTypeOrder(lhs, rhs);
5284    if (result > 0) // convert the rhs
5285      return lhs;
5286    assert(result < 0 && "illegal float comparison");
5287    return rhs;   // convert the lhs
5288  }
5289  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5290    // Handle GCC complex int extension.
5291    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5292    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5293
5294    if (lhsComplexInt && rhsComplexInt) {
5295      if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
5296                              rhsComplexInt->getElementType()) >= 0)
5297        return lhs; // convert the rhs
5298      return rhs;
5299    } else if (lhsComplexInt && rhs->isIntegerType()) {
5300      // convert the rhs to the lhs complex type.
5301      return lhs;
5302    } else if (rhsComplexInt && lhs->isIntegerType()) {
5303      // convert the lhs to the rhs complex type.
5304      return rhs;
5305    }
5306  }
5307  // Finally, we have two differing integer types.
5308  // The rules for this case are in C99 6.3.1.8
5309  int compare = getIntegerTypeOrder(lhs, rhs);
5310  bool lhsSigned = lhs->isSignedIntegerType(),
5311       rhsSigned = rhs->isSignedIntegerType();
5312  QualType destType;
5313  if (lhsSigned == rhsSigned) {
5314    // Same signedness; use the higher-ranked type
5315    destType = compare >= 0 ? lhs : rhs;
5316  } else if (compare != (lhsSigned ? 1 : -1)) {
5317    // The unsigned type has greater than or equal rank to the
5318    // signed type, so use the unsigned type
5319    destType = lhsSigned ? rhs : lhs;
5320  } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5321    // The two types are different widths; if we are here, that
5322    // means the signed type is larger than the unsigned type, so
5323    // use the signed type.
5324    destType = lhsSigned ? lhs : rhs;
5325  } else {
5326    // The signed type is higher-ranked than the unsigned type,
5327    // but isn't actually any bigger (like unsigned int and long
5328    // on most 32-bit systems).  Use the unsigned type corresponding
5329    // to the signed type.
5330    destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5331  }
5332  return destType;
5333}
5334