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