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