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