ASTContext.cpp revision 2888b65aae768f54062505330df7be230a0510c7
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    } else {
3597      S += '?';
3598    }
3599    if (ExpandStructures) {
3600      S += '=';
3601      for (RecordDecl::field_iterator Field = RDecl->field_begin(),
3602                                   FieldEnd = RDecl->field_end();
3603           Field != FieldEnd; ++Field) {
3604        if (FD) {
3605          S += '"';
3606          S += Field->getNameAsString();
3607          S += '"';
3608        }
3609
3610        // Special case bit-fields.
3611        if (Field->isBitField()) {
3612          getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
3613                                     (*Field));
3614        } else {
3615          QualType qt = Field->getType();
3616          getLegacyIntegralTypeEncoding(qt);
3617          getObjCEncodingForTypeImpl(qt, S, false, true,
3618                                     FD);
3619        }
3620      }
3621    }
3622    S += RDecl->isUnion() ? ')' : '}';
3623    return;
3624  }
3625
3626  if (T->isEnumeralType()) {
3627    if (FD && FD->isBitField())
3628      EncodeBitField(this, S, FD);
3629    else
3630      S += 'i';
3631    return;
3632  }
3633
3634  if (T->isBlockPointerType()) {
3635    S += "@?"; // Unlike a pointer-to-function, which is "^?".
3636    return;
3637  }
3638
3639  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
3640    // @encode(class_name)
3641    ObjCInterfaceDecl *OI = OIT->getDecl();
3642    S += '{';
3643    const IdentifierInfo *II = OI->getIdentifier();
3644    S += II->getName();
3645    S += '=';
3646    llvm::SmallVector<FieldDecl*, 32> RecFields;
3647    CollectObjCIvars(OI, RecFields);
3648    for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
3649      if (RecFields[i]->isBitField())
3650        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3651                                   RecFields[i]);
3652      else
3653        getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true,
3654                                   FD);
3655    }
3656    S += '}';
3657    return;
3658  }
3659
3660  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
3661    if (OPT->isObjCIdType()) {
3662      S += '@';
3663      return;
3664    }
3665
3666    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
3667      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
3668      // Since this is a binary compatibility issue, need to consult with runtime
3669      // folks. Fortunately, this is a *very* obsure construct.
3670      S += '#';
3671      return;
3672    }
3673
3674    if (OPT->isObjCQualifiedIdType()) {
3675      getObjCEncodingForTypeImpl(getObjCIdType(), S,
3676                                 ExpandPointedToStructures,
3677                                 ExpandStructures, FD);
3678      if (FD || EncodingProperty) {
3679        // Note that we do extended encoding of protocol qualifer list
3680        // Only when doing ivar or property encoding.
3681        S += '"';
3682        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3683             E = OPT->qual_end(); I != E; ++I) {
3684          S += '<';
3685          S += (*I)->getNameAsString();
3686          S += '>';
3687        }
3688        S += '"';
3689      }
3690      return;
3691    }
3692
3693    QualType PointeeTy = OPT->getPointeeType();
3694    if (!EncodingProperty &&
3695        isa<TypedefType>(PointeeTy.getTypePtr())) {
3696      // Another historical/compatibility reason.
3697      // We encode the underlying type which comes out as
3698      // {...};
3699      S += '^';
3700      getObjCEncodingForTypeImpl(PointeeTy, S,
3701                                 false, ExpandPointedToStructures,
3702                                 NULL);
3703      return;
3704    }
3705
3706    S += '@';
3707    if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) {
3708      S += '"';
3709      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
3710      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
3711           E = OPT->qual_end(); I != E; ++I) {
3712        S += '<';
3713        S += (*I)->getNameAsString();
3714        S += '>';
3715      }
3716      S += '"';
3717    }
3718    return;
3719  }
3720
3721  assert(0 && "@encode for type not implemented!");
3722}
3723
3724void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
3725                                                 std::string& S) const {
3726  if (QT & Decl::OBJC_TQ_In)
3727    S += 'n';
3728  if (QT & Decl::OBJC_TQ_Inout)
3729    S += 'N';
3730  if (QT & Decl::OBJC_TQ_Out)
3731    S += 'o';
3732  if (QT & Decl::OBJC_TQ_Bycopy)
3733    S += 'O';
3734  if (QT & Decl::OBJC_TQ_Byref)
3735    S += 'R';
3736  if (QT & Decl::OBJC_TQ_Oneway)
3737    S += 'V';
3738}
3739
3740void ASTContext::setBuiltinVaListType(QualType T) {
3741  assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!");
3742
3743  BuiltinVaListType = T;
3744}
3745
3746void ASTContext::setObjCIdType(QualType T) {
3747  ObjCIdTypedefType = T;
3748}
3749
3750void ASTContext::setObjCSelType(QualType T) {
3751  ObjCSelTypedefType = T;
3752}
3753
3754void ASTContext::setObjCProtoType(QualType QT) {
3755  ObjCProtoType = QT;
3756}
3757
3758void ASTContext::setObjCClassType(QualType T) {
3759  ObjCClassTypedefType = T;
3760}
3761
3762void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
3763  assert(ObjCConstantStringType.isNull() &&
3764         "'NSConstantString' type already set!");
3765
3766  ObjCConstantStringType = getObjCInterfaceType(Decl);
3767}
3768
3769/// \brief Retrieve the template name that corresponds to a non-empty
3770/// lookup.
3771TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
3772                                                   UnresolvedSetIterator End) {
3773  unsigned size = End - Begin;
3774  assert(size > 1 && "set is not overloaded!");
3775
3776  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
3777                          size * sizeof(FunctionTemplateDecl*));
3778  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
3779
3780  NamedDecl **Storage = OT->getStorage();
3781  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
3782    NamedDecl *D = *I;
3783    assert(isa<FunctionTemplateDecl>(D) ||
3784           (isa<UsingShadowDecl>(D) &&
3785            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
3786    *Storage++ = D;
3787  }
3788
3789  return TemplateName(OT);
3790}
3791
3792/// \brief Retrieve the template name that represents a qualified
3793/// template name such as \c std::vector.
3794TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
3795                                                  bool TemplateKeyword,
3796                                                  TemplateDecl *Template) {
3797  // FIXME: Canonicalization?
3798  llvm::FoldingSetNodeID ID;
3799  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
3800
3801  void *InsertPos = 0;
3802  QualifiedTemplateName *QTN =
3803    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3804  if (!QTN) {
3805    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
3806    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
3807  }
3808
3809  return TemplateName(QTN);
3810}
3811
3812/// \brief Retrieve the template name that represents a dependent
3813/// template name such as \c MetaFun::template apply.
3814TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3815                                                  const IdentifierInfo *Name) {
3816  assert((!NNS || NNS->isDependent()) &&
3817         "Nested name specifier must be dependent");
3818
3819  llvm::FoldingSetNodeID ID;
3820  DependentTemplateName::Profile(ID, NNS, Name);
3821
3822  void *InsertPos = 0;
3823  DependentTemplateName *QTN =
3824    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3825
3826  if (QTN)
3827    return TemplateName(QTN);
3828
3829  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3830  if (CanonNNS == NNS) {
3831    QTN = new (*this,4) DependentTemplateName(NNS, Name);
3832  } else {
3833    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
3834    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
3835    DependentTemplateName *CheckQTN =
3836      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3837    assert(!CheckQTN && "Dependent type name canonicalization broken");
3838    (void)CheckQTN;
3839  }
3840
3841  DependentTemplateNames.InsertNode(QTN, InsertPos);
3842  return TemplateName(QTN);
3843}
3844
3845/// \brief Retrieve the template name that represents a dependent
3846/// template name such as \c MetaFun::template operator+.
3847TemplateName
3848ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
3849                                     OverloadedOperatorKind Operator) {
3850  assert((!NNS || NNS->isDependent()) &&
3851         "Nested name specifier must be dependent");
3852
3853  llvm::FoldingSetNodeID ID;
3854  DependentTemplateName::Profile(ID, NNS, Operator);
3855
3856  void *InsertPos = 0;
3857  DependentTemplateName *QTN
3858    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3859
3860  if (QTN)
3861    return TemplateName(QTN);
3862
3863  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3864  if (CanonNNS == NNS) {
3865    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
3866  } else {
3867    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
3868    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
3869
3870    DependentTemplateName *CheckQTN
3871      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
3872    assert(!CheckQTN && "Dependent template name canonicalization broken");
3873    (void)CheckQTN;
3874  }
3875
3876  DependentTemplateNames.InsertNode(QTN, InsertPos);
3877  return TemplateName(QTN);
3878}
3879
3880/// getFromTargetType - Given one of the integer types provided by
3881/// TargetInfo, produce the corresponding type. The unsigned @p Type
3882/// is actually a value of type @c TargetInfo::IntType.
3883CanQualType ASTContext::getFromTargetType(unsigned Type) const {
3884  switch (Type) {
3885  case TargetInfo::NoInt: return CanQualType();
3886  case TargetInfo::SignedShort: return ShortTy;
3887  case TargetInfo::UnsignedShort: return UnsignedShortTy;
3888  case TargetInfo::SignedInt: return IntTy;
3889  case TargetInfo::UnsignedInt: return UnsignedIntTy;
3890  case TargetInfo::SignedLong: return LongTy;
3891  case TargetInfo::UnsignedLong: return UnsignedLongTy;
3892  case TargetInfo::SignedLongLong: return LongLongTy;
3893  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
3894  }
3895
3896  assert(false && "Unhandled TargetInfo::IntType value");
3897  return CanQualType();
3898}
3899
3900//===----------------------------------------------------------------------===//
3901//                        Type Predicates.
3902//===----------------------------------------------------------------------===//
3903
3904/// isObjCNSObjectType - Return true if this is an NSObject object using
3905/// NSObject attribute on a c-style pointer type.
3906/// FIXME - Make it work directly on types.
3907/// FIXME: Move to Type.
3908///
3909bool ASTContext::isObjCNSObjectType(QualType Ty) const {
3910  if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) {
3911    if (TypedefDecl *TD = TDT->getDecl())
3912      if (TD->getAttr<ObjCNSObjectAttr>())
3913        return true;
3914  }
3915  return false;
3916}
3917
3918/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
3919/// garbage collection attribute.
3920///
3921Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const {
3922  Qualifiers::GC GCAttrs = Qualifiers::GCNone;
3923  if (getLangOptions().ObjC1 &&
3924      getLangOptions().getGCMode() != LangOptions::NonGC) {
3925    GCAttrs = Ty.getObjCGCAttr();
3926    // Default behavious under objective-c's gc is for objective-c pointers
3927    // (or pointers to them) be treated as though they were declared
3928    // as __strong.
3929    if (GCAttrs == Qualifiers::GCNone) {
3930      if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
3931        GCAttrs = Qualifiers::Strong;
3932      else if (Ty->isPointerType())
3933        return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
3934    }
3935    // Non-pointers have none gc'able attribute regardless of the attribute
3936    // set on them.
3937    else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType())
3938      return Qualifiers::GCNone;
3939  }
3940  return GCAttrs;
3941}
3942
3943//===----------------------------------------------------------------------===//
3944//                        Type Compatibility Testing
3945//===----------------------------------------------------------------------===//
3946
3947/// areCompatVectorTypes - Return true if the two specified vector types are
3948/// compatible.
3949static bool areCompatVectorTypes(const VectorType *LHS,
3950                                 const VectorType *RHS) {
3951  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
3952  return LHS->getElementType() == RHS->getElementType() &&
3953         LHS->getNumElements() == RHS->getNumElements();
3954}
3955
3956//===----------------------------------------------------------------------===//
3957// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
3958//===----------------------------------------------------------------------===//
3959
3960/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
3961/// inheritance hierarchy of 'rProto'.
3962bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
3963                                                ObjCProtocolDecl *rProto) {
3964  if (lProto == rProto)
3965    return true;
3966  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
3967       E = rProto->protocol_end(); PI != E; ++PI)
3968    if (ProtocolCompatibleWithProtocol(lProto, *PI))
3969      return true;
3970  return false;
3971}
3972
3973/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
3974/// return true if lhs's protocols conform to rhs's protocol; false
3975/// otherwise.
3976bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
3977  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
3978    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
3979  return false;
3980}
3981
3982/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
3983/// ObjCQualifiedIDType.
3984bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
3985                                                   bool compare) {
3986  // Allow id<P..> and an 'id' or void* type in all cases.
3987  if (lhs->isVoidPointerType() ||
3988      lhs->isObjCIdType() || lhs->isObjCClassType())
3989    return true;
3990  else if (rhs->isVoidPointerType() ||
3991           rhs->isObjCIdType() || rhs->isObjCClassType())
3992    return true;
3993
3994  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
3995    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
3996
3997    if (!rhsOPT) return false;
3998
3999    if (rhsOPT->qual_empty()) {
4000      // If the RHS is a unqualified interface pointer "NSString*",
4001      // make sure we check the class hierarchy.
4002      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4003        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4004             E = lhsQID->qual_end(); I != E; ++I) {
4005          // when comparing an id<P> on lhs with a static type on rhs,
4006          // see if static class implements all of id's protocols, directly or
4007          // through its super class and categories.
4008          if (!rhsID->ClassImplementsProtocol(*I, true))
4009            return false;
4010        }
4011      }
4012      // If there are no qualifiers and no interface, we have an 'id'.
4013      return true;
4014    }
4015    // Both the right and left sides have qualifiers.
4016    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4017         E = lhsQID->qual_end(); I != E; ++I) {
4018      ObjCProtocolDecl *lhsProto = *I;
4019      bool match = false;
4020
4021      // when comparing an id<P> on lhs with a static type on rhs,
4022      // see if static class implements all of id's protocols, directly or
4023      // through its super class and categories.
4024      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
4025           E = rhsOPT->qual_end(); J != E; ++J) {
4026        ObjCProtocolDecl *rhsProto = *J;
4027        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4028            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4029          match = true;
4030          break;
4031        }
4032      }
4033      // If the RHS is a qualified interface pointer "NSString<P>*",
4034      // make sure we check the class hierarchy.
4035      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
4036        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
4037             E = lhsQID->qual_end(); I != E; ++I) {
4038          // when comparing an id<P> on lhs with a static type on rhs,
4039          // see if static class implements all of id's protocols, directly or
4040          // through its super class and categories.
4041          if (rhsID->ClassImplementsProtocol(*I, true)) {
4042            match = true;
4043            break;
4044          }
4045        }
4046      }
4047      if (!match)
4048        return false;
4049    }
4050
4051    return true;
4052  }
4053
4054  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
4055  assert(rhsQID && "One of the LHS/RHS should be id<x>");
4056
4057  if (const ObjCObjectPointerType *lhsOPT =
4058        lhs->getAsObjCInterfacePointerType()) {
4059    if (lhsOPT->qual_empty()) {
4060      bool match = false;
4061      if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
4062        for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(),
4063             E = rhsQID->qual_end(); I != E; ++I) {
4064          // when comparing an id<P> on lhs with a static type on rhs,
4065          // see if static class implements all of id's protocols, directly or
4066          // through its super class and categories.
4067          if (lhsID->ClassImplementsProtocol(*I, true)) {
4068            match = true;
4069            break;
4070          }
4071        }
4072        if (!match)
4073          return false;
4074      }
4075      return true;
4076    }
4077    // Both the right and left sides have qualifiers.
4078    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
4079         E = lhsOPT->qual_end(); I != E; ++I) {
4080      ObjCProtocolDecl *lhsProto = *I;
4081      bool match = false;
4082
4083      // when comparing an id<P> on lhs with a static type on rhs,
4084      // see if static class implements all of id's protocols, directly or
4085      // through its super class and categories.
4086      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
4087           E = rhsQID->qual_end(); J != E; ++J) {
4088        ObjCProtocolDecl *rhsProto = *J;
4089        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
4090            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
4091          match = true;
4092          break;
4093        }
4094      }
4095      if (!match)
4096        return false;
4097    }
4098    return true;
4099  }
4100  return false;
4101}
4102
4103/// canAssignObjCInterfaces - Return true if the two interface types are
4104/// compatible for assignment from RHS to LHS.  This handles validation of any
4105/// protocol qualifiers on the LHS or RHS.
4106///
4107bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
4108                                         const ObjCObjectPointerType *RHSOPT) {
4109  // If either type represents the built-in 'id' or 'Class' types, return true.
4110  if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType())
4111    return true;
4112
4113  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4114    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4115                                             QualType(RHSOPT,0),
4116                                             false);
4117
4118  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4119  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4120  if (LHS && RHS) // We have 2 user-defined types.
4121    return canAssignObjCInterfaces(LHS, RHS);
4122
4123  return false;
4124}
4125
4126/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
4127/// for providing type-safty for objective-c pointers used to pass/return
4128/// arguments in block literals. When passed as arguments, passing 'A*' where
4129/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
4130/// not OK. For the return type, the opposite is not OK.
4131bool ASTContext::canAssignObjCInterfacesInBlockPointer(
4132                                         const ObjCObjectPointerType *LHSOPT,
4133                                         const ObjCObjectPointerType *RHSOPT) {
4134  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
4135    return true;
4136
4137  if (LHSOPT->isObjCBuiltinType()) {
4138    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
4139  }
4140
4141  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
4142    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
4143                                             QualType(RHSOPT,0),
4144                                             false);
4145
4146  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4147  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4148  if (LHS && RHS)  { // We have 2 user-defined types.
4149    if (LHS != RHS) {
4150      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4151        return false;
4152      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
4153        return true;
4154    }
4155    else
4156      return true;
4157  }
4158  return false;
4159}
4160
4161/// getIntersectionOfProtocols - This routine finds the intersection of set
4162/// of protocols inherited from two distinct objective-c pointer objects.
4163/// It is used to build composite qualifier list of the composite type of
4164/// the conditional expression involving two objective-c pointer objects.
4165static
4166void getIntersectionOfProtocols(ASTContext &Context,
4167                                const ObjCObjectPointerType *LHSOPT,
4168                                const ObjCObjectPointerType *RHSOPT,
4169      llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
4170
4171  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4172  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4173
4174  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
4175  unsigned LHSNumProtocols = LHS->getNumProtocols();
4176  if (LHSNumProtocols > 0)
4177    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
4178  else {
4179    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
4180    Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols);
4181    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
4182                                LHSInheritedProtocols.end());
4183  }
4184
4185  unsigned RHSNumProtocols = RHS->getNumProtocols();
4186  if (RHSNumProtocols > 0) {
4187    ObjCProtocolDecl **RHSProtocols =
4188      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
4189    for (unsigned i = 0; i < RHSNumProtocols; ++i)
4190      if (InheritedProtocolSet.count(RHSProtocols[i]))
4191        IntersectionOfProtocols.push_back(RHSProtocols[i]);
4192  }
4193  else {
4194    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
4195    Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols);
4196    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
4197         RHSInheritedProtocols.begin(),
4198         E = RHSInheritedProtocols.end(); I != E; ++I)
4199      if (InheritedProtocolSet.count((*I)))
4200        IntersectionOfProtocols.push_back((*I));
4201  }
4202}
4203
4204/// areCommonBaseCompatible - Returns common base class of the two classes if
4205/// one found. Note that this is O'2 algorithm. But it will be called as the
4206/// last type comparison in a ?-exp of ObjC pointer types before a
4207/// warning is issued. So, its invokation is extremely rare.
4208QualType ASTContext::areCommonBaseCompatible(
4209                                          const ObjCObjectPointerType *LHSOPT,
4210                                          const ObjCObjectPointerType *RHSOPT) {
4211  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
4212  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
4213  if (!LHS || !RHS)
4214    return QualType();
4215
4216  while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) {
4217    QualType LHSTy = getObjCInterfaceType(LHSIDecl);
4218    LHS = LHSTy->getAs<ObjCInterfaceType>();
4219    if (canAssignObjCInterfaces(LHS, RHS)) {
4220      llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols;
4221      getIntersectionOfProtocols(*this,
4222                                 LHSOPT, RHSOPT, IntersectionOfProtocols);
4223      if (IntersectionOfProtocols.empty())
4224        LHSTy = getObjCObjectPointerType(LHSTy);
4225      else
4226        LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0],
4227                                                IntersectionOfProtocols.size());
4228      return LHSTy;
4229    }
4230  }
4231
4232  return QualType();
4233}
4234
4235bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS,
4236                                         const ObjCInterfaceType *RHS) {
4237  // Verify that the base decls are compatible: the RHS must be a subclass of
4238  // the LHS.
4239  if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
4240    return false;
4241
4242  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
4243  // protocol qualified at all, then we are good.
4244  if (LHS->getNumProtocols() == 0)
4245    return true;
4246
4247  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't, then it
4248  // isn't a superset.
4249  if (RHS->getNumProtocols() == 0)
4250    return true;  // FIXME: should return false!
4251
4252  for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(),
4253                                        LHSPE = LHS->qual_end();
4254       LHSPI != LHSPE; LHSPI++) {
4255    bool RHSImplementsProtocol = false;
4256
4257    // If the RHS doesn't implement the protocol on the left, the types
4258    // are incompatible.
4259    for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(),
4260                                          RHSPE = RHS->qual_end();
4261         RHSPI != RHSPE; RHSPI++) {
4262      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
4263        RHSImplementsProtocol = true;
4264        break;
4265      }
4266    }
4267    // FIXME: For better diagnostics, consider passing back the protocol name.
4268    if (!RHSImplementsProtocol)
4269      return false;
4270  }
4271  // The RHS implements all protocols listed on the LHS.
4272  return true;
4273}
4274
4275bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
4276  // get the "pointed to" types
4277  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
4278  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
4279
4280  if (!LHSOPT || !RHSOPT)
4281    return false;
4282
4283  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
4284         canAssignObjCInterfaces(RHSOPT, LHSOPT);
4285}
4286
4287/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
4288/// both shall have the identically qualified version of a compatible type.
4289/// C99 6.2.7p1: Two types have compatible types if their types are the
4290/// same. See 6.7.[2,3,5] for additional rules.
4291bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) {
4292  if (getLangOptions().CPlusPlus)
4293    return hasSameType(LHS, RHS);
4294
4295  return !mergeTypes(LHS, RHS).isNull();
4296}
4297
4298bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
4299  return !mergeTypes(LHS, RHS, true).isNull();
4300}
4301
4302QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
4303                                        bool OfBlockPointer) {
4304  const FunctionType *lbase = lhs->getAs<FunctionType>();
4305  const FunctionType *rbase = rhs->getAs<FunctionType>();
4306  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
4307  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
4308  bool allLTypes = true;
4309  bool allRTypes = true;
4310
4311  // Check return type
4312  QualType retType;
4313  if (OfBlockPointer)
4314    retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true);
4315  else
4316   retType = mergeTypes(lbase->getResultType(), rbase->getResultType());
4317  if (retType.isNull()) return QualType();
4318  if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType()))
4319    allLTypes = false;
4320  if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType()))
4321    allRTypes = false;
4322  // FIXME: double check this
4323  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
4324  //                           rbase->getRegParmAttr() != 0 &&
4325  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
4326  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
4327  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
4328  unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() :
4329      lbaseInfo.getRegParm();
4330  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
4331  if (NoReturn != lbaseInfo.getNoReturn() ||
4332      RegParm != lbaseInfo.getRegParm())
4333    allLTypes = false;
4334  if (NoReturn != rbaseInfo.getNoReturn() ||
4335      RegParm != rbaseInfo.getRegParm())
4336    allRTypes = false;
4337  CallingConv lcc = lbaseInfo.getCC();
4338  CallingConv rcc = rbaseInfo.getCC();
4339  // Compatible functions must have compatible calling conventions
4340  if (!isSameCallConv(lcc, rcc))
4341    return QualType();
4342
4343  if (lproto && rproto) { // two C99 style function prototypes
4344    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
4345           "C++ shouldn't be here");
4346    unsigned lproto_nargs = lproto->getNumArgs();
4347    unsigned rproto_nargs = rproto->getNumArgs();
4348
4349    // Compatible functions must have the same number of arguments
4350    if (lproto_nargs != rproto_nargs)
4351      return QualType();
4352
4353    // Variadic and non-variadic functions aren't compatible
4354    if (lproto->isVariadic() != rproto->isVariadic())
4355      return QualType();
4356
4357    if (lproto->getTypeQuals() != rproto->getTypeQuals())
4358      return QualType();
4359
4360    // Check argument compatibility
4361    llvm::SmallVector<QualType, 10> types;
4362    for (unsigned i = 0; i < lproto_nargs; i++) {
4363      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
4364      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
4365      QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer);
4366      if (argtype.isNull()) return QualType();
4367      types.push_back(argtype);
4368      if (getCanonicalType(argtype) != getCanonicalType(largtype))
4369        allLTypes = false;
4370      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
4371        allRTypes = false;
4372    }
4373    if (allLTypes) return lhs;
4374    if (allRTypes) return rhs;
4375    return getFunctionType(retType, types.begin(), types.size(),
4376                           lproto->isVariadic(), lproto->getTypeQuals(),
4377                           false, false, 0, 0,
4378                           FunctionType::ExtInfo(NoReturn, RegParm, lcc));
4379  }
4380
4381  if (lproto) allRTypes = false;
4382  if (rproto) allLTypes = false;
4383
4384  const FunctionProtoType *proto = lproto ? lproto : rproto;
4385  if (proto) {
4386    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
4387    if (proto->isVariadic()) return QualType();
4388    // Check that the types are compatible with the types that
4389    // would result from default argument promotions (C99 6.7.5.3p15).
4390    // The only types actually affected are promotable integer
4391    // types and floats, which would be passed as a different
4392    // type depending on whether the prototype is visible.
4393    unsigned proto_nargs = proto->getNumArgs();
4394    for (unsigned i = 0; i < proto_nargs; ++i) {
4395      QualType argTy = proto->getArgType(i);
4396
4397      // Look at the promotion type of enum types, since that is the type used
4398      // to pass enum values.
4399      if (const EnumType *Enum = argTy->getAs<EnumType>())
4400        argTy = Enum->getDecl()->getPromotionType();
4401
4402      if (argTy->isPromotableIntegerType() ||
4403          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
4404        return QualType();
4405    }
4406
4407    if (allLTypes) return lhs;
4408    if (allRTypes) return rhs;
4409    return getFunctionType(retType, proto->arg_type_begin(),
4410                           proto->getNumArgs(), proto->isVariadic(),
4411                           proto->getTypeQuals(),
4412                           false, false, 0, 0,
4413                           FunctionType::ExtInfo(NoReturn, RegParm, lcc));
4414  }
4415
4416  if (allLTypes) return lhs;
4417  if (allRTypes) return rhs;
4418  FunctionType::ExtInfo Info(NoReturn, RegParm, lcc);
4419  return getFunctionNoProtoType(retType, Info);
4420}
4421
4422QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
4423                                bool OfBlockPointer) {
4424  // C++ [expr]: If an expression initially has the type "reference to T", the
4425  // type is adjusted to "T" prior to any further analysis, the expression
4426  // designates the object or function denoted by the reference, and the
4427  // expression is an lvalue unless the reference is an rvalue reference and
4428  // the expression is a function call (possibly inside parentheses).
4429  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
4430  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
4431
4432  QualType LHSCan = getCanonicalType(LHS),
4433           RHSCan = getCanonicalType(RHS);
4434
4435  // If two types are identical, they are compatible.
4436  if (LHSCan == RHSCan)
4437    return LHS;
4438
4439  // If the qualifiers are different, the types aren't compatible... mostly.
4440  Qualifiers LQuals = LHSCan.getLocalQualifiers();
4441  Qualifiers RQuals = RHSCan.getLocalQualifiers();
4442  if (LQuals != RQuals) {
4443    // If any of these qualifiers are different, we have a type
4444    // mismatch.
4445    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
4446        LQuals.getAddressSpace() != RQuals.getAddressSpace())
4447      return QualType();
4448
4449    // Exactly one GC qualifier difference is allowed: __strong is
4450    // okay if the other type has no GC qualifier but is an Objective
4451    // C object pointer (i.e. implicitly strong by default).  We fix
4452    // this by pretending that the unqualified type was actually
4453    // qualified __strong.
4454    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
4455    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
4456    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
4457
4458    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
4459      return QualType();
4460
4461    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
4462      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
4463    }
4464    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
4465      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
4466    }
4467    return QualType();
4468  }
4469
4470  // Okay, qualifiers are equal.
4471
4472  Type::TypeClass LHSClass = LHSCan->getTypeClass();
4473  Type::TypeClass RHSClass = RHSCan->getTypeClass();
4474
4475  // We want to consider the two function types to be the same for these
4476  // comparisons, just force one to the other.
4477  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
4478  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
4479
4480  // Same as above for arrays
4481  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
4482    LHSClass = Type::ConstantArray;
4483  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
4484    RHSClass = Type::ConstantArray;
4485
4486  // Canonicalize ExtVector -> Vector.
4487  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
4488  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
4489
4490  // If the canonical type classes don't match.
4491  if (LHSClass != RHSClass) {
4492    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
4493    // a signed integer type, or an unsigned integer type.
4494    // Compatibility is based on the underlying type, not the promotion
4495    // type.
4496    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
4497      if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType())
4498        return RHS;
4499    }
4500    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
4501      if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType())
4502        return LHS;
4503    }
4504
4505    return QualType();
4506  }
4507
4508  // The canonical type classes match.
4509  switch (LHSClass) {
4510#define TYPE(Class, Base)
4511#define ABSTRACT_TYPE(Class, Base)
4512#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
4513#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
4514#define DEPENDENT_TYPE(Class, Base) case Type::Class:
4515#include "clang/AST/TypeNodes.def"
4516    assert(false && "Non-canonical and dependent types shouldn't get here");
4517    return QualType();
4518
4519  case Type::LValueReference:
4520  case Type::RValueReference:
4521  case Type::MemberPointer:
4522    assert(false && "C++ should never be in mergeTypes");
4523    return QualType();
4524
4525  case Type::IncompleteArray:
4526  case Type::VariableArray:
4527  case Type::FunctionProto:
4528  case Type::ExtVector:
4529    assert(false && "Types are eliminated above");
4530    return QualType();
4531
4532  case Type::Pointer:
4533  {
4534    // Merge two pointer types, while trying to preserve typedef info
4535    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
4536    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
4537    QualType ResultType = mergeTypes(LHSPointee, RHSPointee);
4538    if (ResultType.isNull()) return QualType();
4539    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4540      return LHS;
4541    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4542      return RHS;
4543    return getPointerType(ResultType);
4544  }
4545  case Type::BlockPointer:
4546  {
4547    // Merge two block pointer types, while trying to preserve typedef info
4548    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
4549    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
4550    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer);
4551    if (ResultType.isNull()) return QualType();
4552    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
4553      return LHS;
4554    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
4555      return RHS;
4556    return getBlockPointerType(ResultType);
4557  }
4558  case Type::ConstantArray:
4559  {
4560    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
4561    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
4562    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
4563      return QualType();
4564
4565    QualType LHSElem = getAsArrayType(LHS)->getElementType();
4566    QualType RHSElem = getAsArrayType(RHS)->getElementType();
4567    QualType ResultType = mergeTypes(LHSElem, RHSElem);
4568    if (ResultType.isNull()) return QualType();
4569    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4570      return LHS;
4571    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4572      return RHS;
4573    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
4574                                          ArrayType::ArraySizeModifier(), 0);
4575    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
4576                                          ArrayType::ArraySizeModifier(), 0);
4577    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
4578    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
4579    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
4580      return LHS;
4581    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
4582      return RHS;
4583    if (LVAT) {
4584      // FIXME: This isn't correct! But tricky to implement because
4585      // the array's size has to be the size of LHS, but the type
4586      // has to be different.
4587      return LHS;
4588    }
4589    if (RVAT) {
4590      // FIXME: This isn't correct! But tricky to implement because
4591      // the array's size has to be the size of RHS, but the type
4592      // has to be different.
4593      return RHS;
4594    }
4595    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
4596    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
4597    return getIncompleteArrayType(ResultType,
4598                                  ArrayType::ArraySizeModifier(), 0);
4599  }
4600  case Type::FunctionNoProto:
4601    return mergeFunctionTypes(LHS, RHS, OfBlockPointer);
4602  case Type::Record:
4603  case Type::Enum:
4604    return QualType();
4605  case Type::Builtin:
4606    // Only exactly equal builtin types are compatible, which is tested above.
4607    return QualType();
4608  case Type::Complex:
4609    // Distinct complex types are incompatible.
4610    return QualType();
4611  case Type::Vector:
4612    // FIXME: The merged type should be an ExtVector!
4613    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
4614                             RHSCan->getAs<VectorType>()))
4615      return LHS;
4616    return QualType();
4617  case Type::ObjCInterface: {
4618    // Check if the interfaces are assignment compatible.
4619    // FIXME: This should be type compatibility, e.g. whether
4620    // "LHS x; RHS x;" at global scope is legal.
4621    const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>();
4622    const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>();
4623    if (LHSIface && RHSIface &&
4624        canAssignObjCInterfaces(LHSIface, RHSIface))
4625      return LHS;
4626
4627    return QualType();
4628  }
4629  case Type::ObjCObjectPointer: {
4630    if (OfBlockPointer) {
4631      if (canAssignObjCInterfacesInBlockPointer(
4632                                          LHS->getAs<ObjCObjectPointerType>(),
4633                                          RHS->getAs<ObjCObjectPointerType>()))
4634      return LHS;
4635      return QualType();
4636    }
4637    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
4638                                RHS->getAs<ObjCObjectPointerType>()))
4639      return LHS;
4640
4641    return QualType();
4642    }
4643  }
4644
4645  return QualType();
4646}
4647
4648//===----------------------------------------------------------------------===//
4649//                         Integer Predicates
4650//===----------------------------------------------------------------------===//
4651
4652unsigned ASTContext::getIntWidth(QualType T) {
4653  if (T->isBooleanType())
4654    return 1;
4655  if (EnumType *ET = dyn_cast<EnumType>(T))
4656    T = ET->getDecl()->getIntegerType();
4657  // For builtin types, just use the standard type sizing method
4658  return (unsigned)getTypeSize(T);
4659}
4660
4661QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
4662  assert(T->isSignedIntegerType() && "Unexpected type");
4663
4664  // Turn <4 x signed int> -> <4 x unsigned int>
4665  if (const VectorType *VTy = T->getAs<VectorType>())
4666    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
4667             VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel());
4668
4669  // For enums, we return the unsigned version of the base type.
4670  if (const EnumType *ETy = T->getAs<EnumType>())
4671    T = ETy->getDecl()->getIntegerType();
4672
4673  const BuiltinType *BTy = T->getAs<BuiltinType>();
4674  assert(BTy && "Unexpected signed integer type");
4675  switch (BTy->getKind()) {
4676  case BuiltinType::Char_S:
4677  case BuiltinType::SChar:
4678    return UnsignedCharTy;
4679  case BuiltinType::Short:
4680    return UnsignedShortTy;
4681  case BuiltinType::Int:
4682    return UnsignedIntTy;
4683  case BuiltinType::Long:
4684    return UnsignedLongTy;
4685  case BuiltinType::LongLong:
4686    return UnsignedLongLongTy;
4687  case BuiltinType::Int128:
4688    return UnsignedInt128Ty;
4689  default:
4690    assert(0 && "Unexpected signed integer type");
4691    return QualType();
4692  }
4693}
4694
4695ExternalASTSource::~ExternalASTSource() { }
4696
4697void ExternalASTSource::PrintStats() { }
4698
4699
4700//===----------------------------------------------------------------------===//
4701//                          Builtin Type Computation
4702//===----------------------------------------------------------------------===//
4703
4704/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
4705/// pointer over the consumed characters.  This returns the resultant type.
4706static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context,
4707                                  ASTContext::GetBuiltinTypeError &Error,
4708                                  bool AllowTypeModifiers = true) {
4709  // Modifiers.
4710  int HowLong = 0;
4711  bool Signed = false, Unsigned = false;
4712
4713  // Read the modifiers first.
4714  bool Done = false;
4715  while (!Done) {
4716    switch (*Str++) {
4717    default: Done = true; --Str; break;
4718    case 'S':
4719      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
4720      assert(!Signed && "Can't use 'S' modifier multiple times!");
4721      Signed = true;
4722      break;
4723    case 'U':
4724      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
4725      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
4726      Unsigned = true;
4727      break;
4728    case 'L':
4729      assert(HowLong <= 2 && "Can't have LLLL modifier");
4730      ++HowLong;
4731      break;
4732    }
4733  }
4734
4735  QualType Type;
4736
4737  // Read the base type.
4738  switch (*Str++) {
4739  default: assert(0 && "Unknown builtin type letter!");
4740  case 'v':
4741    assert(HowLong == 0 && !Signed && !Unsigned &&
4742           "Bad modifiers used with 'v'!");
4743    Type = Context.VoidTy;
4744    break;
4745  case 'f':
4746    assert(HowLong == 0 && !Signed && !Unsigned &&
4747           "Bad modifiers used with 'f'!");
4748    Type = Context.FloatTy;
4749    break;
4750  case 'd':
4751    assert(HowLong < 2 && !Signed && !Unsigned &&
4752           "Bad modifiers used with 'd'!");
4753    if (HowLong)
4754      Type = Context.LongDoubleTy;
4755    else
4756      Type = Context.DoubleTy;
4757    break;
4758  case 's':
4759    assert(HowLong == 0 && "Bad modifiers used with 's'!");
4760    if (Unsigned)
4761      Type = Context.UnsignedShortTy;
4762    else
4763      Type = Context.ShortTy;
4764    break;
4765  case 'i':
4766    if (HowLong == 3)
4767      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
4768    else if (HowLong == 2)
4769      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
4770    else if (HowLong == 1)
4771      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
4772    else
4773      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
4774    break;
4775  case 'c':
4776    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
4777    if (Signed)
4778      Type = Context.SignedCharTy;
4779    else if (Unsigned)
4780      Type = Context.UnsignedCharTy;
4781    else
4782      Type = Context.CharTy;
4783    break;
4784  case 'b': // boolean
4785    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
4786    Type = Context.BoolTy;
4787    break;
4788  case 'z':  // size_t.
4789    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
4790    Type = Context.getSizeType();
4791    break;
4792  case 'F':
4793    Type = Context.getCFConstantStringType();
4794    break;
4795  case 'a':
4796    Type = Context.getBuiltinVaListType();
4797    assert(!Type.isNull() && "builtin va list type not initialized!");
4798    break;
4799  case 'A':
4800    // This is a "reference" to a va_list; however, what exactly
4801    // this means depends on how va_list is defined. There are two
4802    // different kinds of va_list: ones passed by value, and ones
4803    // passed by reference.  An example of a by-value va_list is
4804    // x86, where va_list is a char*. An example of by-ref va_list
4805    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
4806    // we want this argument to be a char*&; for x86-64, we want
4807    // it to be a __va_list_tag*.
4808    Type = Context.getBuiltinVaListType();
4809    assert(!Type.isNull() && "builtin va list type not initialized!");
4810    if (Type->isArrayType()) {
4811      Type = Context.getArrayDecayedType(Type);
4812    } else {
4813      Type = Context.getLValueReferenceType(Type);
4814    }
4815    break;
4816  case 'V': {
4817    char *End;
4818    unsigned NumElements = strtoul(Str, &End, 10);
4819    assert(End != Str && "Missing vector size");
4820
4821    Str = End;
4822
4823    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4824    // FIXME: Don't know what to do about AltiVec.
4825    Type = Context.getVectorType(ElementType, NumElements, false, false);
4826    break;
4827  }
4828  case 'X': {
4829    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false);
4830    Type = Context.getComplexType(ElementType);
4831    break;
4832  }
4833  case 'P':
4834    Type = Context.getFILEType();
4835    if (Type.isNull()) {
4836      Error = ASTContext::GE_Missing_stdio;
4837      return QualType();
4838    }
4839    break;
4840  case 'J':
4841    if (Signed)
4842      Type = Context.getsigjmp_bufType();
4843    else
4844      Type = Context.getjmp_bufType();
4845
4846    if (Type.isNull()) {
4847      Error = ASTContext::GE_Missing_setjmp;
4848      return QualType();
4849    }
4850    break;
4851  }
4852
4853  if (!AllowTypeModifiers)
4854    return Type;
4855
4856  Done = false;
4857  while (!Done) {
4858    switch (char c = *Str++) {
4859      default: Done = true; --Str; break;
4860      case '*':
4861      case '&':
4862        {
4863          // Both pointers and references can have their pointee types
4864          // qualified with an address space.
4865          char *End;
4866          unsigned AddrSpace = strtoul(Str, &End, 10);
4867          if (End != Str && AddrSpace != 0) {
4868            Type = Context.getAddrSpaceQualType(Type, AddrSpace);
4869            Str = End;
4870          }
4871        }
4872        if (c == '*')
4873          Type = Context.getPointerType(Type);
4874        else
4875          Type = Context.getLValueReferenceType(Type);
4876        break;
4877      // FIXME: There's no way to have a built-in with an rvalue ref arg.
4878      case 'C':
4879        Type = Type.withConst();
4880        break;
4881      case 'D':
4882        Type = Context.getVolatileType(Type);
4883        break;
4884    }
4885  }
4886
4887  return Type;
4888}
4889
4890/// GetBuiltinType - Return the type for the specified builtin.
4891QualType ASTContext::GetBuiltinType(unsigned id,
4892                                    GetBuiltinTypeError &Error) {
4893  const char *TypeStr = BuiltinInfo.GetTypeString(id);
4894
4895  llvm::SmallVector<QualType, 8> ArgTypes;
4896
4897  Error = GE_None;
4898  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error);
4899  if (Error != GE_None)
4900    return QualType();
4901  while (TypeStr[0] && TypeStr[0] != '.') {
4902    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error);
4903    if (Error != GE_None)
4904      return QualType();
4905
4906    // Do array -> pointer decay.  The builtin should use the decayed type.
4907    if (Ty->isArrayType())
4908      Ty = getArrayDecayedType(Ty);
4909
4910    ArgTypes.push_back(Ty);
4911  }
4912
4913  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
4914         "'.' should only occur at end of builtin type list!");
4915
4916  // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);".
4917  if (ArgTypes.size() == 0 && TypeStr[0] == '.')
4918    return getFunctionNoProtoType(ResType);
4919
4920  // FIXME: Should we create noreturn types?
4921  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(),
4922                         TypeStr[0] == '.', 0, false, false, 0, 0,
4923                         FunctionType::ExtInfo());
4924}
4925
4926QualType
4927ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
4928  // Perform the usual unary conversions. We do this early so that
4929  // integral promotions to "int" can allow us to exit early, in the
4930  // lhs == rhs check. Also, for conversion purposes, we ignore any
4931  // qualifiers.  For example, "const float" and "float" are
4932  // equivalent.
4933  if (lhs->isPromotableIntegerType())
4934    lhs = getPromotedIntegerType(lhs);
4935  else
4936    lhs = lhs.getUnqualifiedType();
4937  if (rhs->isPromotableIntegerType())
4938    rhs = getPromotedIntegerType(rhs);
4939  else
4940    rhs = rhs.getUnqualifiedType();
4941
4942  // If both types are identical, no conversion is needed.
4943  if (lhs == rhs)
4944    return lhs;
4945
4946  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
4947  // The caller can deal with this (e.g. pointer + int).
4948  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
4949    return lhs;
4950
4951  // At this point, we have two different arithmetic types.
4952
4953  // Handle complex types first (C99 6.3.1.8p1).
4954  if (lhs->isComplexType() || rhs->isComplexType()) {
4955    // if we have an integer operand, the result is the complex type.
4956    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
4957      // convert the rhs to the lhs complex type.
4958      return lhs;
4959    }
4960    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
4961      // convert the lhs to the rhs complex type.
4962      return rhs;
4963    }
4964    // This handles complex/complex, complex/float, or float/complex.
4965    // When both operands are complex, the shorter operand is converted to the
4966    // type of the longer, and that is the type of the result. This corresponds
4967    // to what is done when combining two real floating-point operands.
4968    // The fun begins when size promotion occur across type domains.
4969    // From H&S 6.3.4: When one operand is complex and the other is a real
4970    // floating-point type, the less precise type is converted, within it's
4971    // real or complex domain, to the precision of the other type. For example,
4972    // when combining a "long double" with a "double _Complex", the
4973    // "double _Complex" is promoted to "long double _Complex".
4974    int result = getFloatingTypeOrder(lhs, rhs);
4975
4976    if (result > 0) { // The left side is bigger, convert rhs.
4977      rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs);
4978    } else if (result < 0) { // The right side is bigger, convert lhs.
4979      lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs);
4980    }
4981    // At this point, lhs and rhs have the same rank/size. Now, make sure the
4982    // domains match. This is a requirement for our implementation, C99
4983    // does not require this promotion.
4984    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
4985      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
4986        return rhs;
4987      } else { // handle "_Complex double, double".
4988        return lhs;
4989      }
4990    }
4991    return lhs; // The domain/size match exactly.
4992  }
4993  // Now handle "real" floating types (i.e. float, double, long double).
4994  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
4995    // if we have an integer operand, the result is the real floating type.
4996    if (rhs->isIntegerType()) {
4997      // convert rhs to the lhs floating point type.
4998      return lhs;
4999    }
5000    if (rhs->isComplexIntegerType()) {
5001      // convert rhs to the complex floating point type.
5002      return getComplexType(lhs);
5003    }
5004    if (lhs->isIntegerType()) {
5005      // convert lhs to the rhs floating point type.
5006      return rhs;
5007    }
5008    if (lhs->isComplexIntegerType()) {
5009      // convert lhs to the complex floating point type.
5010      return getComplexType(rhs);
5011    }
5012    // We have two real floating types, float/complex combos were handled above.
5013    // Convert the smaller operand to the bigger result.
5014    int result = getFloatingTypeOrder(lhs, rhs);
5015    if (result > 0) // convert the rhs
5016      return lhs;
5017    assert(result < 0 && "illegal float comparison");
5018    return rhs;   // convert the lhs
5019  }
5020  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
5021    // Handle GCC complex int extension.
5022    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
5023    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
5024
5025    if (lhsComplexInt && rhsComplexInt) {
5026      if (getIntegerTypeOrder(lhsComplexInt->getElementType(),
5027                              rhsComplexInt->getElementType()) >= 0)
5028        return lhs; // convert the rhs
5029      return rhs;
5030    } else if (lhsComplexInt && rhs->isIntegerType()) {
5031      // convert the rhs to the lhs complex type.
5032      return lhs;
5033    } else if (rhsComplexInt && lhs->isIntegerType()) {
5034      // convert the lhs to the rhs complex type.
5035      return rhs;
5036    }
5037  }
5038  // Finally, we have two differing integer types.
5039  // The rules for this case are in C99 6.3.1.8
5040  int compare = getIntegerTypeOrder(lhs, rhs);
5041  bool lhsSigned = lhs->isSignedIntegerType(),
5042       rhsSigned = rhs->isSignedIntegerType();
5043  QualType destType;
5044  if (lhsSigned == rhsSigned) {
5045    // Same signedness; use the higher-ranked type
5046    destType = compare >= 0 ? lhs : rhs;
5047  } else if (compare != (lhsSigned ? 1 : -1)) {
5048    // The unsigned type has greater than or equal rank to the
5049    // signed type, so use the unsigned type
5050    destType = lhsSigned ? rhs : lhs;
5051  } else if (getIntWidth(lhs) != getIntWidth(rhs)) {
5052    // The two types are different widths; if we are here, that
5053    // means the signed type is larger than the unsigned type, so
5054    // use the signed type.
5055    destType = lhsSigned ? lhs : rhs;
5056  } else {
5057    // The signed type is higher-ranked than the unsigned type,
5058    // but isn't actually any bigger (like unsigned int and long
5059    // on most 32-bit systems).  Use the unsigned type corresponding
5060    // to the signed type.
5061    destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
5062  }
5063  return destType;
5064}
5065