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