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