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