ASTContext.cpp revision 0237941e0beb0c929934b66ad29443b484d987fe
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(Protocols,
2123                                                     Protocols + NumProtocols);
2124      unsigned UniqueCount = NumProtocols;
2125
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(Protocols,
2169                                                   Protocols + NumProtocols);
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 (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0)))
2649    QT = AT->getElementType();
2650  return Qs.apply(QT);
2651}
2652
2653QualType ASTContext::getBaseElementType(const ArrayType *AT) {
2654  QualType ElemTy = AT->getElementType();
2655
2656  if (const ArrayType *AT = getAsArrayType(ElemTy))
2657    return getBaseElementType(AT);
2658
2659  return ElemTy;
2660}
2661
2662/// getConstantArrayElementCount - Returns number of constant array elements.
2663uint64_t
2664ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
2665  uint64_t ElementCount = 1;
2666  do {
2667    ElementCount *= CA->getSize().getZExtValue();
2668    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
2669  } while (CA);
2670  return ElementCount;
2671}
2672
2673/// getFloatingRank - Return a relative rank for floating point types.
2674/// This routine will assert if passed a built-in type that isn't a float.
2675static FloatingRank getFloatingRank(QualType T) {
2676  if (const ComplexType *CT = T->getAs<ComplexType>())
2677    return getFloatingRank(CT->getElementType());
2678
2679  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
2680  switch (T->getAs<BuiltinType>()->getKind()) {
2681  default: assert(0 && "getFloatingRank(): not a floating type");
2682  case BuiltinType::Float:      return FloatRank;
2683  case BuiltinType::Double:     return DoubleRank;
2684  case BuiltinType::LongDouble: return LongDoubleRank;
2685  }
2686}
2687
2688/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
2689/// point or a complex type (based on typeDomain/typeSize).
2690/// 'typeDomain' is a real floating point or complex type.
2691/// 'typeSize' is a real floating point or complex type.
2692QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
2693                                                       QualType Domain) const {
2694  FloatingRank EltRank = getFloatingRank(Size);
2695  if (Domain->isComplexType()) {
2696    switch (EltRank) {
2697    default: assert(0 && "getFloatingRank(): illegal value for rank");
2698    case FloatRank:      return FloatComplexTy;
2699    case DoubleRank:     return DoubleComplexTy;
2700    case LongDoubleRank: return LongDoubleComplexTy;
2701    }
2702  }
2703
2704  assert(Domain->isRealFloatingType() && "Unknown domain!");
2705  switch (EltRank) {
2706  default: assert(0 && "getFloatingRank(): illegal value for rank");
2707  case FloatRank:      return FloatTy;
2708  case DoubleRank:     return DoubleTy;
2709  case LongDoubleRank: return LongDoubleTy;
2710  }
2711}
2712
2713/// getFloatingTypeOrder - Compare the rank of the two specified floating
2714/// point types, ignoring the domain of the type (i.e. 'double' ==
2715/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2716/// LHS < RHS, return -1.
2717int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) {
2718  FloatingRank LHSR = getFloatingRank(LHS);
2719  FloatingRank RHSR = getFloatingRank(RHS);
2720
2721  if (LHSR == RHSR)
2722    return 0;
2723  if (LHSR > RHSR)
2724    return 1;
2725  return -1;
2726}
2727
2728/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
2729/// routine will assert if passed a built-in type that isn't an integer or enum,
2730/// or if it is not canonicalized.
2731unsigned ASTContext::getIntegerRank(Type *T) {
2732  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
2733  if (EnumType* ET = dyn_cast<EnumType>(T))
2734    T = ET->getDecl()->getPromotionType().getTypePtr();
2735
2736  if (T->isSpecificBuiltinType(BuiltinType::WChar))
2737    T = getFromTargetType(Target.getWCharType()).getTypePtr();
2738
2739  if (T->isSpecificBuiltinType(BuiltinType::Char16))
2740    T = getFromTargetType(Target.getChar16Type()).getTypePtr();
2741
2742  if (T->isSpecificBuiltinType(BuiltinType::Char32))
2743    T = getFromTargetType(Target.getChar32Type()).getTypePtr();
2744
2745  switch (cast<BuiltinType>(T)->getKind()) {
2746  default: assert(0 && "getIntegerRank(): not a built-in integer");
2747  case BuiltinType::Bool:
2748    return 1 + (getIntWidth(BoolTy) << 3);
2749  case BuiltinType::Char_S:
2750  case BuiltinType::Char_U:
2751  case BuiltinType::SChar:
2752  case BuiltinType::UChar:
2753    return 2 + (getIntWidth(CharTy) << 3);
2754  case BuiltinType::Short:
2755  case BuiltinType::UShort:
2756    return 3 + (getIntWidth(ShortTy) << 3);
2757  case BuiltinType::Int:
2758  case BuiltinType::UInt:
2759    return 4 + (getIntWidth(IntTy) << 3);
2760  case BuiltinType::Long:
2761  case BuiltinType::ULong:
2762    return 5 + (getIntWidth(LongTy) << 3);
2763  case BuiltinType::LongLong:
2764  case BuiltinType::ULongLong:
2765    return 6 + (getIntWidth(LongLongTy) << 3);
2766  case BuiltinType::Int128:
2767  case BuiltinType::UInt128:
2768    return 7 + (getIntWidth(Int128Ty) << 3);
2769  }
2770}
2771
2772/// \brief Whether this is a promotable bitfield reference according
2773/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2774///
2775/// \returns the type this bit-field will promote to, or NULL if no
2776/// promotion occurs.
2777QualType ASTContext::isPromotableBitField(Expr *E) {
2778  FieldDecl *Field = E->getBitField();
2779  if (!Field)
2780    return QualType();
2781
2782  QualType FT = Field->getType();
2783
2784  llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this);
2785  uint64_t BitWidth = BitWidthAP.getZExtValue();
2786  uint64_t IntSize = getTypeSize(IntTy);
2787  // GCC extension compatibility: if the bit-field size is less than or equal
2788  // to the size of int, it gets promoted no matter what its type is.
2789  // For instance, unsigned long bf : 4 gets promoted to signed int.
2790  if (BitWidth < IntSize)
2791    return IntTy;
2792
2793  if (BitWidth == IntSize)
2794    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
2795
2796  // Types bigger than int are not subject to promotions, and therefore act
2797  // like the base type.
2798  // FIXME: This doesn't quite match what gcc does, but what gcc does here
2799  // is ridiculous.
2800  return QualType();
2801}
2802
2803/// getPromotedIntegerType - Returns the type that Promotable will
2804/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
2805/// integer type.
2806QualType ASTContext::getPromotedIntegerType(QualType Promotable) {
2807  assert(!Promotable.isNull());
2808  assert(Promotable->isPromotableIntegerType());
2809  if (const EnumType *ET = Promotable->getAs<EnumType>())
2810    return ET->getDecl()->getPromotionType();
2811  if (Promotable->isSignedIntegerType())
2812    return IntTy;
2813  uint64_t PromotableSize = getTypeSize(Promotable);
2814  uint64_t IntSize = getTypeSize(IntTy);
2815  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
2816  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
2817}
2818
2819/// getIntegerTypeOrder - Returns the highest ranked integer type:
2820/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
2821/// LHS < RHS, return -1.
2822int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) {
2823  Type *LHSC = getCanonicalType(LHS).getTypePtr();
2824  Type *RHSC = getCanonicalType(RHS).getTypePtr();
2825  if (LHSC == RHSC) return 0;
2826
2827  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
2828  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
2829
2830  unsigned LHSRank = getIntegerRank(LHSC);
2831  unsigned RHSRank = getIntegerRank(RHSC);
2832
2833  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
2834    if (LHSRank == RHSRank) return 0;
2835    return LHSRank > RHSRank ? 1 : -1;
2836  }
2837
2838  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
2839  if (LHSUnsigned) {
2840    // If the unsigned [LHS] type is larger, return it.
2841    if (LHSRank >= RHSRank)
2842      return 1;
2843
2844    // If the signed type can represent all values of the unsigned type, it
2845    // wins.  Because we are dealing with 2's complement and types that are
2846    // powers of two larger than each other, this is always safe.
2847    return -1;
2848  }
2849
2850  // If the unsigned [RHS] type is larger, return it.
2851  if (RHSRank >= LHSRank)
2852    return -1;
2853
2854  // If the signed type can represent all values of the unsigned type, it
2855  // wins.  Because we are dealing with 2's complement and types that are
2856  // powers of two larger than each other, this is always safe.
2857  return 1;
2858}
2859
2860static RecordDecl *
2861CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC,
2862                 SourceLocation L, IdentifierInfo *Id) {
2863  if (Ctx.getLangOptions().CPlusPlus)
2864    return CXXRecordDecl::Create(Ctx, TK, DC, L, Id);
2865  else
2866    return RecordDecl::Create(Ctx, TK, DC, L, Id);
2867}
2868
2869// getCFConstantStringType - Return the type used for constant CFStrings.
2870QualType ASTContext::getCFConstantStringType() {
2871  if (!CFConstantStringTypeDecl) {
2872    CFConstantStringTypeDecl =
2873      CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2874                       &Idents.get("NSConstantString"));
2875    CFConstantStringTypeDecl->startDefinition();
2876
2877    QualType FieldTypes[4];
2878
2879    // const int *isa;
2880    FieldTypes[0] = getPointerType(IntTy.withConst());
2881    // int flags;
2882    FieldTypes[1] = IntTy;
2883    // const char *str;
2884    FieldTypes[2] = getPointerType(CharTy.withConst());
2885    // long length;
2886    FieldTypes[3] = LongTy;
2887
2888    // Create fields
2889    for (unsigned i = 0; i < 4; ++i) {
2890      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
2891                                           SourceLocation(), 0,
2892                                           FieldTypes[i], /*TInfo=*/0,
2893                                           /*BitWidth=*/0,
2894                                           /*Mutable=*/false);
2895      CFConstantStringTypeDecl->addDecl(Field);
2896    }
2897
2898    CFConstantStringTypeDecl->completeDefinition();
2899  }
2900
2901  return getTagDeclType(CFConstantStringTypeDecl);
2902}
2903
2904void ASTContext::setCFConstantStringType(QualType T) {
2905  const RecordType *Rec = T->getAs<RecordType>();
2906  assert(Rec && "Invalid CFConstantStringType");
2907  CFConstantStringTypeDecl = Rec->getDecl();
2908}
2909
2910// getNSConstantStringType - Return the type used for constant NSStrings.
2911QualType ASTContext::getNSConstantStringType() {
2912  if (!NSConstantStringTypeDecl) {
2913    NSConstantStringTypeDecl =
2914    CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2915                     &Idents.get("__builtin_NSString"));
2916    NSConstantStringTypeDecl->startDefinition();
2917
2918    QualType FieldTypes[3];
2919
2920    // const int *isa;
2921    FieldTypes[0] = getPointerType(IntTy.withConst());
2922    // const char *str;
2923    FieldTypes[1] = getPointerType(CharTy.withConst());
2924    // unsigned int length;
2925    FieldTypes[2] = UnsignedIntTy;
2926
2927    // Create fields
2928    for (unsigned i = 0; i < 3; ++i) {
2929      FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl,
2930                                           SourceLocation(), 0,
2931                                           FieldTypes[i], /*TInfo=*/0,
2932                                           /*BitWidth=*/0,
2933                                           /*Mutable=*/false);
2934      NSConstantStringTypeDecl->addDecl(Field);
2935    }
2936
2937    NSConstantStringTypeDecl->completeDefinition();
2938  }
2939
2940  return getTagDeclType(NSConstantStringTypeDecl);
2941}
2942
2943void ASTContext::setNSConstantStringType(QualType T) {
2944  const RecordType *Rec = T->getAs<RecordType>();
2945  assert(Rec && "Invalid NSConstantStringType");
2946  NSConstantStringTypeDecl = Rec->getDecl();
2947}
2948
2949QualType ASTContext::getObjCFastEnumerationStateType() {
2950  if (!ObjCFastEnumerationStateTypeDecl) {
2951    ObjCFastEnumerationStateTypeDecl =
2952      CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2953                       &Idents.get("__objcFastEnumerationState"));
2954    ObjCFastEnumerationStateTypeDecl->startDefinition();
2955
2956    QualType FieldTypes[] = {
2957      UnsignedLongTy,
2958      getPointerType(ObjCIdTypedefType),
2959      getPointerType(UnsignedLongTy),
2960      getConstantArrayType(UnsignedLongTy,
2961                           llvm::APInt(32, 5), ArrayType::Normal, 0)
2962    };
2963
2964    for (size_t i = 0; i < 4; ++i) {
2965      FieldDecl *Field = FieldDecl::Create(*this,
2966                                           ObjCFastEnumerationStateTypeDecl,
2967                                           SourceLocation(), 0,
2968                                           FieldTypes[i], /*TInfo=*/0,
2969                                           /*BitWidth=*/0,
2970                                           /*Mutable=*/false);
2971      ObjCFastEnumerationStateTypeDecl->addDecl(Field);
2972    }
2973
2974    ObjCFastEnumerationStateTypeDecl->completeDefinition();
2975  }
2976
2977  return getTagDeclType(ObjCFastEnumerationStateTypeDecl);
2978}
2979
2980QualType ASTContext::getBlockDescriptorType() {
2981  if (BlockDescriptorType)
2982    return getTagDeclType(BlockDescriptorType);
2983
2984  RecordDecl *T;
2985  // FIXME: Needs the FlagAppleBlock bit.
2986  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
2987                       &Idents.get("__block_descriptor"));
2988  T->startDefinition();
2989
2990  QualType FieldTypes[] = {
2991    UnsignedLongTy,
2992    UnsignedLongTy,
2993  };
2994
2995  const char *FieldNames[] = {
2996    "reserved",
2997    "Size"
2998  };
2999
3000  for (size_t i = 0; i < 2; ++i) {
3001    FieldDecl *Field = FieldDecl::Create(*this,
3002                                         T,
3003                                         SourceLocation(),
3004                                         &Idents.get(FieldNames[i]),
3005                                         FieldTypes[i], /*TInfo=*/0,
3006                                         /*BitWidth=*/0,
3007                                         /*Mutable=*/false);
3008    T->addDecl(Field);
3009  }
3010
3011  T->completeDefinition();
3012
3013  BlockDescriptorType = T;
3014
3015  return getTagDeclType(BlockDescriptorType);
3016}
3017
3018void ASTContext::setBlockDescriptorType(QualType T) {
3019  const RecordType *Rec = T->getAs<RecordType>();
3020  assert(Rec && "Invalid BlockDescriptorType");
3021  BlockDescriptorType = Rec->getDecl();
3022}
3023
3024QualType ASTContext::getBlockDescriptorExtendedType() {
3025  if (BlockDescriptorExtendedType)
3026    return getTagDeclType(BlockDescriptorExtendedType);
3027
3028  RecordDecl *T;
3029  // FIXME: Needs the FlagAppleBlock bit.
3030  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3031                       &Idents.get("__block_descriptor_withcopydispose"));
3032  T->startDefinition();
3033
3034  QualType FieldTypes[] = {
3035    UnsignedLongTy,
3036    UnsignedLongTy,
3037    getPointerType(VoidPtrTy),
3038    getPointerType(VoidPtrTy)
3039  };
3040
3041  const char *FieldNames[] = {
3042    "reserved",
3043    "Size",
3044    "CopyFuncPtr",
3045    "DestroyFuncPtr"
3046  };
3047
3048  for (size_t i = 0; i < 4; ++i) {
3049    FieldDecl *Field = FieldDecl::Create(*this,
3050                                         T,
3051                                         SourceLocation(),
3052                                         &Idents.get(FieldNames[i]),
3053                                         FieldTypes[i], /*TInfo=*/0,
3054                                         /*BitWidth=*/0,
3055                                         /*Mutable=*/false);
3056    T->addDecl(Field);
3057  }
3058
3059  T->completeDefinition();
3060
3061  BlockDescriptorExtendedType = T;
3062
3063  return getTagDeclType(BlockDescriptorExtendedType);
3064}
3065
3066void ASTContext::setBlockDescriptorExtendedType(QualType T) {
3067  const RecordType *Rec = T->getAs<RecordType>();
3068  assert(Rec && "Invalid BlockDescriptorType");
3069  BlockDescriptorExtendedType = Rec->getDecl();
3070}
3071
3072bool ASTContext::BlockRequiresCopying(QualType Ty) {
3073  if (Ty->isBlockPointerType())
3074    return true;
3075  if (isObjCNSObjectType(Ty))
3076    return true;
3077  if (Ty->isObjCObjectPointerType())
3078    return true;
3079  return false;
3080}
3081
3082QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) {
3083  //  type = struct __Block_byref_1_X {
3084  //    void *__isa;
3085  //    struct __Block_byref_1_X *__forwarding;
3086  //    unsigned int __flags;
3087  //    unsigned int __size;
3088  //    void *__copy_helper;		// as needed
3089  //    void *__destroy_help		// as needed
3090  //    int X;
3091  //  } *
3092
3093  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
3094
3095  // FIXME: Move up
3096  static unsigned int UniqueBlockByRefTypeID = 0;
3097  llvm::SmallString<36> Name;
3098  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
3099                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
3100  RecordDecl *T;
3101  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3102                       &Idents.get(Name.str()));
3103  T->startDefinition();
3104  QualType Int32Ty = IntTy;
3105  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
3106  QualType FieldTypes[] = {
3107    getPointerType(VoidPtrTy),
3108    getPointerType(getTagDeclType(T)),
3109    Int32Ty,
3110    Int32Ty,
3111    getPointerType(VoidPtrTy),
3112    getPointerType(VoidPtrTy),
3113    Ty
3114  };
3115
3116  const char *FieldNames[] = {
3117    "__isa",
3118    "__forwarding",
3119    "__flags",
3120    "__size",
3121    "__copy_helper",
3122    "__destroy_helper",
3123    DeclName,
3124  };
3125
3126  for (size_t i = 0; i < 7; ++i) {
3127    if (!HasCopyAndDispose && i >=4 && i <= 5)
3128      continue;
3129    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3130                                         &Idents.get(FieldNames[i]),
3131                                         FieldTypes[i], /*TInfo=*/0,
3132                                         /*BitWidth=*/0, /*Mutable=*/false);
3133    T->addDecl(Field);
3134  }
3135
3136  T->completeDefinition();
3137
3138  return getPointerType(getTagDeclType(T));
3139}
3140
3141
3142QualType ASTContext::getBlockParmType(
3143  bool BlockHasCopyDispose,
3144  llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) {
3145  // FIXME: Move up
3146  static unsigned int UniqueBlockParmTypeID = 0;
3147  llvm::SmallString<36> Name;
3148  llvm::raw_svector_ostream(Name) << "__block_literal_"
3149                                  << ++UniqueBlockParmTypeID;
3150  RecordDecl *T;
3151  T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(),
3152                       &Idents.get(Name.str()));
3153  T->startDefinition();
3154  QualType FieldTypes[] = {
3155    getPointerType(VoidPtrTy),
3156    IntTy,
3157    IntTy,
3158    getPointerType(VoidPtrTy),
3159    (BlockHasCopyDispose ?
3160     getPointerType(getBlockDescriptorExtendedType()) :
3161     getPointerType(getBlockDescriptorType()))
3162  };
3163
3164  const char *FieldNames[] = {
3165    "__isa",
3166    "__flags",
3167    "__reserved",
3168    "__FuncPtr",
3169    "__descriptor"
3170  };
3171
3172  for (size_t i = 0; i < 5; ++i) {
3173    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3174                                         &Idents.get(FieldNames[i]),
3175                                         FieldTypes[i], /*TInfo=*/0,
3176                                         /*BitWidth=*/0, /*Mutable=*/false);
3177    T->addDecl(Field);
3178  }
3179
3180  for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) {
3181    const Expr *E = BlockDeclRefDecls[i];
3182    const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E);
3183    clang::IdentifierInfo *Name = 0;
3184    if (BDRE) {
3185      const ValueDecl *D = BDRE->getDecl();
3186      Name = &Idents.get(D->getName());
3187    }
3188    QualType FieldType = E->getType();
3189
3190    if (BDRE && BDRE->isByRef())
3191      FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(),
3192                                 FieldType);
3193
3194    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3195                                         Name, FieldType, /*TInfo=*/0,
3196                                         /*BitWidth=*/0, /*Mutable=*/false);
3197    T->addDecl(Field);
3198  }
3199
3200  T->completeDefinition();
3201
3202  return getPointerType(getTagDeclType(T));
3203}
3204
3205void ASTContext::setObjCFastEnumerationStateType(QualType T) {
3206  const RecordType *Rec = T->getAs<RecordType>();
3207  assert(Rec && "Invalid ObjCFAstEnumerationStateType");
3208  ObjCFastEnumerationStateTypeDecl = Rec->getDecl();
3209}
3210
3211// This returns true if a type has been typedefed to BOOL:
3212// typedef <type> BOOL;
3213static bool isTypeTypedefedAsBOOL(QualType T) {
3214  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
3215    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
3216      return II->isStr("BOOL");
3217
3218  return false;
3219}
3220
3221/// getObjCEncodingTypeSize returns size of type for objective-c encoding
3222/// purpose.
3223CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) {
3224  CharUnits sz = getTypeSizeInChars(type);
3225
3226  // Make all integer and enum types at least as large as an int
3227  if (sz.isPositive() && type->isIntegralType())
3228    sz = std::max(sz, getTypeSizeInChars(IntTy));
3229  // Treat arrays as pointers, since that's how they're passed in.
3230  else if (type->isArrayType())
3231    sz = getTypeSizeInChars(VoidPtrTy);
3232  return sz;
3233}
3234
3235static inline
3236std::string charUnitsToString(const CharUnits &CU) {
3237  return llvm::itostr(CU.getQuantity());
3238}
3239
3240/// getObjCEncodingForBlockDecl - Return the encoded type for this block
3241/// declaration.
3242void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr,
3243                                             std::string& S) {
3244  const BlockDecl *Decl = Expr->getBlockDecl();
3245  QualType BlockTy =
3246      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
3247  // Encode result type.
3248  getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S);
3249  // Compute size of all parameters.
3250  // Start with computing size of a pointer in number of bytes.
3251  // FIXME: There might(should) be a better way of doing this computation!
3252  SourceLocation Loc;
3253  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3254  CharUnits ParmOffset = PtrSize;
3255  for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
3256       E = Decl->param_end(); PI != E; ++PI) {
3257    QualType PType = (*PI)->getType();
3258    CharUnits sz = getObjCEncodingTypeSize(PType);
3259    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
3260    ParmOffset += sz;
3261  }
3262  // Size of the argument frame
3263  S += charUnitsToString(ParmOffset);
3264  // Block pointer and offset.
3265  S += "@?0";
3266  ParmOffset = PtrSize;
3267
3268  // Argument types.
3269  ParmOffset = PtrSize;
3270  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
3271       Decl->param_end(); PI != E; ++PI) {
3272    ParmVarDecl *PVDecl = *PI;
3273    QualType PType = PVDecl->getOriginalType();
3274    if (const ArrayType *AT =
3275          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3276      // Use array's original type only if it has known number of
3277      // elements.
3278      if (!isa<ConstantArrayType>(AT))
3279        PType = PVDecl->getType();
3280    } else if (PType->isFunctionType())
3281      PType = PVDecl->getType();
3282    getObjCEncodingForType(PType, S);
3283    S += charUnitsToString(ParmOffset);
3284    ParmOffset += getObjCEncodingTypeSize(PType);
3285  }
3286}
3287
3288/// getObjCEncodingForMethodDecl - Return the encoded type for this method
3289/// declaration.
3290void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
3291                                              std::string& S) {
3292  // FIXME: This is not very efficient.
3293  // Encode type qualifer, 'in', 'inout', etc. for the return type.
3294  getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S);
3295  // Encode result type.
3296  getObjCEncodingForType(Decl->getResultType(), S);
3297  // Compute size of all parameters.
3298  // Start with computing size of a pointer in number of bytes.
3299  // FIXME: There might(should) be a better way of doing this computation!
3300  SourceLocation Loc;
3301  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
3302  // The first two arguments (self and _cmd) are pointers; account for
3303  // their size.
3304  CharUnits ParmOffset = 2 * PtrSize;
3305  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3306       E = Decl->sel_param_end(); PI != E; ++PI) {
3307    QualType PType = (*PI)->getType();
3308    CharUnits sz = getObjCEncodingTypeSize(PType);
3309    assert (sz.isPositive() &&
3310        "getObjCEncodingForMethodDecl - Incomplete param type");
3311    ParmOffset += sz;
3312  }
3313  S += charUnitsToString(ParmOffset);
3314  S += "@0:";
3315  S += charUnitsToString(PtrSize);
3316
3317  // Argument types.
3318  ParmOffset = 2 * PtrSize;
3319  for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(),
3320       E = Decl->sel_param_end(); PI != E; ++PI) {
3321    ParmVarDecl *PVDecl = *PI;
3322    QualType PType = PVDecl->getOriginalType();
3323    if (const ArrayType *AT =
3324          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
3325      // Use array's original type only if it has known number of
3326      // elements.
3327      if (!isa<ConstantArrayType>(AT))
3328        PType = PVDecl->getType();
3329    } else if (PType->isFunctionType())
3330      PType = PVDecl->getType();
3331    // Process argument qualifiers for user supplied arguments; such as,
3332    // 'in', 'inout', etc.
3333    getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S);
3334    getObjCEncodingForType(PType, S);
3335    S += charUnitsToString(ParmOffset);
3336    ParmOffset += getObjCEncodingTypeSize(PType);
3337  }
3338}
3339
3340/// getObjCEncodingForPropertyDecl - Return the encoded type for this
3341/// property declaration. If non-NULL, Container must be either an
3342/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
3343/// NULL when getting encodings for protocol properties.
3344/// Property attributes are stored as a comma-delimited C string. The simple
3345/// attributes readonly and bycopy are encoded as single characters. The
3346/// parametrized attributes, getter=name, setter=name, and ivar=name, are
3347/// encoded as single characters, followed by an identifier. Property types
3348/// are also encoded as a parametrized attribute. The characters used to encode
3349/// these attributes are defined by the following enumeration:
3350/// @code
3351/// enum PropertyAttributes {
3352/// kPropertyReadOnly = 'R',   // property is read-only.
3353/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
3354/// kPropertyByref = '&',  // property is a reference to the value last assigned
3355/// kPropertyDynamic = 'D',    // property is dynamic
3356/// kPropertyGetter = 'G',     // followed by getter selector name
3357/// kPropertySetter = 'S',     // followed by setter selector name
3358/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
3359/// kPropertyType = 't'              // followed by old-style type encoding.
3360/// kPropertyWeak = 'W'              // 'weak' property
3361/// kPropertyStrong = 'P'            // property GC'able
3362/// kPropertyNonAtomic = 'N'         // property non-atomic
3363/// };
3364/// @endcode
3365void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
3366                                                const Decl *Container,
3367                                                std::string& S) {
3368  // Collect information from the property implementation decl(s).
3369  bool Dynamic = false;
3370  ObjCPropertyImplDecl *SynthesizePID = 0;
3371
3372  // FIXME: Duplicated code due to poor abstraction.
3373  if (Container) {
3374    if (const ObjCCategoryImplDecl *CID =
3375        dyn_cast<ObjCCategoryImplDecl>(Container)) {
3376      for (ObjCCategoryImplDecl::propimpl_iterator
3377             i = CID->propimpl_begin(), e = CID->propimpl_end();
3378           i != e; ++i) {
3379        ObjCPropertyImplDecl *PID = *i;
3380        if (PID->getPropertyDecl() == PD) {
3381          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3382            Dynamic = true;
3383          } else {
3384            SynthesizePID = PID;
3385          }
3386        }
3387      }
3388    } else {
3389      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
3390      for (ObjCCategoryImplDecl::propimpl_iterator
3391             i = OID->propimpl_begin(), e = OID->propimpl_end();
3392           i != e; ++i) {
3393        ObjCPropertyImplDecl *PID = *i;
3394        if (PID->getPropertyDecl() == PD) {
3395          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
3396            Dynamic = true;
3397          } else {
3398            SynthesizePID = PID;
3399          }
3400        }
3401      }
3402    }
3403  }
3404
3405  // FIXME: This is not very efficient.
3406  S = "T";
3407
3408  // Encode result type.
3409  // GCC has some special rules regarding encoding of properties which
3410  // closely resembles encoding of ivars.
3411  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
3412                             true /* outermost type */,
3413                             true /* encoding for property */);
3414
3415  if (PD->isReadOnly()) {
3416    S += ",R";
3417  } else {
3418    switch (PD->getSetterKind()) {
3419    case ObjCPropertyDecl::Assign: break;
3420    case ObjCPropertyDecl::Copy:   S += ",C"; break;
3421    case ObjCPropertyDecl::Retain: S += ",&"; break;
3422    }
3423  }
3424
3425  // It really isn't clear at all what this means, since properties
3426  // are "dynamic by default".
3427  if (Dynamic)
3428    S += ",D";
3429
3430  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
3431    S += ",N";
3432
3433  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
3434    S += ",G";
3435    S += PD->getGetterName().getAsString();
3436  }
3437
3438  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
3439    S += ",S";
3440    S += PD->getSetterName().getAsString();
3441  }
3442
3443  if (SynthesizePID) {
3444    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
3445    S += ",V";
3446    S += OID->getNameAsString();
3447  }
3448
3449  // FIXME: OBJCGC: weak & strong
3450}
3451
3452/// getLegacyIntegralTypeEncoding -
3453/// Another legacy compatibility encoding: 32-bit longs are encoded as
3454/// 'l' or 'L' , but not always.  For typedefs, we need to use
3455/// 'i' or 'I' instead if encoding a struct field, or a pointer!
3456///
3457void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
3458  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
3459    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
3460      if (BT->getKind() == BuiltinType::ULong &&
3461          ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3462        PointeeTy = UnsignedIntTy;
3463      else
3464        if (BT->getKind() == BuiltinType::Long &&
3465            ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32))
3466          PointeeTy = IntTy;
3467    }
3468  }
3469}
3470
3471void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
3472                                        const FieldDecl *Field) {
3473  // We follow the behavior of gcc, expanding structures which are
3474  // directly pointed to, and expanding embedded structures. Note that
3475  // these rules are sufficient to prevent recursive encoding of the
3476  // same type.
3477  getObjCEncodingForTypeImpl(T, S, true, true, Field,
3478                             true /* outermost type */);
3479}
3480
3481static void EncodeBitField(const ASTContext *Context, std::string& S,
3482                           const FieldDecl *FD) {
3483  const Expr *E = FD->getBitWidth();
3484  assert(E && "bitfield width not there - getObjCEncodingForTypeImpl");
3485  ASTContext *Ctx = const_cast<ASTContext*>(Context);
3486  unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue();
3487  S += 'b';
3488  S += llvm::utostr(N);
3489}
3490
3491// FIXME: Use SmallString for accumulating string.
3492void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
3493                                            bool ExpandPointedToStructures,
3494                                            bool ExpandStructures,
3495                                            const FieldDecl *FD,
3496                                            bool OutermostType,
3497                                            bool EncodingProperty) {
3498  if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
3499    if (FD && FD->isBitField())
3500      return EncodeBitField(this, S, FD);
3501    char encoding;
3502    switch (BT->getKind()) {
3503    default: assert(0 && "Unhandled builtin type kind");
3504    case BuiltinType::Void:       encoding = 'v'; break;
3505    case BuiltinType::Bool:       encoding = 'B'; break;
3506    case BuiltinType::Char_U:
3507    case BuiltinType::UChar:      encoding = 'C'; break;
3508    case BuiltinType::UShort:     encoding = 'S'; break;
3509    case BuiltinType::UInt:       encoding = 'I'; break;
3510    case BuiltinType::ULong:
3511        encoding =
3512          (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q';
3513        break;
3514    case BuiltinType::UInt128:    encoding = 'T'; break;
3515    case BuiltinType::ULongLong:  encoding = 'Q'; break;
3516    case BuiltinType::Char_S:
3517    case BuiltinType::SChar:      encoding = 'c'; break;
3518    case BuiltinType::Short:      encoding = 's'; break;
3519    case BuiltinType::Int:        encoding = 'i'; break;
3520    case BuiltinType::Long:
3521      encoding =
3522        (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q';
3523      break;
3524    case BuiltinType::LongLong:   encoding = 'q'; break;
3525    case BuiltinType::Int128:     encoding = 't'; break;
3526    case BuiltinType::Float:      encoding = 'f'; break;
3527    case BuiltinType::Double:     encoding = 'd'; break;
3528    case BuiltinType::LongDouble: encoding = 'd'; break;
3529    }
3530
3531    S += encoding;
3532    return;
3533  }
3534
3535  if (const ComplexType *CT = T->getAs<ComplexType>()) {
3536    S += 'j';
3537    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
3538                               false);
3539    return;
3540  }
3541
3542  // encoding for pointer or r3eference types.
3543  QualType PointeeTy;
3544  if (const PointerType *PT = T->getAs<PointerType>()) {
3545    if (PT->isObjCSelType()) {
3546      S += ':';
3547      return;
3548    }
3549    PointeeTy = PT->getPointeeType();
3550  }
3551  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3552    PointeeTy = RT->getPointeeType();
3553  if (!PointeeTy.isNull()) {
3554    bool isReadOnly = false;
3555    // For historical/compatibility reasons, the read-only qualifier of the
3556    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
3557    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
3558    // Also, do not emit the 'r' for anything but the outermost type!
3559    if (isa<TypedefType>(T.getTypePtr())) {
3560      if (OutermostType && T.isConstQualified()) {
3561        isReadOnly = true;
3562        S += 'r';
3563      }
3564    } else if (OutermostType) {
3565      QualType P = PointeeTy;
3566      while (P->getAs<PointerType>())
3567        P = P->getAs<PointerType>()->getPointeeType();
3568      if (P.isConstQualified()) {
3569        isReadOnly = true;
3570        S += 'r';
3571      }
3572    }
3573    if (isReadOnly) {
3574      // Another legacy compatibility encoding. Some ObjC qualifier and type
3575      // combinations need to be rearranged.
3576      // Rewrite "in const" from "nr" to "rn"
3577      if (llvm::StringRef(S).endswith("nr"))
3578        S.replace(S.end()-2, S.end(), "rn");
3579    }
3580
3581    if (PointeeTy->isCharType()) {
3582      // char pointer types should be encoded as '*' unless it is a
3583      // type that has been typedef'd to 'BOOL'.
3584      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
3585        S += '*';
3586        return;
3587      }
3588    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
3589      // GCC binary compat: Need to convert "struct objc_class *" to "#".
3590      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
3591        S += '#';
3592        return;
3593      }
3594      // GCC binary compat: Need to convert "struct objc_object *" to "@".
3595      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
3596        S += '@';
3597        return;
3598      }
3599      // fall through...
3600    }
3601    S += '^';
3602    getLegacyIntegralTypeEncoding(PointeeTy);
3603
3604    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
3605                               NULL);
3606    return;
3607  }
3608
3609  if (const ArrayType *AT =
3610      // Ignore type qualifiers etc.
3611        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
3612    if (isa<IncompleteArrayType>(AT)) {
3613      // Incomplete arrays are encoded as a pointer to the array element.
3614      S += '^';
3615
3616      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3617                                 false, ExpandStructures, FD);
3618    } else {
3619      S += '[';
3620
3621      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
3622        S += llvm::utostr(CAT->getSize().getZExtValue());
3623      else {
3624        //Variable length arrays are encoded as a regular array with 0 elements.
3625        assert(isa<VariableArrayType>(AT) && "Unknown array type!");
3626        S += '0';
3627      }
3628
3629      getObjCEncodingForTypeImpl(AT->getElementType(), S,
3630                                 false, ExpandStructures, FD);
3631      S += ']';
3632    }
3633    return;
3634  }
3635
3636  if (T->getAs<FunctionType>()) {
3637    S += '?';
3638    return;
3639  }
3640
3641  if (const RecordType *RTy = T->getAs<RecordType>()) {
3642    RecordDecl *RDecl = RTy->getDecl();
3643    S += RDecl->isUnion() ? '(' : '{';
3644    // Anonymous structures print as '?'
3645    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
3646      S += II->getName();
3647    } else {
3648      S += '?';
3649    }
3650    if (ExpandStructures) {
3651      S += '=';
3652      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3653                                   FieldEnd = RDecl->field_end();
3654           Field != FieldEnd; ++Field) {
3655        if (FD) {
3656          S += '"';
3657          S += Field->getNameAsString();
3658          S += '"';
3659        }
3660
3661        // Special case bit-fields.
3662        if (Field->isBitField()) {
3663          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3664                                     (*Field));
3665        } else {
3666          QualType qt = Field->getType();
3667          getLegacyIntegralTypeEncoding(qt);
3668          getObjCEncodingForTypeImpl(qt, S, false, true,
3669                                     FD);
3670        }
3671      }
3672    }
3673    S += RDecl->isUnion() ? ')' : '}';
3674    return;
3675  }
3676
3677  if (T->isEnumeralType()) {
3678    if (FD && FD->isBitField())
3679      EncodeBitField(this, S, FD);
3680    else
3681      S += 'i';
3682    return;
3683  }
3684
3685  if (T->isBlockPointerType()) {
3686    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3687    return;
3688  }
3689
3690  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3691    // @encode(class_name)
3692    ObjCInterfaceDecl *OI = OIT->getDecl();
3693    S += '{';
3694    const IdentifierInfo *II = OI->getIdentifier();
3695    S += II->getName();
3696    S += '=';
3697    llvm::SmallVector<FieldDecl*, 32> RecFields;
3698    CollectObjCIvars(OI, RecFields);
3699    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3700      if (RecFields[i]->isBitField())
3701        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3702                                   RecFields[i]);
3703      else
3704        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3705                                   FD);
3706    }
3707    S += '}';
3708    return;
3709  }
3710
3711  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
3712    if (OPT->isObjCIdType()) {
3713      S += '@';
3714      return;
3715    }
3716
3717    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3718      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3719      // Since this is a binary compatibility issue, need to consult with runtime
3720      // folks. Fortunately, this is a *very* obsure construct.
3721      S += '#';
3722      return;
3723    }
3724
3725    if (OPT->isObjCQualifiedIdType()) {
3726      getObjCEncodingForTypeImpl(getObjCIdType(), S,
3727                                 ExpandPointedToStructures,
3728                                 ExpandStructures, FD);
3729      if (FD || EncodingProperty) {
3730        // Note that we do extended encoding of protocol qualifer list
3731        // Only when doing ivar or property encoding.
3732        S += '"';
3733        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3734             E = OPT->qual_end(); I != E; ++I) {
3735          S += '<';
3736          S += (*I)->getNameAsString();
3737          S += '>';
3738        }
3739        S += '"';
3740      }
3741      return;
3742    }
3743
3744    QualType PointeeTy = OPT->getPointeeType();
3745    if (!EncodingProperty &&
3746        isa<TypedefType>(PointeeTy.getTypePtr())) {
3747      // Another historical/compatibility reason.
3748      // We encode the underlying type which comes out as
3749      // {...};
3750      S += '^';
3751      getObjCEncodingForTypeImpl(PointeeTy, S,
3752                                 false, ExpandPointedToStructures,
3753                                 NULL);
3754      return;
3755    }
3756
3757    S += '@';
3758    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
3759      S += '"';
3760      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
3761      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3762           E = OPT->qual_end(); I != E; ++I) {
3763        S += '<';
3764        S += (*I)->getNameAsString();
3765        S += '>';
3766      }
3767      S += '"';
3768    }
3769    return;
3770  }
3771
3772  assert(0 && "@encode for type not implemented!");
3773}
3774
3775void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
3776                                                 std::string& S) const {
3777  if (QT & Decl::OBJC_TQ_In)
3778    S += 'n';
3779  if (QT & Decl::OBJC_TQ_Inout)
3780    S += 'N';
3781  if (QT & Decl::OBJC_TQ_Out)
3782    S += 'o';
3783  if (QT & Decl::OBJC_TQ_Bycopy)
3784    S += 'O';
3785  if (QT & Decl::OBJC_TQ_Byref)
3786    S += 'R';
3787  if (QT & Decl::OBJC_TQ_Oneway)
3788    S += 'V';
3789}
3790
3791void ASTContext::setBuiltinVaListType(QualType T) {
3792  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3793
3794  BuiltinVaListType = T;
3795}
3796
3797void ASTContext::setObjCIdType(QualType T) {
3798  ObjCIdTypedefType = T;
3799}
3800
3801void ASTContext::setObjCSelType(QualType T) {
3802  ObjCSelTypedefType = T;
3803}
3804
3805void ASTContext::setObjCProtoType(QualType QT) {
3806  ObjCProtoType = QT;
3807}
3808
3809void ASTContext::setObjCClassType(QualType T) {
3810  ObjCClassTypedefType = T;
3811}
3812
3813void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3814  assert(ObjCConstantStringType.isNull() &&
3815         "'NSConstantString' type already set!");
3816
3817  ObjCConstantStringType = getObjCInterfaceType(Decl);
3818}
3819
3820/// \brief Retrieve the template name that corresponds to a non-empty
3821/// lookup.
3822TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3823                                                   UnresolvedSetIterator End) {
3824  unsigned size = End - Begin;
3825  assert(size > 1 && "set is not overloaded!");
3826
3827  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3828                          size * sizeof(FunctionTemplateDecl*));
3829  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3830
3831  NamedDecl **Storage = OT->getStorage();
3832  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
3833    NamedDecl *D = *I;
3834    assert(isa<FunctionTemplateDecl>(D) ||
3835           (isa<UsingShadowDecl>(D) &&
3836            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3837    *Storage++ = D;
3838  }
3839
3840  return TemplateName(OT);
3841}
3842
3843/// \brief Retrieve the template name that represents a qualified
3844/// template name such as \c std::vector.
3845TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3846                                                  bool TemplateKeyword,
3847                                                  TemplateDecl *Template) {
3848  // FIXME: Canonicalization?
3849  llvm::FoldingSetNodeID ID;
3850  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3851
3852  void *InsertPos = 0;
3853  QualifiedTemplateName *QTN =
3854    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3855  if (!QTN) {
3856    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3857    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3858  }
3859
3860  return TemplateName(QTN);
3861}
3862
3863/// \brief Retrieve the template name that represents a dependent
3864/// template name such as \c MetaFun::template apply.
3865TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3866                                                  const IdentifierInfo *Name) {
3867  assert((!NNS || NNS->isDependent()) &&
3868         "Nested name specifier must be dependent");
3869
3870  llvm::FoldingSetNodeID ID;
3871  DependentTemplateName::Profile(ID, NNS, Name);
3872
3873  void *InsertPos = 0;
3874  DependentTemplateName *QTN =
3875    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3876
3877  if (QTN)
3878    return TemplateName(QTN);
3879
3880  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3881  if (CanonNNS == NNS) {
3882    QTN = new (*this,4) DependentTemplateName(NNS, Name);
3883  } else {
3884    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3885    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3886    DependentTemplateName *CheckQTN =
3887      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3888    assert(!CheckQTN && "Dependent type name canonicalization broken");
3889    (void)CheckQTN;
3890  }
3891
3892  DependentTemplateNames.InsertNode(QTN, InsertPos);
3893  return TemplateName(QTN);
3894}
3895
3896/// \brief Retrieve the template name that represents a dependent
3897/// template name such as \c MetaFun::template operator+.
3898TemplateName
3899ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3900                                     OverloadedOperatorKind Operator) {
3901  assert((!NNS || NNS->isDependent()) &&
3902         "Nested name specifier must be dependent");
3903
3904  llvm::FoldingSetNodeID ID;
3905  DependentTemplateName::Profile(ID, NNS, Operator);
3906
3907  void *InsertPos = 0;
3908  DependentTemplateName *QTN
3909    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3910
3911  if (QTN)
3912    return TemplateName(QTN);
3913
3914  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3915  if (CanonNNS == NNS) {
3916    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3917  } else {
3918    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3919    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3920
3921    DependentTemplateName *CheckQTN
3922      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3923    assert(!CheckQTN && "Dependent template name canonicalization broken");
3924    (void)CheckQTN;
3925  }
3926
3927  DependentTemplateNames.InsertNode(QTN, InsertPos);
3928  return TemplateName(QTN);
3929}
3930
3931/// getFromTargetType - Given one of the integer types provided by
3932/// TargetInfo, produce the corresponding type. The unsigned @p Type
3933/// is actually a value of type @c TargetInfo::IntType.
3934CanQualType ASTContext::getFromTargetType(unsigned Type) const {
3935  switch (Type) {
3936  case TargetInfo::NoInt: return CanQualType();
3937  case TargetInfo::SignedShort: return ShortTy;
3938  case TargetInfo::UnsignedShort: return UnsignedShortTy;
3939  case TargetInfo::SignedInt: return IntTy;
3940  case TargetInfo::UnsignedInt: return UnsignedIntTy;
3941  case TargetInfo::SignedLong: return LongTy;
3942  case TargetInfo::UnsignedLong: return UnsignedLongTy;
3943  case TargetInfo::SignedLongLong: return LongLongTy;
3944  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3945  }
3946
3947  assert(false && "Unhandled TargetInfo::IntType value");
3948  return CanQualType();
3949}
3950
3951//===----------------------------------------------------------------------===//
3952//                        Type Predicates.
3953//===----------------------------------------------------------------------===//
3954
3955/// isObjCNSObjectType - Return true if this is an NSObject object using
3956/// NSObject attribute on a c-style pointer type.
3957/// FIXME - Make it work directly on types.
3958/// FIXME: Move to Type.
3959///
3960bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3961  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3962    if (TypedefDecl *TD = TDT->getDecl())
3963      if (TD->getAttr<ObjCNSObjectAttr>())
3964        return true;
3965  }
3966  return false;
3967}
3968
3969/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3970/// garbage collection attribute.
3971///
3972Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3973  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
3974  if (getLangOptions().ObjC1 &&
3975      getLangOptions().getGCMode() != LangOptions::NonGC) {
3976    GCAttrs = Ty.getObjCGCAttr();
3977    // Default behavious under objective-c's gc is for objective-c pointers
3978    // (or pointers to them) be treated as though they were declared
3979    // as __strong.
3980    if (GCAttrs == Qualifiers::GCNone) {
3981      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
3982        GCAttrs = Qualifiers::Strong;
3983      else if (Ty->isPointerType())
3984        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
3985    }
3986    // Non-pointers have none gc'able attribute regardless of the attribute
3987    // set on them.
3988    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
3989      return Qualifiers::GCNone;
3990  }
3991  return GCAttrs;
3992}
3993
3994//===----------------------------------------------------------------------===//
3995//                        Type Compatibility Testing
3996//===----------------------------------------------------------------------===//
3997
3998/// areCompatVectorTypes - Return true if the two specified vector types are
3999/// compatible.
4000static bool areCompatVectorTypes(const VectorType *LHS,
4001                                 const VectorType *RHS) {
4002  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
4003  return LHS->getElementType() == RHS->getElementType() &&
4004         LHS->getNumElements() == RHS->getNumElements();
4005}
4006
4007//===----------------------------------------------------------------------===//
4008// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
4009//===----------------------------------------------------------------------===//
4010
4011/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
4012/// inheritance hierarchy of 'rProto'.
4013bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
4014                                                ObjCProtocolDecl *rProto) {
4015  if (lProto == rProto)
4016    return true;
4017  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
4018       E = rProto->protocol_end(); PI != E; ++PI)
4019    if (ProtocolCompatibleWithProtocol(lProto, *PI))
4020      return true;
4021  return false;
4022}
4023
4024/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
4025/// return true if lhs's protocols conform to rhs's protocol; false
4026/// otherwise.
4027bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
4028  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
4029    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
4030  return false;
4031}
4032
4033/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
4034/// ObjCQualifiedIDType.
4035bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
4036                                                   bool compare) {
4037  // Allow id<P..> and an 'id' or void* type in all cases.
4038  if (lhs->isVoidPointerType() ||
4039      lhs->isObjCIdType() || lhs->isObjCClassType())
4040    return true;
4041  else if (rhs->isVoidPointerType() ||
4042           rhs->isObjCIdType() || rhs->isObjCClassType())
4043    return true;
4044
4045  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
4046    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
4047
4048    if (!rhsOPT) return false;
4049
4050    if (rhsOPT->qual_empty()) {
4051      // If the RHS is a unqualified interface pointer "NSString*",
4052      // make sure we check the class hierarchy.
4053      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4054        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4055             E = lhsQID->qual_end(); I != E; ++I) {
4056          // when comparing an id<P> on lhs with a static type on rhs,
4057          // see if static class implements all of id's protocols, directly or
4058          // through its super class and categories.
4059          if (!rhsID->ClassImplementsProtocol(*I, true))
4060            return false;
4061        }
4062      }
4063      // If there are no qualifiers and no interface, we have an 'id'.
4064      return true;
4065    }
4066    // Both the right and left sides have qualifiers.
4067    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4068         E = lhsQID->qual_end(); I != E; ++I) {
4069      ObjCProtocolDecl *lhsProto = *I;
4070      bool match = false;
4071
4072      // when comparing an id<P> on lhs with a static type on rhs,
4073      // see if static class implements all of id's protocols, directly or
4074      // through its super class and categories.
4075      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4076           E = rhsOPT->qual_end(); J != E; ++J) {
4077        ObjCProtocolDecl *rhsProto = *J;
4078        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4079            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4080          match = true;
4081          break;
4082        }
4083      }
4084      // If the RHS is a qualified interface pointer "NSString<P>*",
4085      // make sure we check the class hierarchy.
4086      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4087        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4088             E = lhsQID->qual_end(); I != E; ++I) {
4089          // when comparing an id<P> on lhs with a static type on rhs,
4090          // see if static class implements all of id's protocols, directly or
4091          // through its super class and categories.
4092          if (rhsID->ClassImplementsProtocol(*I, true)) {
4093            match = true;
4094            break;
4095          }
4096        }
4097      }
4098      if (!match)
4099        return false;
4100    }
4101
4102    return true;
4103  }
4104
4105  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4106  assert(rhsQID && "One of the LHS/RHS should be id<x>");
4107
4108  if (const ObjCObjectPointerType *lhsOPT =
4109        lhs->getAsObjCInterfacePointerType()) {
4110    if (lhsOPT->qual_empty()) {
4111      bool match = false;
4112      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4113        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4114             E = rhsQID->qual_end(); I != E; ++I) {
4115          // when comparing an id<P> on lhs with a static type on rhs,
4116          // see if static class implements all of id's protocols, directly or
4117          // through its super class and categories.
4118          if (lhsID->ClassImplementsProtocol(*I, true)) {
4119            match = true;
4120            break;
4121          }
4122        }
4123        if (!match)
4124          return false;
4125      }
4126      return true;
4127    }
4128    // Both the right and left sides have qualifiers.
4129    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4130         E = lhsOPT->qual_end(); I != E; ++I) {
4131      ObjCProtocolDecl *lhsProto = *I;
4132      bool match = false;
4133
4134      // when comparing an id<P> on lhs with a static type on rhs,
4135      // see if static class implements all of id's protocols, directly or
4136      // through its super class and categories.
4137      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4138           E = rhsQID->qual_end(); J != E; ++J) {
4139        ObjCProtocolDecl *rhsProto = *J;
4140        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4141            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4142          match = true;
4143          break;
4144        }
4145      }
4146      if (!match)
4147        return false;
4148    }
4149    return true;
4150  }
4151  return false;
4152}
4153
4154/// canAssignObjCInterfaces - Return true if the two interface types are
4155/// compatible for assignment from RHS to LHS.  This handles validation of any
4156/// protocol qualifiers on the LHS or RHS.
4157///
4158bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4159                                         const ObjCObjectPointerType *RHSOPT) {
4160  // If either type represents the built-in 'id' or 'Class' types, return true.
4161  if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
4162    return true;
4163
4164  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4165    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4166                                             QualType(RHSOPT,0),
4167                                             false);
4168
4169  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4170  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4171  if (LHS && RHS) // We have 2 user-defined types.
4172    return canAssignObjCInterfaces(LHS, RHS);
4173
4174  return false;
4175}
4176
4177/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4178/// for providing type-safty for objective-c pointers used to pass/return
4179/// arguments in block literals. When passed as arguments, passing 'A*' where
4180/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4181/// not OK. For the return type, the opposite is not OK.
4182bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4183                                         const ObjCObjectPointerType *LHSOPT,
4184                                         const ObjCObjectPointerType *RHSOPT) {
4185  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
4186    return true;
4187
4188  if (LHSOPT->isObjCBuiltinType()) {
4189    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4190  }
4191
4192  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4193    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4194                                             QualType(RHSOPT,0),
4195                                             false);
4196
4197  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4198  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4199  if (LHS && RHS)  { // We have 2 user-defined types.
4200    if (LHS != RHS) {
4201      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4202        return false;
4203      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4204        return true;
4205    }
4206    else
4207      return true;
4208  }
4209  return false;
4210}
4211
4212/// getIntersectionOfProtocols - This routine finds the intersection of set
4213/// of protocols inherited from two distinct objective-c pointer objects.
4214/// It is used to build composite qualifier list of the composite type of
4215/// the conditional expression involving two objective-c pointer objects.
4216static
4217void getIntersectionOfProtocols(ASTContext &Context,
4218                                const ObjCObjectPointerType *LHSOPT,
4219                                const ObjCObjectPointerType *RHSOPT,
4220      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4221
4222  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4223  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4224
4225  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4226  unsigned LHSNumProtocols = LHS->getNumProtocols();
4227  if (LHSNumProtocols > 0)
4228    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4229  else {
4230    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4231    Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4232    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4233                                LHSInheritedProtocols.end());
4234  }
4235
4236  unsigned RHSNumProtocols = RHS->getNumProtocols();
4237  if (RHSNumProtocols > 0) {
4238    ObjCProtocolDecl **RHSProtocols =
4239      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
4240    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4241      if (InheritedProtocolSet.count(RHSProtocols[i]))
4242        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4243  }
4244  else {
4245    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4246    Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4247    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4248         RHSInheritedProtocols.begin(),
4249         E = RHSInheritedProtocols.end(); I != E; ++I)
4250      if (InheritedProtocolSet.count((*I)))
4251        IntersectionOfProtocols.push_back((*I));
4252  }
4253}
4254
4255/// areCommonBaseCompatible - Returns common base class of the two classes if
4256/// one found. Note that this is O'2 algorithm. But it will be called as the
4257/// last type comparison in a ?-exp of ObjC pointer types before a
4258/// warning is issued. So, its invokation is extremely rare.
4259QualType ASTContext::areCommonBaseCompatible(
4260                                          const ObjCObjectPointerType *LHSOPT,
4261                                          const ObjCObjectPointerType *RHSOPT) {
4262  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4263  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4264  if (!LHS || !RHS)
4265    return QualType();
4266
4267  while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4268    QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4269    LHS = LHSTy->getAs<ObjCInterfaceType>();
4270    if (canAssignObjCInterfaces(LHS, RHS)) {
4271      llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4272      getIntersectionOfProtocols(*this,
4273                                 LHSOPT, RHSOPT, IntersectionOfProtocols);
4274      if (IntersectionOfProtocols.empty())
4275        LHSTy = getObjCObjectPointerType(LHSTy);
4276      else
4277        LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4278                                                IntersectionOfProtocols.size());
4279      return LHSTy;
4280    }
4281  }
4282
4283  return QualType();
4284}
4285
4286bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4287                                         const ObjCInterfaceType *RHS) {
4288  // Verify that the base decls are compatible: the RHS must be a subclass of
4289  // the LHS.
4290  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4291    return false;
4292
4293  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
4294  // protocol qualified at all, then we are good.
4295  if (LHS->getNumProtocols() == 0)
4296    return true;
4297
4298  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
4299  // isn't a superset.
4300  if (RHS->getNumProtocols() == 0)
4301    return true;  // FIXME: should return false!
4302
4303  for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4304                                        LHSPE = LHS->qual_end();
4305       LHSPI != LHSPE; LHSPI++) {
4306    bool RHSImplementsProtocol = false;
4307
4308    // If the RHS doesn't implement the protocol on the left, the types
4309    // are incompatible.
4310    for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
4311                                          RHSPE = RHS->qual_end();
4312         RHSPI != RHSPE; RHSPI++) {
4313      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
4314        RHSImplementsProtocol = true;
4315        break;
4316      }
4317    }
4318    // FIXME: For better diagnostics, consider passing back the protocol name.
4319    if (!RHSImplementsProtocol)
4320      return false;
4321  }
4322  // The RHS implements all protocols listed on the LHS.
4323  return true;
4324}
4325
4326bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4327  // get the "pointed to" types
4328  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4329  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
4330
4331  if (!LHSOPT || !RHSOPT)
4332    return false;
4333
4334  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4335         canAssignObjCInterfaces(RHSOPT, LHSOPT);
4336}
4337
4338/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
4339/// both shall have the identically qualified version of a compatible type.
4340/// C99 6.2.7p1: Two types have compatible types if their types are the
4341/// same. See 6.7.[2,3,5] for additional rules.
4342bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4343  if (getLangOptions().CPlusPlus)
4344    return hasSameType(LHS, RHS);
4345
4346  return !mergeTypes(LHS, RHS).isNull();
4347}
4348
4349bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4350  return !mergeTypes(LHS, RHS, true).isNull();
4351}
4352
4353QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4354                                        bool OfBlockPointer) {
4355  const FunctionType *lbase = lhs->getAs<FunctionType>();
4356  const FunctionType *rbase = rhs->getAs<FunctionType>();
4357  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4358  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
4359  bool allLTypes = true;
4360  bool allRTypes = true;
4361
4362  // Check return type
4363  QualType retType;
4364  if (OfBlockPointer)
4365    retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4366  else
4367   retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4368  if (retType.isNull()) return QualType();
4369  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4370    allLTypes = false;
4371  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4372    allRTypes = false;
4373  // FIXME: double check this
4374  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4375  //                           rbase->getRegParmAttr() != 0 &&
4376  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
4377  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4378  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
4379  unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4380      lbaseInfo.getRegParm();
4381  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4382  if (NoReturn != lbaseInfo.getNoReturn() ||
4383      RegParm != lbaseInfo.getRegParm())
4384    allLTypes = false;
4385  if (NoReturn != rbaseInfo.getNoReturn() ||
4386      RegParm != rbaseInfo.getRegParm())
4387    allRTypes = false;
4388  CallingConv lcc = lbaseInfo.getCC();
4389  CallingConv rcc = rbaseInfo.getCC();
4390  // Compatible functions must have compatible calling conventions
4391  if (!isSameCallConv(lcc, rcc))
4392    return QualType();
4393
4394  if (lproto && rproto) { // two C99 style function prototypes
4395    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4396           "C++ shouldn't be here");
4397    unsigned lproto_nargs = lproto->getNumArgs();
4398    unsigned rproto_nargs = rproto->getNumArgs();
4399
4400    // Compatible functions must have the same number of arguments
4401    if (lproto_nargs != rproto_nargs)
4402      return QualType();
4403
4404    // Variadic and non-variadic functions aren't compatible
4405    if (lproto->isVariadic() != rproto->isVariadic())
4406      return QualType();
4407
4408    if (lproto->getTypeQuals() != rproto->getTypeQuals())
4409      return QualType();
4410
4411    // Check argument compatibility
4412    llvm::SmallVector<QualType, 10> types;
4413    for (unsigned i = 0; i < lproto_nargs; i++) {
4414      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4415      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4416      QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
4417      if (argtype.isNull()) return QualType();
4418      types.push_back(argtype);
4419      if (getCanonicalType(argtype) != getCanonicalType(largtype))
4420        allLTypes = false;
4421      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4422        allRTypes = false;
4423    }
4424    if (allLTypes) return lhs;
4425    if (allRTypes) return rhs;
4426    return getFunctionType(retType, types.begin(), types.size(),
4427                           lproto->isVariadic(), lproto->getTypeQuals(),
4428                           false, false, 0, 0,
4429                           FunctionType::ExtInfo(NoReturn, RegParm, lcc));
4430  }
4431
4432  if (lproto) allRTypes = false;
4433  if (rproto) allLTypes = false;
4434
4435  const FunctionProtoType *proto = lproto ? lproto : rproto;
4436  if (proto) {
4437    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
4438    if (proto->isVariadic()) return QualType();
4439    // Check that the types are compatible with the types that
4440    // would result from default argument promotions (C99 6.7.5.3p15).
4441    // The only types actually affected are promotable integer
4442    // types and floats, which would be passed as a different
4443    // type depending on whether the prototype is visible.
4444    unsigned proto_nargs = proto->getNumArgs();
4445    for (unsigned i = 0; i < proto_nargs; ++i) {
4446      QualType argTy = proto->getArgType(i);
4447
4448      // Look at the promotion type of enum types, since that is the type used
4449      // to pass enum values.
4450      if (const EnumType *Enum = argTy->getAs<EnumType>())
4451        argTy = Enum->getDecl()->getPromotionType();
4452
4453      if (argTy->isPromotableIntegerType() ||
4454          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4455        return QualType();
4456    }
4457
4458    if (allLTypes) return lhs;
4459    if (allRTypes) return rhs;
4460    return getFunctionType(retType, proto->arg_type_begin(),
4461                           proto->getNumArgs(), proto->isVariadic(),
4462                           proto->getTypeQuals(),
4463                           false, false, 0, 0,
4464                           FunctionType::ExtInfo(NoReturn, RegParm, lcc));
4465  }
4466
4467  if (allLTypes) return lhs;
4468  if (allRTypes) return rhs;
4469  FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
4470  return getFunctionNoProtoType(retType, Info);
4471}
4472
4473QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4474                                bool OfBlockPointer) {
4475  // C++ [expr]: If an expression initially has the type "reference to T", the
4476  // type is adjusted to "T" prior to any further analysis, the expression
4477  // designates the object or function denoted by the reference, and the
4478  // expression is an lvalue unless the reference is an rvalue reference and
4479  // the expression is a function call (possibly inside parentheses).
4480  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4481  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4482
4483  QualType LHSCan = getCanonicalType(LHS),
4484           RHSCan = getCanonicalType(RHS);
4485
4486  // If two types are identical, they are compatible.
4487  if (LHSCan == RHSCan)
4488    return LHS;
4489
4490  // If the qualifiers are different, the types aren't compatible... mostly.
4491  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4492  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4493  if (LQuals != RQuals) {
4494    // If any of these qualifiers are different, we have a type
4495    // mismatch.
4496    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4497        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4498      return QualType();
4499
4500    // Exactly one GC qualifier difference is allowed: __strong is
4501    // okay if the other type has no GC qualifier but is an Objective
4502    // C object pointer (i.e. implicitly strong by default).  We fix
4503    // this by pretending that the unqualified type was actually
4504    // qualified __strong.
4505    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4506    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4507    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4508
4509    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4510      return QualType();
4511
4512    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4513      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4514    }
4515    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4516      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4517    }
4518    return QualType();
4519  }
4520
4521  // Okay, qualifiers are equal.
4522
4523  Type::TypeClass LHSClass = LHSCan->getTypeClass();
4524  Type::TypeClass RHSClass = RHSCan->getTypeClass();
4525
4526  // We want to consider the two function types to be the same for these
4527  // comparisons, just force one to the other.
4528  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4529  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
4530
4531  // Same as above for arrays
4532  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4533    LHSClass = Type::ConstantArray;
4534  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4535    RHSClass = Type::ConstantArray;
4536
4537  // Canonicalize ExtVector -> Vector.
4538  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4539  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
4540
4541  // If the canonical type classes don't match.
4542  if (LHSClass != RHSClass) {
4543    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
4544    // a signed integer type, or an unsigned integer type.
4545    // Compatibility is based on the underlying type, not the promotion
4546    // type.
4547    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
4548      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4549        return RHS;
4550    }
4551    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
4552      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4553        return LHS;
4554    }
4555
4556    return QualType();
4557  }
4558
4559  // The canonical type classes match.
4560  switch (LHSClass) {
4561#define TYPE(Class, Base)
4562#define ABSTRACT_TYPE(Class, Base)
4563#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4564#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4565#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4566#include "clang/AST/TypeNodes.def"
4567    assert(false && "Non-canonical and dependent types shouldn't get here");
4568    return QualType();
4569
4570  case Type::LValueReference:
4571  case Type::RValueReference:
4572  case Type::MemberPointer:
4573    assert(false && "C++ should never be in mergeTypes");
4574    return QualType();
4575
4576  case Type::IncompleteArray:
4577  case Type::VariableArray:
4578  case Type::FunctionProto:
4579  case Type::ExtVector:
4580    assert(false && "Types are eliminated above");
4581    return QualType();
4582
4583  case Type::Pointer:
4584  {
4585    // Merge two pointer types, while trying to preserve typedef info
4586    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4587    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
4588    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4589    if (ResultType.isNull()) return QualType();
4590    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4591      return LHS;
4592    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4593      return RHS;
4594    return getPointerType(ResultType);
4595  }
4596  case Type::BlockPointer:
4597  {
4598    // Merge two block pointer types, while trying to preserve typedef info
4599    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4600    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
4601    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
4602    if (ResultType.isNull()) return QualType();
4603    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4604      return LHS;
4605    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4606      return RHS;
4607    return getBlockPointerType(ResultType);
4608  }
4609  case Type::ConstantArray:
4610  {
4611    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4612    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4613    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4614      return QualType();
4615
4616    QualType LHSElem = getAsArrayType(LHS)->getElementType();
4617    QualType RHSElem = getAsArrayType(RHS)->getElementType();
4618    QualType ResultType = mergeTypes(LHSElem, RHSElem);
4619    if (ResultType.isNull()) return QualType();
4620    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4621      return LHS;
4622    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4623      return RHS;
4624    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4625                                          ArrayType::ArraySizeModifier(), 0);
4626    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4627                                          ArrayType::ArraySizeModifier(), 0);
4628    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4629    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
4630    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4631      return LHS;
4632    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4633      return RHS;
4634    if (LVAT) {
4635      // FIXME: This isn't correct! But tricky to implement because
4636      // the array's size has to be the size of LHS, but the type
4637      // has to be different.
4638      return LHS;
4639    }
4640    if (RVAT) {
4641      // FIXME: This isn't correct! But tricky to implement because
4642      // the array's size has to be the size of RHS, but the type
4643      // has to be different.
4644      return RHS;
4645    }
4646    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4647    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
4648    return getIncompleteArrayType(ResultType,
4649                                  ArrayType::ArraySizeModifier(), 0);
4650  }
4651  case Type::FunctionNoProto:
4652    return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
4653  case Type::Record:
4654  case Type::Enum:
4655    return QualType();
4656  case Type::Builtin:
4657    // Only exactly equal builtin types are compatible, which is tested above.
4658    return QualType();
4659  case Type::Complex:
4660    // Distinct complex types are incompatible.
4661    return QualType();
4662  case Type::Vector:
4663    // FIXME: The merged type should be an ExtVector!
4664    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4665                             RHSCan->getAs<VectorType>()))
4666      return LHS;
4667    return QualType();
4668  case Type::ObjCInterface: {
4669    // Check if the interfaces are assignment compatible.
4670    // FIXME: This should be type compatibility, e.g. whether
4671    // "LHS x; RHS x;" at global scope is legal.
4672    const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4673    const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
4674    if (LHSIface && RHSIface &&
4675        canAssignObjCInterfaces(LHSIface, RHSIface))
4676      return LHS;
4677
4678    return QualType();
4679  }
4680  case Type::ObjCObjectPointer: {
4681    if (OfBlockPointer) {
4682      if (canAssignObjCInterfacesInBlockPointer(
4683                                          LHS->getAs<ObjCObjectPointerType>(),
4684                                          RHS->getAs<ObjCObjectPointerType>()))
4685      return LHS;
4686      return QualType();
4687    }
4688    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4689                                RHS->getAs<ObjCObjectPointerType>()))
4690      return LHS;
4691
4692    return QualType();
4693    }
4694  }
4695
4696  return QualType();
4697}
4698
4699//===----------------------------------------------------------------------===//
4700//                         Integer Predicates
4701//===----------------------------------------------------------------------===//
4702
4703unsigned ASTContext::getIntWidth(QualType T) {
4704  if (T->isBooleanType())
4705    return 1;
4706  if (EnumType *ET = dyn_cast<EnumType>(T))
4707    T = ET->getDecl()->getIntegerType();
4708  // For builtin types, just use the standard type sizing method
4709  return (unsigned)getTypeSize(T);
4710}
4711
4712QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4713  assert(T->isSignedIntegerType() && "Unexpected type");
4714
4715  // Turn <4 x signed int> -> <4 x unsigned int>
4716  if (const VectorType *VTy = T->getAs<VectorType>())
4717    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4718             VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
4719
4720  // For enums, we return the unsigned version of the base type.
4721  if (const EnumType *ETy = T->getAs<EnumType>())
4722    T = ETy->getDecl()->getIntegerType();
4723
4724  const BuiltinType *BTy = T->getAs<BuiltinType>();
4725  assert(BTy && "Unexpected signed integer type");
4726  switch (BTy->getKind()) {
4727  case BuiltinType::Char_S:
4728  case BuiltinType::SChar:
4729    return UnsignedCharTy;
4730  case BuiltinType::Short:
4731    return UnsignedShortTy;
4732  case BuiltinType::Int:
4733    return UnsignedIntTy;
4734  case BuiltinType::Long:
4735    return UnsignedLongTy;
4736  case BuiltinType::LongLong:
4737    return UnsignedLongLongTy;
4738  case BuiltinType::Int128:
4739    return UnsignedInt128Ty;
4740  default:
4741    assert(0 && "Unexpected signed integer type");
4742    return QualType();
4743  }
4744}
4745
4746ExternalASTSource::~ExternalASTSource() { }
4747
4748void ExternalASTSource::PrintStats() { }
4749
4750
4751//===----------------------------------------------------------------------===//
4752//                          Builtin Type Computation
4753//===----------------------------------------------------------------------===//
4754
4755/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4756/// pointer over the consumed characters.  This returns the resultant type.
4757static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4758                                  ASTContext::GetBuiltinTypeError &Error,
4759                                  bool AllowTypeModifiers = true) {
4760  // Modifiers.
4761  int HowLong = 0;
4762  bool Signed = false, Unsigned = false;
4763
4764  // Read the modifiers first.
4765  bool Done = false;
4766  while (!Done) {
4767    switch (*Str++) {
4768    default: Done = true; --Str; break;
4769    case 'S':
4770      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4771      assert(!Signed && "Can't use 'S' modifier multiple times!");
4772      Signed = true;
4773      break;
4774    case 'U':
4775      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4776      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4777      Unsigned = true;
4778      break;
4779    case 'L':
4780      assert(HowLong <= 2 && "Can't have LLLL modifier");
4781      ++HowLong;
4782      break;
4783    }
4784  }
4785
4786  QualType Type;
4787
4788  // Read the base type.
4789  switch (*Str++) {
4790  default: assert(0 && "Unknown builtin type letter!");
4791  case 'v':
4792    assert(HowLong == 0 && !Signed && !Unsigned &&
4793           "Bad modifiers used with 'v'!");
4794    Type = Context.VoidTy;
4795    break;
4796  case 'f':
4797    assert(HowLong == 0 && !Signed && !Unsigned &&
4798           "Bad modifiers used with 'f'!");
4799    Type = Context.FloatTy;
4800    break;
4801  case 'd':
4802    assert(HowLong < 2 && !Signed && !Unsigned &&
4803           "Bad modifiers used with 'd'!");
4804    if (HowLong)
4805      Type = Context.LongDoubleTy;
4806    else
4807      Type = Context.DoubleTy;
4808    break;
4809  case 's':
4810    assert(HowLong == 0 && "Bad modifiers used with 's'!");
4811    if (Unsigned)
4812      Type = Context.UnsignedShortTy;
4813    else
4814      Type = Context.ShortTy;
4815    break;
4816  case 'i':
4817    if (HowLong == 3)
4818      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4819    else if (HowLong == 2)
4820      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4821    else if (HowLong == 1)
4822      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4823    else
4824      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4825    break;
4826  case 'c':
4827    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4828    if (Signed)
4829      Type = Context.SignedCharTy;
4830    else if (Unsigned)
4831      Type = Context.UnsignedCharTy;
4832    else
4833      Type = Context.CharTy;
4834    break;
4835  case 'b': // boolean
4836    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4837    Type = Context.BoolTy;
4838    break;
4839  case 'z':  // size_t.
4840    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4841    Type = Context.getSizeType();
4842    break;
4843  case 'F':
4844    Type = Context.getCFConstantStringType();
4845    break;
4846  case 'a':
4847    Type = Context.getBuiltinVaListType();
4848    assert(!Type.isNull() && "builtin va list type not initialized!");
4849    break;
4850  case 'A':
4851    // This is a "reference" to a va_list; however, what exactly
4852    // this means depends on how va_list is defined. There are two
4853    // different kinds of va_list: ones passed by value, and ones
4854    // passed by reference.  An example of a by-value va_list is
4855    // x86, where va_list is a char*. An example of by-ref va_list
4856    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4857    // we want this argument to be a char*&; for x86-64, we want
4858    // it to be a __va_list_tag*.
4859    Type = Context.getBuiltinVaListType();
4860    assert(!Type.isNull() && "builtin va list type not initialized!");
4861    if (Type->isArrayType()) {
4862      Type = Context.getArrayDecayedType(Type);
4863    } else {
4864      Type = Context.getLValueReferenceType(Type);
4865    }
4866    break;
4867  case 'V': {
4868    char *End;
4869    unsigned NumElements = strtoul(Str, &End, 10);
4870    assert(End != Str && "Missing vector size");
4871
4872    Str = End;
4873
4874    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4875    // FIXME: Don't know what to do about AltiVec.
4876    Type = Context.getVectorType(ElementType, NumElements, false, false);
4877    break;
4878  }
4879  case 'X': {
4880    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4881    Type = Context.getComplexType(ElementType);
4882    break;
4883  }
4884  case 'P':
4885    Type = Context.getFILEType();
4886    if (Type.isNull()) {
4887      Error = ASTContext::GE_Missing_stdio;
4888      return QualType();
4889    }
4890    break;
4891  case 'J':
4892    if (Signed)
4893      Type = Context.getsigjmp_bufType();
4894    else
4895      Type = Context.getjmp_bufType();
4896
4897    if (Type.isNull()) {
4898      Error = ASTContext::GE_Missing_setjmp;
4899      return QualType();
4900    }
4901    break;
4902  }
4903
4904  if (!AllowTypeModifiers)
4905    return Type;
4906
4907  Done = false;
4908  while (!Done) {
4909    switch (char c = *Str++) {
4910      default: Done = true; --Str; break;
4911      case '*':
4912      case '&':
4913        {
4914          // Both pointers and references can have their pointee types
4915          // qualified with an address space.
4916          char *End;
4917          unsigned AddrSpace = strtoul(Str, &End, 10);
4918          if (End != Str && AddrSpace != 0) {
4919            Type = Context.getAddrSpaceQualType(Type, AddrSpace);
4920            Str = End;
4921          }
4922        }
4923        if (c == '*')
4924          Type = Context.getPointerType(Type);
4925        else
4926          Type = Context.getLValueReferenceType(Type);
4927        break;
4928      // FIXME: There's no way to have a built-in with an rvalue ref arg.
4929      case 'C':
4930        Type = Type.withConst();
4931        break;
4932      case 'D':
4933        Type = Context.getVolatileType(Type);
4934        break;
4935    }
4936  }
4937
4938  return Type;
4939}
4940
4941/// GetBuiltinType - Return the type for the specified builtin.
4942QualType ASTContext::GetBuiltinType(unsigned id,
4943                                    GetBuiltinTypeError &Error) {
4944  const char *TypeStr = BuiltinInfo.GetTypeString(id);
4945
4946  llvm::SmallVector<QualType, 8> ArgTypes;
4947
4948  Error = GE_None;
4949  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4950  if (Error != GE_None)
4951    return QualType();
4952  while (TypeStr[0] && TypeStr[0] != '.') {
4953    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4954    if (Error != GE_None)
4955      return QualType();
4956
4957    // Do array -> pointer decay.  The builtin should use the decayed type.
4958    if (Ty->isArrayType())
4959      Ty = getArrayDecayedType(Ty);
4960
4961    ArgTypes.push_back(Ty);
4962  }
4963
4964  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4965         "'.' should only occur at end of builtin type list!");
4966
4967  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4968  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4969    return getFunctionNoProtoType(ResType);
4970
4971  // FIXME: Should we create noreturn types?
4972  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4973                         TypeStr[0] == '.', 0, false, false, 0, 0,
4974                         FunctionType::ExtInfo());
4975}
4976
4977QualType
4978ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4979  // Perform the usual unary conversions. We do this early so that
4980  // integral promotions to "int" can allow us to exit early, in the
4981  // lhs == rhs check. Also, for conversion purposes, we ignore any
4982  // qualifiers.  For example, "const float" and "float" are
4983  // equivalent.
4984  if (lhs->isPromotableIntegerType())
4985    lhs = getPromotedIntegerType(lhs);
4986  else
4987    lhs = lhs.getUnqualifiedType();
4988  if (rhs->isPromotableIntegerType())
4989    rhs = getPromotedIntegerType(rhs);
4990  else
4991    rhs = rhs.getUnqualifiedType();
4992
4993  // If both types are identical, no conversion is needed.
4994  if (lhs == rhs)
4995    return lhs;
4996
4997  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4998  // The caller can deal with this (e.g. pointer + int).
4999  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
5000    return lhs;
5001
5002  // At this point, we have two different arithmetic types.
5003
5004  // Handle complex types first (C99 6.3.1.8p1).
5005  if (lhs->isComplexType() || rhs->isComplexType()) {
5006    // if we have an integer operand, the result is the complex type.
5007    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
5008      // convert the rhs to the lhs complex type.
5009      return lhs;
5010    }
5011    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
5012      // convert the lhs to the rhs complex type.
5013      return rhs;
5014    }
5015    // This handles complex/complex, complex/float, or float/complex.
5016    // When both operands are complex, the shorter operand is converted to the
5017    // type of the longer, and that is the type of the result. This corresponds
5018    // to what is done when combining two real floating-point operands.
5019    // The fun begins when size promotion occur across type domains.
5020    // From H&S 6.3.4: When one operand is complex and the other is a real
5021    // floating-point type, the less precise type is converted, within it's
5022    // real or complex domain, to the precision of the other type. For example,
5023    // when combining a "long double" with a "double _Complex", the
5024    // "double _Complex" is promoted to "long double _Complex".
5025    int result = getFloatingTypeOrder(lhs, rhs);
5026
5027    if (result > 0) { // The left side is bigger, convert rhs.
5028      rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
5029    } else if (result < 0) { // The right side is bigger, convert lhs.
5030      lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
5031    }
5032    // At this point, lhs and rhs have the same rank/size. Now, make sure the
5033    // domains match. This is a requirement for our implementation, C99
5034    // does not require this promotion.
5035    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
5036      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
5037        return rhs;
5038      } else { // handle "_Complex double, double".
5039        return lhs;
5040      }
5041    }
5042    return lhs; // The domain/size match exactly.
5043  }
5044  // Now handle "real" floating types (i.e. float, double, long double).
5045  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
5046    // if we have an integer operand, the result is the real floating type.
5047    if (rhs->isIntegerType()) {
5048      // convert rhs to the lhs floating point type.
5049      return lhs;
5050    }
5051    if (rhs->isComplexIntegerType()) {
5052      // convert rhs to the complex floating point type.
5053      return getComplexType(lhs);
5054    }
5055    if (lhs->isIntegerType()) {
5056      // convert lhs to the rhs floating point type.
5057      return rhs;
5058    }
5059    if (lhs->isComplexIntegerType()) {
5060      // convert lhs to the complex floating point type.
5061      return getComplexType(rhs);
5062    }
5063    // We have two real floating types, float/complex combos were handled above.
5064    // Convert the smaller operand to the bigger result.
5065    int result = getFloatingTypeOrder(lhs, rhs);
5066    if (result > 0) // convert the rhs
5067      return lhs;
5068    assert(result < 0 && "illegal float comparison");
5069    return rhs;   // convert the lhs
5070  }
5071  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5072    // Handle GCC complex int extension.
5073    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5074    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5075
5076    if (lhsComplexInt && rhsComplexInt) {
5077      if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
5078                              rhsComplexInt->getElementType()) >= 0)
5079        return lhs; // convert the rhs
5080      return rhs;
5081    } else if (lhsComplexInt && rhs->isIntegerType()) {
5082      // convert the rhs to the lhs complex type.
5083      return lhs;
5084    } else if (rhsComplexInt && lhs->isIntegerType()) {
5085      // convert the lhs to the rhs complex type.
5086      return rhs;
5087    }
5088  }
5089  // Finally, we have two differing integer types.
5090  // The rules for this case are in C99 6.3.1.8
5091  int compare = getIntegerTypeOrder(lhs, rhs);
5092  bool lhsSigned = lhs->isSignedIntegerType(),
5093       rhsSigned = rhs->isSignedIntegerType();
5094  QualType destType;
5095  if (lhsSigned == rhsSigned) {
5096    // Same signedness; use the higher-ranked type
5097    destType = compare >= 0 ? lhs : rhs;
5098  } else if (compare != (lhsSigned ? 1 : -1)) {
5099    // The unsigned type has greater than or equal rank to the
5100    // signed type, so use the unsigned type
5101    destType = lhsSigned ? rhs : lhs;
5102  } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5103    // The two types are different widths; if we are here, that
5104    // means the signed type is larger than the unsigned type, so
5105    // use the signed type.
5106    destType = lhsSigned ? lhs : rhs;
5107  } else {
5108    // The signed type is higher-ranked than the unsigned type,
5109    // but isn't actually any bigger (like unsigned int and long
5110    // on most 32-bit systems).  Use the unsigned type corresponding
5111    // to the signed type.
5112    destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5113  }
5114  return destType;
5115}
5116