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