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