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