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