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