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