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