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