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