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