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