ASTContext.cpp revision c3fee3539fd00a6ce21dc1f574baf76686640072
1//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements the ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/CharUnits.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExternalASTSource.h"
23#include "clang/AST/ASTMutationListener.h"
24#include "clang/AST/RecordLayout.h"
25#include "clang/AST/Mangle.h"
26#include "clang/Basic/Builtins.h"
27#include "clang/Basic/SourceManager.h"
28#include "clang/Basic/TargetInfo.h"
29#include "llvm/ADT/SmallString.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/Support/MathExtras.h"
32#include "llvm/Support/raw_ostream.h"
33#include "llvm/Support/Capacity.h"
34#include "CXXABI.h"
35#include <map>
36
37using namespace clang;
38
39unsigned ASTContext::NumImplicitDefaultConstructors;
40unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
41unsigned ASTContext::NumImplicitCopyConstructors;
42unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
43unsigned ASTContext::NumImplicitMoveConstructors;
44unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
45unsigned ASTContext::NumImplicitCopyAssignmentOperators;
46unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
47unsigned ASTContext::NumImplicitMoveAssignmentOperators;
48unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
49unsigned ASTContext::NumImplicitDestructors;
50unsigned ASTContext::NumImplicitDestructorsDeclared;
51
52enum FloatingRank {
53  HalfRank, FloatRank, DoubleRank, LongDoubleRank
54};
55
56const RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
57  if (!CommentsLoaded && ExternalSource) {
58    ExternalSource->ReadComments();
59    CommentsLoaded = true;
60  }
61
62  assert(D);
63
64  // User can not attach documentation to implicit declarations.
65  if (D->isImplicit())
66    return NULL;
67
68  // TODO: handle comments for function parameters properly.
69  if (isa<ParmVarDecl>(D))
70    return NULL;
71
72  ArrayRef<RawComment> RawComments = Comments.getComments();
73
74  // If there are no comments anywhere, we won't find anything.
75  if (RawComments.empty())
76    return NULL;
77
78  // If the declaration doesn't map directly to a location in a file, we
79  // can't find the comment.
80  SourceLocation DeclLoc = D->getLocation();
81  if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
82    return NULL;
83
84  // Find the comment that occurs just after this declaration.
85  ArrayRef<RawComment>::iterator Comment
86      = std::lower_bound(RawComments.begin(),
87                         RawComments.end(),
88                         RawComment(SourceMgr, SourceRange(DeclLoc)),
89                         BeforeThanCompare<RawComment>(SourceMgr));
90
91  // Decompose the location for the declaration and find the beginning of the
92  // file buffer.
93  std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
94
95  // First check whether we have a trailing comment.
96  if (Comment != RawComments.end() &&
97      Comment->isDocumentation() && Comment->isTrailingComment() &&
98      !isa<TagDecl>(D) && !isa<NamespaceDecl>(D)) {
99    std::pair<FileID, unsigned> CommentBeginDecomp
100      = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getBegin());
101    // Check that Doxygen trailing comment comes after the declaration, starts
102    // on the same line and in the same file as the declaration.
103    if (DeclLocDecomp.first == CommentBeginDecomp.first &&
104        SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
105          == SourceMgr.getLineNumber(CommentBeginDecomp.first,
106                                     CommentBeginDecomp.second)) {
107      return &*Comment;
108    }
109  }
110
111  // The comment just after the declaration was not a trailing comment.
112  // Let's look at the previous comment.
113  if (Comment == RawComments.begin())
114    return NULL;
115  --Comment;
116
117  // Check that we actually have a non-member Doxygen comment.
118  if (!Comment->isDocumentation() || Comment->isTrailingComment())
119    return NULL;
120
121  // Decompose the end of the comment.
122  std::pair<FileID, unsigned> CommentEndDecomp
123    = SourceMgr.getDecomposedLoc(Comment->getSourceRange().getEnd());
124
125  // If the comment and the declaration aren't in the same file, then they
126  // aren't related.
127  if (DeclLocDecomp.first != CommentEndDecomp.first)
128    return NULL;
129
130  // Get the corresponding buffer.
131  bool Invalid = false;
132  const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
133                                               &Invalid).data();
134  if (Invalid)
135    return NULL;
136
137  // Extract text between the comment and declaration.
138  StringRef Text(Buffer + CommentEndDecomp.second,
139                 DeclLocDecomp.second - CommentEndDecomp.second);
140
141  // There should be no other declarations or preprocessor directives between
142  // comment and declaration.
143  if (Text.find_first_of(",;{}#") != StringRef::npos)
144    return NULL;
145
146  return &*Comment;
147}
148
149const RawComment *ASTContext::getRawCommentForDecl(const Decl *D) const {
150  // Check whether we have cached a comment string for this declaration
151  // already.
152  llvm::DenseMap<const Decl *, const RawComment *>::iterator Pos
153      = DeclComments.find(D);
154  if (Pos != DeclComments.end())
155      return Pos->second;
156
157  const RawComment *RC = getRawCommentForDeclNoCache(D);
158  DeclComments[D] = RC;
159  return RC;
160}
161
162void
163ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
164                                               TemplateTemplateParmDecl *Parm) {
165  ID.AddInteger(Parm->getDepth());
166  ID.AddInteger(Parm->getPosition());
167  ID.AddBoolean(Parm->isParameterPack());
168
169  TemplateParameterList *Params = Parm->getTemplateParameters();
170  ID.AddInteger(Params->size());
171  for (TemplateParameterList::const_iterator P = Params->begin(),
172                                          PEnd = Params->end();
173       P != PEnd; ++P) {
174    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
175      ID.AddInteger(0);
176      ID.AddBoolean(TTP->isParameterPack());
177      continue;
178    }
179
180    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
181      ID.AddInteger(1);
182      ID.AddBoolean(NTTP->isParameterPack());
183      ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
184      if (NTTP->isExpandedParameterPack()) {
185        ID.AddBoolean(true);
186        ID.AddInteger(NTTP->getNumExpansionTypes());
187        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
188          QualType T = NTTP->getExpansionType(I);
189          ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
190        }
191      } else
192        ID.AddBoolean(false);
193      continue;
194    }
195
196    TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
197    ID.AddInteger(2);
198    Profile(ID, TTP);
199  }
200}
201
202TemplateTemplateParmDecl *
203ASTContext::getCanonicalTemplateTemplateParmDecl(
204                                          TemplateTemplateParmDecl *TTP) const {
205  // Check if we already have a canonical template template parameter.
206  llvm::FoldingSetNodeID ID;
207  CanonicalTemplateTemplateParm::Profile(ID, TTP);
208  void *InsertPos = 0;
209  CanonicalTemplateTemplateParm *Canonical
210    = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
211  if (Canonical)
212    return Canonical->getParam();
213
214  // Build a canonical template parameter list.
215  TemplateParameterList *Params = TTP->getTemplateParameters();
216  SmallVector<NamedDecl *, 4> CanonParams;
217  CanonParams.reserve(Params->size());
218  for (TemplateParameterList::const_iterator P = Params->begin(),
219                                          PEnd = Params->end();
220       P != PEnd; ++P) {
221    if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
222      CanonParams.push_back(
223                  TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
224                                               SourceLocation(),
225                                               SourceLocation(),
226                                               TTP->getDepth(),
227                                               TTP->getIndex(), 0, false,
228                                               TTP->isParameterPack()));
229    else if (NonTypeTemplateParmDecl *NTTP
230             = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
231      QualType T = getCanonicalType(NTTP->getType());
232      TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
233      NonTypeTemplateParmDecl *Param;
234      if (NTTP->isExpandedParameterPack()) {
235        SmallVector<QualType, 2> ExpandedTypes;
236        SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
237        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
238          ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
239          ExpandedTInfos.push_back(
240                                getTrivialTypeSourceInfo(ExpandedTypes.back()));
241        }
242
243        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
244                                                SourceLocation(),
245                                                SourceLocation(),
246                                                NTTP->getDepth(),
247                                                NTTP->getPosition(), 0,
248                                                T,
249                                                TInfo,
250                                                ExpandedTypes.data(),
251                                                ExpandedTypes.size(),
252                                                ExpandedTInfos.data());
253      } else {
254        Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
255                                                SourceLocation(),
256                                                SourceLocation(),
257                                                NTTP->getDepth(),
258                                                NTTP->getPosition(), 0,
259                                                T,
260                                                NTTP->isParameterPack(),
261                                                TInfo);
262      }
263      CanonParams.push_back(Param);
264
265    } else
266      CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
267                                           cast<TemplateTemplateParmDecl>(*P)));
268  }
269
270  TemplateTemplateParmDecl *CanonTTP
271    = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
272                                       SourceLocation(), TTP->getDepth(),
273                                       TTP->getPosition(),
274                                       TTP->isParameterPack(),
275                                       0,
276                         TemplateParameterList::Create(*this, SourceLocation(),
277                                                       SourceLocation(),
278                                                       CanonParams.data(),
279                                                       CanonParams.size(),
280                                                       SourceLocation()));
281
282  // Get the new insert position for the node we care about.
283  Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
284  assert(Canonical == 0 && "Shouldn't be in the map!");
285  (void)Canonical;
286
287  // Create the canonical template template parameter entry.
288  Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
289  CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
290  return CanonTTP;
291}
292
293CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
294  if (!LangOpts.CPlusPlus) return 0;
295
296  switch (T.getCXXABI()) {
297  case CXXABI_ARM:
298    return CreateARMCXXABI(*this);
299  case CXXABI_Itanium:
300    return CreateItaniumCXXABI(*this);
301  case CXXABI_Microsoft:
302    return CreateMicrosoftCXXABI(*this);
303  }
304  llvm_unreachable("Invalid CXXABI type!");
305}
306
307static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
308                                             const LangOptions &LOpts) {
309  if (LOpts.FakeAddressSpaceMap) {
310    // The fake address space map must have a distinct entry for each
311    // language-specific address space.
312    static const unsigned FakeAddrSpaceMap[] = {
313      1, // opencl_global
314      2, // opencl_local
315      3, // opencl_constant
316      4, // cuda_device
317      5, // cuda_constant
318      6  // cuda_shared
319    };
320    return &FakeAddrSpaceMap;
321  } else {
322    return &T.getAddressSpaceMap();
323  }
324}
325
326ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM,
327                       const TargetInfo *t,
328                       IdentifierTable &idents, SelectorTable &sels,
329                       Builtin::Context &builtins,
330                       unsigned size_reserve,
331                       bool DelayInitialization)
332  : FunctionProtoTypes(this_()),
333    TemplateSpecializationTypes(this_()),
334    DependentTemplateSpecializationTypes(this_()),
335    SubstTemplateTemplateParmPacks(this_()),
336    GlobalNestedNameSpecifier(0),
337    Int128Decl(0), UInt128Decl(0),
338    BuiltinVaListDecl(0),
339    ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0),
340    CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0),
341    FILEDecl(0),
342    jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0),
343    BlockDescriptorType(0), BlockDescriptorExtendedType(0),
344    cudaConfigureCallDecl(0),
345    NullTypeSourceInfo(QualType()),
346    FirstLocalImport(), LastLocalImport(),
347    SourceMgr(SM), LangOpts(LOpts),
348    AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts),
349    Idents(idents), Selectors(sels),
350    BuiltinInfo(builtins),
351    DeclarationNames(*this),
352    ExternalSource(0), Listener(0),
353    Comments(SM), CommentsLoaded(false),
354    LastSDM(0, 0),
355    UniqueBlockByRefTypeID(0)
356{
357  if (size_reserve > 0) Types.reserve(size_reserve);
358  TUDecl = TranslationUnitDecl::Create(*this);
359
360  if (!DelayInitialization) {
361    assert(t && "No target supplied for ASTContext initialization");
362    InitBuiltinTypes(*t);
363  }
364}
365
366ASTContext::~ASTContext() {
367  // Release the DenseMaps associated with DeclContext objects.
368  // FIXME: Is this the ideal solution?
369  ReleaseDeclContextMaps();
370
371  // Call all of the deallocation functions.
372  for (unsigned I = 0, N = Deallocations.size(); I != N; ++I)
373    Deallocations[I].first(Deallocations[I].second);
374
375  // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
376  // because they can contain DenseMaps.
377  for (llvm::DenseMap<const ObjCContainerDecl*,
378       const ASTRecordLayout*>::iterator
379       I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
380    // Increment in loop to prevent using deallocated memory.
381    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
382      R->Destroy(*this);
383
384  for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
385       I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
386    // Increment in loop to prevent using deallocated memory.
387    if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
388      R->Destroy(*this);
389  }
390
391  for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
392                                                    AEnd = DeclAttrs.end();
393       A != AEnd; ++A)
394    A->second->~AttrVec();
395}
396
397void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
398  Deallocations.push_back(std::make_pair(Callback, Data));
399}
400
401void
402ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) {
403  ExternalSource.reset(Source.take());
404}
405
406void ASTContext::PrintStats() const {
407  llvm::errs() << "\n*** AST Context Stats:\n";
408  llvm::errs() << "  " << Types.size() << " types total.\n";
409
410  unsigned counts[] = {
411#define TYPE(Name, Parent) 0,
412#define ABSTRACT_TYPE(Name, Parent)
413#include "clang/AST/TypeNodes.def"
414    0 // Extra
415  };
416
417  for (unsigned i = 0, e = Types.size(); i != e; ++i) {
418    Type *T = Types[i];
419    counts[(unsigned)T->getTypeClass()]++;
420  }
421
422  unsigned Idx = 0;
423  unsigned TotalBytes = 0;
424#define TYPE(Name, Parent)                                              \
425  if (counts[Idx])                                                      \
426    llvm::errs() << "    " << counts[Idx] << " " << #Name               \
427                 << " types\n";                                         \
428  TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
429  ++Idx;
430#define ABSTRACT_TYPE(Name, Parent)
431#include "clang/AST/TypeNodes.def"
432
433  llvm::errs() << "Total bytes = " << TotalBytes << "\n";
434
435  // Implicit special member functions.
436  llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
437               << NumImplicitDefaultConstructors
438               << " implicit default constructors created\n";
439  llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
440               << NumImplicitCopyConstructors
441               << " implicit copy constructors created\n";
442  if (getLangOpts().CPlusPlus)
443    llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
444                 << NumImplicitMoveConstructors
445                 << " implicit move constructors created\n";
446  llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
447               << NumImplicitCopyAssignmentOperators
448               << " implicit copy assignment operators created\n";
449  if (getLangOpts().CPlusPlus)
450    llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
451                 << NumImplicitMoveAssignmentOperators
452                 << " implicit move assignment operators created\n";
453  llvm::errs() << NumImplicitDestructorsDeclared << "/"
454               << NumImplicitDestructors
455               << " implicit destructors created\n";
456
457  if (ExternalSource.get()) {
458    llvm::errs() << "\n";
459    ExternalSource->PrintStats();
460  }
461
462  BumpAlloc.PrintStats();
463}
464
465TypedefDecl *ASTContext::getInt128Decl() const {
466  if (!Int128Decl) {
467    TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty);
468    Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
469                                     getTranslationUnitDecl(),
470                                     SourceLocation(),
471                                     SourceLocation(),
472                                     &Idents.get("__int128_t"),
473                                     TInfo);
474  }
475
476  return Int128Decl;
477}
478
479TypedefDecl *ASTContext::getUInt128Decl() const {
480  if (!UInt128Decl) {
481    TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty);
482    UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
483                                     getTranslationUnitDecl(),
484                                     SourceLocation(),
485                                     SourceLocation(),
486                                     &Idents.get("__uint128_t"),
487                                     TInfo);
488  }
489
490  return UInt128Decl;
491}
492
493void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
494  BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
495  R = CanQualType::CreateUnsafe(QualType(Ty, 0));
496  Types.push_back(Ty);
497}
498
499void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
500  assert((!this->Target || this->Target == &Target) &&
501         "Incorrect target reinitialization");
502  assert(VoidTy.isNull() && "Context reinitialized?");
503
504  this->Target = &Target;
505
506  ABI.reset(createCXXABI(Target));
507  AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
508
509  // C99 6.2.5p19.
510  InitBuiltinType(VoidTy,              BuiltinType::Void);
511
512  // C99 6.2.5p2.
513  InitBuiltinType(BoolTy,              BuiltinType::Bool);
514  // C99 6.2.5p3.
515  if (LangOpts.CharIsSigned)
516    InitBuiltinType(CharTy,            BuiltinType::Char_S);
517  else
518    InitBuiltinType(CharTy,            BuiltinType::Char_U);
519  // C99 6.2.5p4.
520  InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
521  InitBuiltinType(ShortTy,             BuiltinType::Short);
522  InitBuiltinType(IntTy,               BuiltinType::Int);
523  InitBuiltinType(LongTy,              BuiltinType::Long);
524  InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
525
526  // C99 6.2.5p6.
527  InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
528  InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
529  InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
530  InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
531  InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
532
533  // C99 6.2.5p10.
534  InitBuiltinType(FloatTy,             BuiltinType::Float);
535  InitBuiltinType(DoubleTy,            BuiltinType::Double);
536  InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
537
538  // GNU extension, 128-bit integers.
539  InitBuiltinType(Int128Ty,            BuiltinType::Int128);
540  InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
541
542  if (LangOpts.CPlusPlus) { // C++ 3.9.1p5
543    if (TargetInfo::isTypeSigned(Target.getWCharType()))
544      InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
545    else  // -fshort-wchar makes wchar_t be unsigned.
546      InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
547  } else // C99
548    WCharTy = getFromTargetType(Target.getWCharType());
549
550  WIntTy = getFromTargetType(Target.getWIntType());
551
552  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
553    InitBuiltinType(Char16Ty,           BuiltinType::Char16);
554  else // C99
555    Char16Ty = getFromTargetType(Target.getChar16Type());
556
557  if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
558    InitBuiltinType(Char32Ty,           BuiltinType::Char32);
559  else // C99
560    Char32Ty = getFromTargetType(Target.getChar32Type());
561
562  // Placeholder type for type-dependent expressions whose type is
563  // completely unknown. No code should ever check a type against
564  // DependentTy and users should never see it; however, it is here to
565  // help diagnose failures to properly check for type-dependent
566  // expressions.
567  InitBuiltinType(DependentTy,         BuiltinType::Dependent);
568
569  // Placeholder type for functions.
570  InitBuiltinType(OverloadTy,          BuiltinType::Overload);
571
572  // Placeholder type for bound members.
573  InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
574
575  // Placeholder type for pseudo-objects.
576  InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
577
578  // "any" type; useful for debugger-like clients.
579  InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
580
581  // Placeholder type for unbridged ARC casts.
582  InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
583
584  // C99 6.2.5p11.
585  FloatComplexTy      = getComplexType(FloatTy);
586  DoubleComplexTy     = getComplexType(DoubleTy);
587  LongDoubleComplexTy = getComplexType(LongDoubleTy);
588
589  // Builtin types for 'id', 'Class', and 'SEL'.
590  InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
591  InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
592  InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
593
594  // Builtin type for __objc_yes and __objc_no
595  ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
596                       SignedCharTy : BoolTy);
597
598  ObjCConstantStringType = QualType();
599
600  // void * type
601  VoidPtrTy = getPointerType(VoidTy);
602
603  // nullptr type (C++0x 2.14.7)
604  InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
605
606  // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
607  InitBuiltinType(HalfTy, BuiltinType::Half);
608}
609
610DiagnosticsEngine &ASTContext::getDiagnostics() const {
611  return SourceMgr.getDiagnostics();
612}
613
614AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
615  AttrVec *&Result = DeclAttrs[D];
616  if (!Result) {
617    void *Mem = Allocate(sizeof(AttrVec));
618    Result = new (Mem) AttrVec;
619  }
620
621  return *Result;
622}
623
624/// \brief Erase the attributes corresponding to the given declaration.
625void ASTContext::eraseDeclAttrs(const Decl *D) {
626  llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
627  if (Pos != DeclAttrs.end()) {
628    Pos->second->~AttrVec();
629    DeclAttrs.erase(Pos);
630  }
631}
632
633MemberSpecializationInfo *
634ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
635  assert(Var->isStaticDataMember() && "Not a static data member");
636  llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos
637    = InstantiatedFromStaticDataMember.find(Var);
638  if (Pos == InstantiatedFromStaticDataMember.end())
639    return 0;
640
641  return Pos->second;
642}
643
644void
645ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
646                                                TemplateSpecializationKind TSK,
647                                          SourceLocation PointOfInstantiation) {
648  assert(Inst->isStaticDataMember() && "Not a static data member");
649  assert(Tmpl->isStaticDataMember() && "Not a static data member");
650  assert(!InstantiatedFromStaticDataMember[Inst] &&
651         "Already noted what static data member was instantiated from");
652  InstantiatedFromStaticDataMember[Inst]
653    = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation);
654}
655
656FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
657                                                     const FunctionDecl *FD){
658  assert(FD && "Specialization is 0");
659  llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
660    = ClassScopeSpecializationPattern.find(FD);
661  if (Pos == ClassScopeSpecializationPattern.end())
662    return 0;
663
664  return Pos->second;
665}
666
667void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
668                                        FunctionDecl *Pattern) {
669  assert(FD && "Specialization is 0");
670  assert(Pattern && "Class scope specialization pattern is 0");
671  ClassScopeSpecializationPattern[FD] = Pattern;
672}
673
674NamedDecl *
675ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
676  llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
677    = InstantiatedFromUsingDecl.find(UUD);
678  if (Pos == InstantiatedFromUsingDecl.end())
679    return 0;
680
681  return Pos->second;
682}
683
684void
685ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
686  assert((isa<UsingDecl>(Pattern) ||
687          isa<UnresolvedUsingValueDecl>(Pattern) ||
688          isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
689         "pattern decl is not a using decl");
690  assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
691  InstantiatedFromUsingDecl[Inst] = Pattern;
692}
693
694UsingShadowDecl *
695ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
696  llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
697    = InstantiatedFromUsingShadowDecl.find(Inst);
698  if (Pos == InstantiatedFromUsingShadowDecl.end())
699    return 0;
700
701  return Pos->second;
702}
703
704void
705ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
706                                               UsingShadowDecl *Pattern) {
707  assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
708  InstantiatedFromUsingShadowDecl[Inst] = Pattern;
709}
710
711FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
712  llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
713    = InstantiatedFromUnnamedFieldDecl.find(Field);
714  if (Pos == InstantiatedFromUnnamedFieldDecl.end())
715    return 0;
716
717  return Pos->second;
718}
719
720void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
721                                                     FieldDecl *Tmpl) {
722  assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
723  assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
724  assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
725         "Already noted what unnamed field was instantiated from");
726
727  InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
728}
729
730bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD,
731                                    const FieldDecl *LastFD) const {
732  return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
733          FD->getBitWidthValue(*this) == 0);
734}
735
736bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD,
737                                             const FieldDecl *LastFD) const {
738  return (FD->isBitField() && LastFD && LastFD->isBitField() &&
739          FD->getBitWidthValue(*this) == 0 &&
740          LastFD->getBitWidthValue(*this) != 0);
741}
742
743bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD,
744                                         const FieldDecl *LastFD) const {
745  return (FD->isBitField() && LastFD && LastFD->isBitField() &&
746          FD->getBitWidthValue(*this) &&
747          LastFD->getBitWidthValue(*this));
748}
749
750bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD,
751                                         const FieldDecl *LastFD) const {
752  return (!FD->isBitField() && LastFD && LastFD->isBitField() &&
753          LastFD->getBitWidthValue(*this));
754}
755
756bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD,
757                                             const FieldDecl *LastFD) const {
758  return (FD->isBitField() && LastFD && !LastFD->isBitField() &&
759          FD->getBitWidthValue(*this));
760}
761
762ASTContext::overridden_cxx_method_iterator
763ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
764  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
765    = OverriddenMethods.find(Method);
766  if (Pos == OverriddenMethods.end())
767    return 0;
768
769  return Pos->second.begin();
770}
771
772ASTContext::overridden_cxx_method_iterator
773ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
774  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
775    = OverriddenMethods.find(Method);
776  if (Pos == OverriddenMethods.end())
777    return 0;
778
779  return Pos->second.end();
780}
781
782unsigned
783ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
784  llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
785    = OverriddenMethods.find(Method);
786  if (Pos == OverriddenMethods.end())
787    return 0;
788
789  return Pos->second.size();
790}
791
792void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
793                                     const CXXMethodDecl *Overridden) {
794  OverriddenMethods[Method].push_back(Overridden);
795}
796
797void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
798  assert(!Import->NextLocalImport && "Import declaration already in the chain");
799  assert(!Import->isFromASTFile() && "Non-local import declaration");
800  if (!FirstLocalImport) {
801    FirstLocalImport = Import;
802    LastLocalImport = Import;
803    return;
804  }
805
806  LastLocalImport->NextLocalImport = Import;
807  LastLocalImport = Import;
808}
809
810//===----------------------------------------------------------------------===//
811//                         Type Sizing and Analysis
812//===----------------------------------------------------------------------===//
813
814/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
815/// scalar floating point type.
816const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
817  const BuiltinType *BT = T->getAs<BuiltinType>();
818  assert(BT && "Not a floating point type!");
819  switch (BT->getKind()) {
820  default: llvm_unreachable("Not a floating point type!");
821  case BuiltinType::Half:       return Target->getHalfFormat();
822  case BuiltinType::Float:      return Target->getFloatFormat();
823  case BuiltinType::Double:     return Target->getDoubleFormat();
824  case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
825  }
826}
827
828/// getDeclAlign - Return a conservative estimate of the alignment of the
829/// specified decl.  Note that bitfields do not have a valid alignment, so
830/// this method will assert on them.
831/// If @p RefAsPointee, references are treated like their underlying type
832/// (for alignof), else they're treated like pointers (for CodeGen).
833CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
834  unsigned Align = Target->getCharWidth();
835
836  bool UseAlignAttrOnly = false;
837  if (unsigned AlignFromAttr = D->getMaxAlignment()) {
838    Align = AlignFromAttr;
839
840    // __attribute__((aligned)) can increase or decrease alignment
841    // *except* on a struct or struct member, where it only increases
842    // alignment unless 'packed' is also specified.
843    //
844    // It is an error for alignas to decrease alignment, so we can
845    // ignore that possibility;  Sema should diagnose it.
846    if (isa<FieldDecl>(D)) {
847      UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
848        cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
849    } else {
850      UseAlignAttrOnly = true;
851    }
852  }
853  else if (isa<FieldDecl>(D))
854      UseAlignAttrOnly =
855        D->hasAttr<PackedAttr>() ||
856        cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
857
858  // If we're using the align attribute only, just ignore everything
859  // else about the declaration and its type.
860  if (UseAlignAttrOnly) {
861    // do nothing
862
863  } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
864    QualType T = VD->getType();
865    if (const ReferenceType* RT = T->getAs<ReferenceType>()) {
866      if (RefAsPointee)
867        T = RT->getPointeeType();
868      else
869        T = getPointerType(RT->getPointeeType());
870    }
871    if (!T->isIncompleteType() && !T->isFunctionType()) {
872      // Adjust alignments of declarations with array type by the
873      // large-array alignment on the target.
874      unsigned MinWidth = Target->getLargeArrayMinWidth();
875      const ArrayType *arrayType;
876      if (MinWidth && (arrayType = getAsArrayType(T))) {
877        if (isa<VariableArrayType>(arrayType))
878          Align = std::max(Align, Target->getLargeArrayAlign());
879        else if (isa<ConstantArrayType>(arrayType) &&
880                 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
881          Align = std::max(Align, Target->getLargeArrayAlign());
882
883        // Walk through any array types while we're at it.
884        T = getBaseElementType(arrayType);
885      }
886      Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
887    }
888
889    // Fields can be subject to extra alignment constraints, like if
890    // the field is packed, the struct is packed, or the struct has a
891    // a max-field-alignment constraint (#pragma pack).  So calculate
892    // the actual alignment of the field within the struct, and then
893    // (as we're expected to) constrain that by the alignment of the type.
894    if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) {
895      // So calculate the alignment of the field.
896      const ASTRecordLayout &layout = getASTRecordLayout(field->getParent());
897
898      // Start with the record's overall alignment.
899      unsigned fieldAlign = toBits(layout.getAlignment());
900
901      // Use the GCD of that and the offset within the record.
902      uint64_t offset = layout.getFieldOffset(field->getFieldIndex());
903      if (offset > 0) {
904        // Alignment is always a power of 2, so the GCD will be a power of 2,
905        // which means we get to do this crazy thing instead of Euclid's.
906        uint64_t lowBitOfOffset = offset & (~offset + 1);
907        if (lowBitOfOffset < fieldAlign)
908          fieldAlign = static_cast<unsigned>(lowBitOfOffset);
909      }
910
911      Align = std::min(Align, fieldAlign);
912    }
913  }
914
915  return toCharUnitsFromBits(Align);
916}
917
918std::pair<CharUnits, CharUnits>
919ASTContext::getTypeInfoInChars(const Type *T) const {
920  std::pair<uint64_t, unsigned> Info = getTypeInfo(T);
921  return std::make_pair(toCharUnitsFromBits(Info.first),
922                        toCharUnitsFromBits(Info.second));
923}
924
925std::pair<CharUnits, CharUnits>
926ASTContext::getTypeInfoInChars(QualType T) const {
927  return getTypeInfoInChars(T.getTypePtr());
928}
929
930std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const {
931  TypeInfoMap::iterator it = MemoizedTypeInfo.find(T);
932  if (it != MemoizedTypeInfo.end())
933    return it->second;
934
935  std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T);
936  MemoizedTypeInfo.insert(std::make_pair(T, Info));
937  return Info;
938}
939
940/// getTypeInfoImpl - Return the size of the specified type, in bits.  This
941/// method does not work on incomplete types.
942///
943/// FIXME: Pointers into different addr spaces could have different sizes and
944/// alignment requirements: getPointerInfo should take an AddrSpace, this
945/// should take a QualType, &c.
946std::pair<uint64_t, unsigned>
947ASTContext::getTypeInfoImpl(const Type *T) const {
948  uint64_t Width=0;
949  unsigned Align=8;
950  switch (T->getTypeClass()) {
951#define TYPE(Class, Base)
952#define ABSTRACT_TYPE(Class, Base)
953#define NON_CANONICAL_TYPE(Class, Base)
954#define DEPENDENT_TYPE(Class, Base) case Type::Class:
955#include "clang/AST/TypeNodes.def"
956    llvm_unreachable("Should not see dependent types");
957
958  case Type::FunctionNoProto:
959  case Type::FunctionProto:
960    // GCC extension: alignof(function) = 32 bits
961    Width = 0;
962    Align = 32;
963    break;
964
965  case Type::IncompleteArray:
966  case Type::VariableArray:
967    Width = 0;
968    Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
969    break;
970
971  case Type::ConstantArray: {
972    const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
973
974    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType());
975    uint64_t Size = CAT->getSize().getZExtValue();
976    assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) &&
977           "Overflow in array type bit size evaluation");
978    Width = EltInfo.first*Size;
979    Align = EltInfo.second;
980    Width = llvm::RoundUpToAlignment(Width, Align);
981    break;
982  }
983  case Type::ExtVector:
984  case Type::Vector: {
985    const VectorType *VT = cast<VectorType>(T);
986    std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType());
987    Width = EltInfo.first*VT->getNumElements();
988    Align = Width;
989    // If the alignment is not a power of 2, round up to the next power of 2.
990    // This happens for non-power-of-2 length vectors.
991    if (Align & (Align-1)) {
992      Align = llvm::NextPowerOf2(Align);
993      Width = llvm::RoundUpToAlignment(Width, Align);
994    }
995    break;
996  }
997
998  case Type::Builtin:
999    switch (cast<BuiltinType>(T)->getKind()) {
1000    default: llvm_unreachable("Unknown builtin type!");
1001    case BuiltinType::Void:
1002      // GCC extension: alignof(void) = 8 bits.
1003      Width = 0;
1004      Align = 8;
1005      break;
1006
1007    case BuiltinType::Bool:
1008      Width = Target->getBoolWidth();
1009      Align = Target->getBoolAlign();
1010      break;
1011    case BuiltinType::Char_S:
1012    case BuiltinType::Char_U:
1013    case BuiltinType::UChar:
1014    case BuiltinType::SChar:
1015      Width = Target->getCharWidth();
1016      Align = Target->getCharAlign();
1017      break;
1018    case BuiltinType::WChar_S:
1019    case BuiltinType::WChar_U:
1020      Width = Target->getWCharWidth();
1021      Align = Target->getWCharAlign();
1022      break;
1023    case BuiltinType::Char16:
1024      Width = Target->getChar16Width();
1025      Align = Target->getChar16Align();
1026      break;
1027    case BuiltinType::Char32:
1028      Width = Target->getChar32Width();
1029      Align = Target->getChar32Align();
1030      break;
1031    case BuiltinType::UShort:
1032    case BuiltinType::Short:
1033      Width = Target->getShortWidth();
1034      Align = Target->getShortAlign();
1035      break;
1036    case BuiltinType::UInt:
1037    case BuiltinType::Int:
1038      Width = Target->getIntWidth();
1039      Align = Target->getIntAlign();
1040      break;
1041    case BuiltinType::ULong:
1042    case BuiltinType::Long:
1043      Width = Target->getLongWidth();
1044      Align = Target->getLongAlign();
1045      break;
1046    case BuiltinType::ULongLong:
1047    case BuiltinType::LongLong:
1048      Width = Target->getLongLongWidth();
1049      Align = Target->getLongLongAlign();
1050      break;
1051    case BuiltinType::Int128:
1052    case BuiltinType::UInt128:
1053      Width = 128;
1054      Align = 128; // int128_t is 128-bit aligned on all targets.
1055      break;
1056    case BuiltinType::Half:
1057      Width = Target->getHalfWidth();
1058      Align = Target->getHalfAlign();
1059      break;
1060    case BuiltinType::Float:
1061      Width = Target->getFloatWidth();
1062      Align = Target->getFloatAlign();
1063      break;
1064    case BuiltinType::Double:
1065      Width = Target->getDoubleWidth();
1066      Align = Target->getDoubleAlign();
1067      break;
1068    case BuiltinType::LongDouble:
1069      Width = Target->getLongDoubleWidth();
1070      Align = Target->getLongDoubleAlign();
1071      break;
1072    case BuiltinType::NullPtr:
1073      Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1074      Align = Target->getPointerAlign(0); //   == sizeof(void*)
1075      break;
1076    case BuiltinType::ObjCId:
1077    case BuiltinType::ObjCClass:
1078    case BuiltinType::ObjCSel:
1079      Width = Target->getPointerWidth(0);
1080      Align = Target->getPointerAlign(0);
1081      break;
1082    }
1083    break;
1084  case Type::ObjCObjectPointer:
1085    Width = Target->getPointerWidth(0);
1086    Align = Target->getPointerAlign(0);
1087    break;
1088  case Type::BlockPointer: {
1089    unsigned AS = getTargetAddressSpace(
1090        cast<BlockPointerType>(T)->getPointeeType());
1091    Width = Target->getPointerWidth(AS);
1092    Align = Target->getPointerAlign(AS);
1093    break;
1094  }
1095  case Type::LValueReference:
1096  case Type::RValueReference: {
1097    // alignof and sizeof should never enter this code path here, so we go
1098    // the pointer route.
1099    unsigned AS = getTargetAddressSpace(
1100        cast<ReferenceType>(T)->getPointeeType());
1101    Width = Target->getPointerWidth(AS);
1102    Align = Target->getPointerAlign(AS);
1103    break;
1104  }
1105  case Type::Pointer: {
1106    unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1107    Width = Target->getPointerWidth(AS);
1108    Align = Target->getPointerAlign(AS);
1109    break;
1110  }
1111  case Type::MemberPointer: {
1112    const MemberPointerType *MPT = cast<MemberPointerType>(T);
1113    std::pair<uint64_t, unsigned> PtrDiffInfo =
1114      getTypeInfo(getPointerDiffType());
1115    Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT);
1116    Align = PtrDiffInfo.second;
1117    break;
1118  }
1119  case Type::Complex: {
1120    // Complex types have the same alignment as their elements, but twice the
1121    // size.
1122    std::pair<uint64_t, unsigned> EltInfo =
1123      getTypeInfo(cast<ComplexType>(T)->getElementType());
1124    Width = EltInfo.first*2;
1125    Align = EltInfo.second;
1126    break;
1127  }
1128  case Type::ObjCObject:
1129    return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1130  case Type::ObjCInterface: {
1131    const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1132    const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1133    Width = toBits(Layout.getSize());
1134    Align = toBits(Layout.getAlignment());
1135    break;
1136  }
1137  case Type::Record:
1138  case Type::Enum: {
1139    const TagType *TT = cast<TagType>(T);
1140
1141    if (TT->getDecl()->isInvalidDecl()) {
1142      Width = 8;
1143      Align = 8;
1144      break;
1145    }
1146
1147    if (const EnumType *ET = dyn_cast<EnumType>(TT))
1148      return getTypeInfo(ET->getDecl()->getIntegerType());
1149
1150    const RecordType *RT = cast<RecordType>(TT);
1151    const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl());
1152    Width = toBits(Layout.getSize());
1153    Align = toBits(Layout.getAlignment());
1154    break;
1155  }
1156
1157  case Type::SubstTemplateTypeParm:
1158    return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1159                       getReplacementType().getTypePtr());
1160
1161  case Type::Auto: {
1162    const AutoType *A = cast<AutoType>(T);
1163    assert(A->isDeduced() && "Cannot request the size of a dependent type");
1164    return getTypeInfo(A->getDeducedType().getTypePtr());
1165  }
1166
1167  case Type::Paren:
1168    return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1169
1170  case Type::Typedef: {
1171    const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1172    std::pair<uint64_t, unsigned> Info
1173      = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1174    // If the typedef has an aligned attribute on it, it overrides any computed
1175    // alignment we have.  This violates the GCC documentation (which says that
1176    // attribute(aligned) can only round up) but matches its implementation.
1177    if (unsigned AttrAlign = Typedef->getMaxAlignment())
1178      Align = AttrAlign;
1179    else
1180      Align = Info.second;
1181    Width = Info.first;
1182    break;
1183  }
1184
1185  case Type::TypeOfExpr:
1186    return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType()
1187                         .getTypePtr());
1188
1189  case Type::TypeOf:
1190    return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr());
1191
1192  case Type::Decltype:
1193    return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType()
1194                        .getTypePtr());
1195
1196  case Type::UnaryTransform:
1197    return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType());
1198
1199  case Type::Elaborated:
1200    return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1201
1202  case Type::Attributed:
1203    return getTypeInfo(
1204                  cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1205
1206  case Type::TemplateSpecialization: {
1207    assert(getCanonicalType(T) != T &&
1208           "Cannot request the size of a dependent type");
1209    const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T);
1210    // A type alias template specialization may refer to a typedef with the
1211    // aligned attribute on it.
1212    if (TST->isTypeAlias())
1213      return getTypeInfo(TST->getAliasedType().getTypePtr());
1214    else
1215      return getTypeInfo(getCanonicalType(T));
1216  }
1217
1218  case Type::Atomic: {
1219    std::pair<uint64_t, unsigned> Info
1220      = getTypeInfo(cast<AtomicType>(T)->getValueType());
1221    Width = Info.first;
1222    Align = Info.second;
1223    if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() &&
1224        llvm::isPowerOf2_64(Width)) {
1225      // We can potentially perform lock-free atomic operations for this
1226      // type; promote the alignment appropriately.
1227      // FIXME: We could potentially promote the width here as well...
1228      // is that worthwhile?  (Non-struct atomic types generally have
1229      // power-of-two size anyway, but structs might not.  Requires a bit
1230      // of implementation work to make sure we zero out the extra bits.)
1231      Align = static_cast<unsigned>(Width);
1232    }
1233  }
1234
1235  }
1236
1237  assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1238  return std::make_pair(Width, Align);
1239}
1240
1241/// toCharUnitsFromBits - Convert a size in bits to a size in characters.
1242CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1243  return CharUnits::fromQuantity(BitSize / getCharWidth());
1244}
1245
1246/// toBits - Convert a size in characters to a size in characters.
1247int64_t ASTContext::toBits(CharUnits CharSize) const {
1248  return CharSize.getQuantity() * getCharWidth();
1249}
1250
1251/// getTypeSizeInChars - Return the size of the specified type, in characters.
1252/// This method does not work on incomplete types.
1253CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1254  return toCharUnitsFromBits(getTypeSize(T));
1255}
1256CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1257  return toCharUnitsFromBits(getTypeSize(T));
1258}
1259
1260/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1261/// characters. This method does not work on incomplete types.
1262CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1263  return toCharUnitsFromBits(getTypeAlign(T));
1264}
1265CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1266  return toCharUnitsFromBits(getTypeAlign(T));
1267}
1268
1269/// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1270/// type for the current target in bits.  This can be different than the ABI
1271/// alignment in cases where it is beneficial for performance to overalign
1272/// a data type.
1273unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1274  unsigned ABIAlign = getTypeAlign(T);
1275
1276  // Double and long long should be naturally aligned if possible.
1277  if (const ComplexType* CT = T->getAs<ComplexType>())
1278    T = CT->getElementType().getTypePtr();
1279  if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1280      T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1281      T->isSpecificBuiltinType(BuiltinType::ULongLong))
1282    return std::max(ABIAlign, (unsigned)getTypeSize(T));
1283
1284  return ABIAlign;
1285}
1286
1287/// DeepCollectObjCIvars -
1288/// This routine first collects all declared, but not synthesized, ivars in
1289/// super class and then collects all ivars, including those synthesized for
1290/// current class. This routine is used for implementation of current class
1291/// when all ivars, declared and synthesized are known.
1292///
1293void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1294                                      bool leafClass,
1295                            SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1296  if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1297    DeepCollectObjCIvars(SuperClass, false, Ivars);
1298  if (!leafClass) {
1299    for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1300         E = OI->ivar_end(); I != E; ++I)
1301      Ivars.push_back(*I);
1302  } else {
1303    ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1304    for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1305         Iv= Iv->getNextIvar())
1306      Ivars.push_back(Iv);
1307  }
1308}
1309
1310/// CollectInheritedProtocols - Collect all protocols in current class and
1311/// those inherited by it.
1312void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1313                          llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1314  if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1315    // We can use protocol_iterator here instead of
1316    // all_referenced_protocol_iterator since we are walking all categories.
1317    for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(),
1318         PE = OI->all_referenced_protocol_end(); P != PE; ++P) {
1319      ObjCProtocolDecl *Proto = (*P);
1320      Protocols.insert(Proto->getCanonicalDecl());
1321      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1322           PE = Proto->protocol_end(); P != PE; ++P) {
1323        Protocols.insert((*P)->getCanonicalDecl());
1324        CollectInheritedProtocols(*P, Protocols);
1325      }
1326    }
1327
1328    // Categories of this Interface.
1329    for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList();
1330         CDeclChain; CDeclChain = CDeclChain->getNextClassCategory())
1331      CollectInheritedProtocols(CDeclChain, Protocols);
1332    if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1333      while (SD) {
1334        CollectInheritedProtocols(SD, Protocols);
1335        SD = SD->getSuperClass();
1336      }
1337  } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1338    for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(),
1339         PE = OC->protocol_end(); P != PE; ++P) {
1340      ObjCProtocolDecl *Proto = (*P);
1341      Protocols.insert(Proto->getCanonicalDecl());
1342      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1343           PE = Proto->protocol_end(); P != PE; ++P)
1344        CollectInheritedProtocols(*P, Protocols);
1345    }
1346  } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1347    for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(),
1348         PE = OP->protocol_end(); P != PE; ++P) {
1349      ObjCProtocolDecl *Proto = (*P);
1350      Protocols.insert(Proto->getCanonicalDecl());
1351      for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(),
1352           PE = Proto->protocol_end(); P != PE; ++P)
1353        CollectInheritedProtocols(*P, Protocols);
1354    }
1355  }
1356}
1357
1358unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1359  unsigned count = 0;
1360  // Count ivars declared in class extension.
1361  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1362       CDecl = CDecl->getNextClassExtension())
1363    count += CDecl->ivar_size();
1364
1365  // Count ivar defined in this class's implementation.  This
1366  // includes synthesized ivars.
1367  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1368    count += ImplDecl->ivar_size();
1369
1370  return count;
1371}
1372
1373bool ASTContext::isSentinelNullExpr(const Expr *E) {
1374  if (!E)
1375    return false;
1376
1377  // nullptr_t is always treated as null.
1378  if (E->getType()->isNullPtrType()) return true;
1379
1380  if (E->getType()->isAnyPointerType() &&
1381      E->IgnoreParenCasts()->isNullPointerConstant(*this,
1382                                                Expr::NPC_ValueDependentIsNull))
1383    return true;
1384
1385  // Unfortunately, __null has type 'int'.
1386  if (isa<GNUNullExpr>(E)) return true;
1387
1388  return false;
1389}
1390
1391/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
1392ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1393  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1394    I = ObjCImpls.find(D);
1395  if (I != ObjCImpls.end())
1396    return cast<ObjCImplementationDecl>(I->second);
1397  return 0;
1398}
1399/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
1400ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1401  llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1402    I = ObjCImpls.find(D);
1403  if (I != ObjCImpls.end())
1404    return cast<ObjCCategoryImplDecl>(I->second);
1405  return 0;
1406}
1407
1408/// \brief Set the implementation of ObjCInterfaceDecl.
1409void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1410                           ObjCImplementationDecl *ImplD) {
1411  assert(IFaceD && ImplD && "Passed null params");
1412  ObjCImpls[IFaceD] = ImplD;
1413}
1414/// \brief Set the implementation of ObjCCategoryDecl.
1415void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
1416                           ObjCCategoryImplDecl *ImplD) {
1417  assert(CatD && ImplD && "Passed null params");
1418  ObjCImpls[CatD] = ImplD;
1419}
1420
1421ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const {
1422  if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
1423    return ID;
1424  if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
1425    return CD->getClassInterface();
1426  if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
1427    return IMD->getClassInterface();
1428
1429  return 0;
1430}
1431
1432/// \brief Get the copy initialization expression of VarDecl,or NULL if
1433/// none exists.
1434Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
1435  assert(VD && "Passed null params");
1436  assert(VD->hasAttr<BlocksAttr>() &&
1437         "getBlockVarCopyInits - not __block var");
1438  llvm::DenseMap<const VarDecl*, Expr*>::iterator
1439    I = BlockVarCopyInits.find(VD);
1440  return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0;
1441}
1442
1443/// \brief Set the copy inialization expression of a block var decl.
1444void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
1445  assert(VD && Init && "Passed null params");
1446  assert(VD->hasAttr<BlocksAttr>() &&
1447         "setBlockVarCopyInits - not __block var");
1448  BlockVarCopyInits[VD] = Init;
1449}
1450
1451TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
1452                                                 unsigned DataSize) const {
1453  if (!DataSize)
1454    DataSize = TypeLoc::getFullDataSizeForType(T);
1455  else
1456    assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
1457           "incorrect data size provided to CreateTypeSourceInfo!");
1458
1459  TypeSourceInfo *TInfo =
1460    (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
1461  new (TInfo) TypeSourceInfo(T);
1462  return TInfo;
1463}
1464
1465TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
1466                                                     SourceLocation L) const {
1467  TypeSourceInfo *DI = CreateTypeSourceInfo(T);
1468  DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
1469  return DI;
1470}
1471
1472const ASTRecordLayout &
1473ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
1474  return getObjCLayout(D, 0);
1475}
1476
1477const ASTRecordLayout &
1478ASTContext::getASTObjCImplementationLayout(
1479                                        const ObjCImplementationDecl *D) const {
1480  return getObjCLayout(D->getClassInterface(), D);
1481}
1482
1483//===----------------------------------------------------------------------===//
1484//                   Type creation/memoization methods
1485//===----------------------------------------------------------------------===//
1486
1487QualType
1488ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
1489  unsigned fastQuals = quals.getFastQualifiers();
1490  quals.removeFastQualifiers();
1491
1492  // Check if we've already instantiated this type.
1493  llvm::FoldingSetNodeID ID;
1494  ExtQuals::Profile(ID, baseType, quals);
1495  void *insertPos = 0;
1496  if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
1497    assert(eq->getQualifiers() == quals);
1498    return QualType(eq, fastQuals);
1499  }
1500
1501  // If the base type is not canonical, make the appropriate canonical type.
1502  QualType canon;
1503  if (!baseType->isCanonicalUnqualified()) {
1504    SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
1505    canonSplit.Quals.addConsistentQualifiers(quals);
1506    canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
1507
1508    // Re-find the insert position.
1509    (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
1510  }
1511
1512  ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
1513  ExtQualNodes.InsertNode(eq, insertPos);
1514  return QualType(eq, fastQuals);
1515}
1516
1517QualType
1518ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
1519  QualType CanT = getCanonicalType(T);
1520  if (CanT.getAddressSpace() == AddressSpace)
1521    return T;
1522
1523  // If we are composing extended qualifiers together, merge together
1524  // into one ExtQuals node.
1525  QualifierCollector Quals;
1526  const Type *TypeNode = Quals.strip(T);
1527
1528  // If this type already has an address space specified, it cannot get
1529  // another one.
1530  assert(!Quals.hasAddressSpace() &&
1531         "Type cannot be in multiple addr spaces!");
1532  Quals.addAddressSpace(AddressSpace);
1533
1534  return getExtQualType(TypeNode, Quals);
1535}
1536
1537QualType ASTContext::getObjCGCQualType(QualType T,
1538                                       Qualifiers::GC GCAttr) const {
1539  QualType CanT = getCanonicalType(T);
1540  if (CanT.getObjCGCAttr() == GCAttr)
1541    return T;
1542
1543  if (const PointerType *ptr = T->getAs<PointerType>()) {
1544    QualType Pointee = ptr->getPointeeType();
1545    if (Pointee->isAnyPointerType()) {
1546      QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
1547      return getPointerType(ResultType);
1548    }
1549  }
1550
1551  // If we are composing extended qualifiers together, merge together
1552  // into one ExtQuals node.
1553  QualifierCollector Quals;
1554  const Type *TypeNode = Quals.strip(T);
1555
1556  // If this type already has an ObjCGC specified, it cannot get
1557  // another one.
1558  assert(!Quals.hasObjCGCAttr() &&
1559         "Type cannot have multiple ObjCGCs!");
1560  Quals.addObjCGCAttr(GCAttr);
1561
1562  return getExtQualType(TypeNode, Quals);
1563}
1564
1565const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
1566                                                   FunctionType::ExtInfo Info) {
1567  if (T->getExtInfo() == Info)
1568    return T;
1569
1570  QualType Result;
1571  if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
1572    Result = getFunctionNoProtoType(FNPT->getResultType(), Info);
1573  } else {
1574    const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
1575    FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
1576    EPI.ExtInfo = Info;
1577    Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(),
1578                             FPT->getNumArgs(), EPI);
1579  }
1580
1581  return cast<FunctionType>(Result.getTypePtr());
1582}
1583
1584/// getComplexType - Return the uniqued reference to the type for a complex
1585/// number with the specified element type.
1586QualType ASTContext::getComplexType(QualType T) const {
1587  // Unique pointers, to guarantee there is only one pointer of a particular
1588  // structure.
1589  llvm::FoldingSetNodeID ID;
1590  ComplexType::Profile(ID, T);
1591
1592  void *InsertPos = 0;
1593  if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
1594    return QualType(CT, 0);
1595
1596  // If the pointee type isn't canonical, this won't be a canonical type either,
1597  // so fill in the canonical type field.
1598  QualType Canonical;
1599  if (!T.isCanonical()) {
1600    Canonical = getComplexType(getCanonicalType(T));
1601
1602    // Get the new insert position for the node we care about.
1603    ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
1604    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1605  }
1606  ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
1607  Types.push_back(New);
1608  ComplexTypes.InsertNode(New, InsertPos);
1609  return QualType(New, 0);
1610}
1611
1612/// getPointerType - Return the uniqued reference to the type for a pointer to
1613/// the specified type.
1614QualType ASTContext::getPointerType(QualType T) const {
1615  // Unique pointers, to guarantee there is only one pointer of a particular
1616  // structure.
1617  llvm::FoldingSetNodeID ID;
1618  PointerType::Profile(ID, T);
1619
1620  void *InsertPos = 0;
1621  if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1622    return QualType(PT, 0);
1623
1624  // If the pointee type isn't canonical, this won't be a canonical type either,
1625  // so fill in the canonical type field.
1626  QualType Canonical;
1627  if (!T.isCanonical()) {
1628    Canonical = getPointerType(getCanonicalType(T));
1629
1630    // Get the new insert position for the node we care about.
1631    PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1632    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1633  }
1634  PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
1635  Types.push_back(New);
1636  PointerTypes.InsertNode(New, InsertPos);
1637  return QualType(New, 0);
1638}
1639
1640/// getBlockPointerType - Return the uniqued reference to the type for
1641/// a pointer to the specified block.
1642QualType ASTContext::getBlockPointerType(QualType T) const {
1643  assert(T->isFunctionType() && "block of function types only");
1644  // Unique pointers, to guarantee there is only one block of a particular
1645  // structure.
1646  llvm::FoldingSetNodeID ID;
1647  BlockPointerType::Profile(ID, T);
1648
1649  void *InsertPos = 0;
1650  if (BlockPointerType *PT =
1651        BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1652    return QualType(PT, 0);
1653
1654  // If the block pointee type isn't canonical, this won't be a canonical
1655  // type either so fill in the canonical type field.
1656  QualType Canonical;
1657  if (!T.isCanonical()) {
1658    Canonical = getBlockPointerType(getCanonicalType(T));
1659
1660    // Get the new insert position for the node we care about.
1661    BlockPointerType *NewIP =
1662      BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1663    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1664  }
1665  BlockPointerType *New
1666    = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
1667  Types.push_back(New);
1668  BlockPointerTypes.InsertNode(New, InsertPos);
1669  return QualType(New, 0);
1670}
1671
1672/// getLValueReferenceType - Return the uniqued reference to the type for an
1673/// lvalue reference to the specified type.
1674QualType
1675ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
1676  assert(getCanonicalType(T) != OverloadTy &&
1677         "Unresolved overloaded function type");
1678
1679  // Unique pointers, to guarantee there is only one pointer of a particular
1680  // structure.
1681  llvm::FoldingSetNodeID ID;
1682  ReferenceType::Profile(ID, T, SpelledAsLValue);
1683
1684  void *InsertPos = 0;
1685  if (LValueReferenceType *RT =
1686        LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1687    return QualType(RT, 0);
1688
1689  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1690
1691  // If the referencee type isn't canonical, this won't be a canonical type
1692  // either, so fill in the canonical type field.
1693  QualType Canonical;
1694  if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
1695    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1696    Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
1697
1698    // Get the new insert position for the node we care about.
1699    LValueReferenceType *NewIP =
1700      LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1701    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1702  }
1703
1704  LValueReferenceType *New
1705    = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
1706                                                     SpelledAsLValue);
1707  Types.push_back(New);
1708  LValueReferenceTypes.InsertNode(New, InsertPos);
1709
1710  return QualType(New, 0);
1711}
1712
1713/// getRValueReferenceType - Return the uniqued reference to the type for an
1714/// rvalue reference to the specified type.
1715QualType ASTContext::getRValueReferenceType(QualType T) const {
1716  // Unique pointers, to guarantee there is only one pointer of a particular
1717  // structure.
1718  llvm::FoldingSetNodeID ID;
1719  ReferenceType::Profile(ID, T, false);
1720
1721  void *InsertPos = 0;
1722  if (RValueReferenceType *RT =
1723        RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
1724    return QualType(RT, 0);
1725
1726  const ReferenceType *InnerRef = T->getAs<ReferenceType>();
1727
1728  // If the referencee type isn't canonical, this won't be a canonical type
1729  // either, so fill in the canonical type field.
1730  QualType Canonical;
1731  if (InnerRef || !T.isCanonical()) {
1732    QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
1733    Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
1734
1735    // Get the new insert position for the node we care about.
1736    RValueReferenceType *NewIP =
1737      RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
1738    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1739  }
1740
1741  RValueReferenceType *New
1742    = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
1743  Types.push_back(New);
1744  RValueReferenceTypes.InsertNode(New, InsertPos);
1745  return QualType(New, 0);
1746}
1747
1748/// getMemberPointerType - Return the uniqued reference to the type for a
1749/// member pointer to the specified type, in the specified class.
1750QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
1751  // Unique pointers, to guarantee there is only one pointer of a particular
1752  // structure.
1753  llvm::FoldingSetNodeID ID;
1754  MemberPointerType::Profile(ID, T, Cls);
1755
1756  void *InsertPos = 0;
1757  if (MemberPointerType *PT =
1758      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
1759    return QualType(PT, 0);
1760
1761  // If the pointee or class type isn't canonical, this won't be a canonical
1762  // type either, so fill in the canonical type field.
1763  QualType Canonical;
1764  if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
1765    Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
1766
1767    // Get the new insert position for the node we care about.
1768    MemberPointerType *NewIP =
1769      MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
1770    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1771  }
1772  MemberPointerType *New
1773    = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
1774  Types.push_back(New);
1775  MemberPointerTypes.InsertNode(New, InsertPos);
1776  return QualType(New, 0);
1777}
1778
1779/// getConstantArrayType - Return the unique reference to the type for an
1780/// array of the specified element type.
1781QualType ASTContext::getConstantArrayType(QualType EltTy,
1782                                          const llvm::APInt &ArySizeIn,
1783                                          ArrayType::ArraySizeModifier ASM,
1784                                          unsigned IndexTypeQuals) const {
1785  assert((EltTy->isDependentType() ||
1786          EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
1787         "Constant array of VLAs is illegal!");
1788
1789  // Convert the array size into a canonical width matching the pointer size for
1790  // the target.
1791  llvm::APInt ArySize(ArySizeIn);
1792  ArySize =
1793    ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
1794
1795  llvm::FoldingSetNodeID ID;
1796  ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
1797
1798  void *InsertPos = 0;
1799  if (ConstantArrayType *ATP =
1800      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
1801    return QualType(ATP, 0);
1802
1803  // If the element type isn't canonical or has qualifiers, this won't
1804  // be a canonical type either, so fill in the canonical type field.
1805  QualType Canon;
1806  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1807    SplitQualType canonSplit = getCanonicalType(EltTy).split();
1808    Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
1809                                 ASM, IndexTypeQuals);
1810    Canon = getQualifiedType(Canon, canonSplit.Quals);
1811
1812    // Get the new insert position for the node we care about.
1813    ConstantArrayType *NewIP =
1814      ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
1815    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
1816  }
1817
1818  ConstantArrayType *New = new(*this,TypeAlignment)
1819    ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
1820  ConstantArrayTypes.InsertNode(New, InsertPos);
1821  Types.push_back(New);
1822  return QualType(New, 0);
1823}
1824
1825/// getVariableArrayDecayedType - Turns the given type, which may be
1826/// variably-modified, into the corresponding type with all the known
1827/// sizes replaced with [*].
1828QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
1829  // Vastly most common case.
1830  if (!type->isVariablyModifiedType()) return type;
1831
1832  QualType result;
1833
1834  SplitQualType split = type.getSplitDesugaredType();
1835  const Type *ty = split.Ty;
1836  switch (ty->getTypeClass()) {
1837#define TYPE(Class, Base)
1838#define ABSTRACT_TYPE(Class, Base)
1839#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
1840#include "clang/AST/TypeNodes.def"
1841    llvm_unreachable("didn't desugar past all non-canonical types?");
1842
1843  // These types should never be variably-modified.
1844  case Type::Builtin:
1845  case Type::Complex:
1846  case Type::Vector:
1847  case Type::ExtVector:
1848  case Type::DependentSizedExtVector:
1849  case Type::ObjCObject:
1850  case Type::ObjCInterface:
1851  case Type::ObjCObjectPointer:
1852  case Type::Record:
1853  case Type::Enum:
1854  case Type::UnresolvedUsing:
1855  case Type::TypeOfExpr:
1856  case Type::TypeOf:
1857  case Type::Decltype:
1858  case Type::UnaryTransform:
1859  case Type::DependentName:
1860  case Type::InjectedClassName:
1861  case Type::TemplateSpecialization:
1862  case Type::DependentTemplateSpecialization:
1863  case Type::TemplateTypeParm:
1864  case Type::SubstTemplateTypeParmPack:
1865  case Type::Auto:
1866  case Type::PackExpansion:
1867    llvm_unreachable("type should never be variably-modified");
1868
1869  // These types can be variably-modified but should never need to
1870  // further decay.
1871  case Type::FunctionNoProto:
1872  case Type::FunctionProto:
1873  case Type::BlockPointer:
1874  case Type::MemberPointer:
1875    return type;
1876
1877  // These types can be variably-modified.  All these modifications
1878  // preserve structure except as noted by comments.
1879  // TODO: if we ever care about optimizing VLAs, there are no-op
1880  // optimizations available here.
1881  case Type::Pointer:
1882    result = getPointerType(getVariableArrayDecayedType(
1883                              cast<PointerType>(ty)->getPointeeType()));
1884    break;
1885
1886  case Type::LValueReference: {
1887    const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
1888    result = getLValueReferenceType(
1889                 getVariableArrayDecayedType(lv->getPointeeType()),
1890                                    lv->isSpelledAsLValue());
1891    break;
1892  }
1893
1894  case Type::RValueReference: {
1895    const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
1896    result = getRValueReferenceType(
1897                 getVariableArrayDecayedType(lv->getPointeeType()));
1898    break;
1899  }
1900
1901  case Type::Atomic: {
1902    const AtomicType *at = cast<AtomicType>(ty);
1903    result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
1904    break;
1905  }
1906
1907  case Type::ConstantArray: {
1908    const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
1909    result = getConstantArrayType(
1910                 getVariableArrayDecayedType(cat->getElementType()),
1911                                  cat->getSize(),
1912                                  cat->getSizeModifier(),
1913                                  cat->getIndexTypeCVRQualifiers());
1914    break;
1915  }
1916
1917  case Type::DependentSizedArray: {
1918    const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
1919    result = getDependentSizedArrayType(
1920                 getVariableArrayDecayedType(dat->getElementType()),
1921                                        dat->getSizeExpr(),
1922                                        dat->getSizeModifier(),
1923                                        dat->getIndexTypeCVRQualifiers(),
1924                                        dat->getBracketsRange());
1925    break;
1926  }
1927
1928  // Turn incomplete types into [*] types.
1929  case Type::IncompleteArray: {
1930    const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
1931    result = getVariableArrayType(
1932                 getVariableArrayDecayedType(iat->getElementType()),
1933                                  /*size*/ 0,
1934                                  ArrayType::Normal,
1935                                  iat->getIndexTypeCVRQualifiers(),
1936                                  SourceRange());
1937    break;
1938  }
1939
1940  // Turn VLA types into [*] types.
1941  case Type::VariableArray: {
1942    const VariableArrayType *vat = cast<VariableArrayType>(ty);
1943    result = getVariableArrayType(
1944                 getVariableArrayDecayedType(vat->getElementType()),
1945                                  /*size*/ 0,
1946                                  ArrayType::Star,
1947                                  vat->getIndexTypeCVRQualifiers(),
1948                                  vat->getBracketsRange());
1949    break;
1950  }
1951  }
1952
1953  // Apply the top-level qualifiers from the original.
1954  return getQualifiedType(result, split.Quals);
1955}
1956
1957/// getVariableArrayType - Returns a non-unique reference to the type for a
1958/// variable array of the specified element type.
1959QualType ASTContext::getVariableArrayType(QualType EltTy,
1960                                          Expr *NumElts,
1961                                          ArrayType::ArraySizeModifier ASM,
1962                                          unsigned IndexTypeQuals,
1963                                          SourceRange Brackets) const {
1964  // Since we don't unique expressions, it isn't possible to unique VLA's
1965  // that have an expression provided for their size.
1966  QualType Canon;
1967
1968  // Be sure to pull qualifiers off the element type.
1969  if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
1970    SplitQualType canonSplit = getCanonicalType(EltTy).split();
1971    Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
1972                                 IndexTypeQuals, Brackets);
1973    Canon = getQualifiedType(Canon, canonSplit.Quals);
1974  }
1975
1976  VariableArrayType *New = new(*this, TypeAlignment)
1977    VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
1978
1979  VariableArrayTypes.push_back(New);
1980  Types.push_back(New);
1981  return QualType(New, 0);
1982}
1983
1984/// getDependentSizedArrayType - Returns a non-unique reference to
1985/// the type for a dependently-sized array of the specified element
1986/// type.
1987QualType ASTContext::getDependentSizedArrayType(QualType elementType,
1988                                                Expr *numElements,
1989                                                ArrayType::ArraySizeModifier ASM,
1990                                                unsigned elementTypeQuals,
1991                                                SourceRange brackets) const {
1992  assert((!numElements || numElements->isTypeDependent() ||
1993          numElements->isValueDependent()) &&
1994         "Size must be type- or value-dependent!");
1995
1996  // Dependently-sized array types that do not have a specified number
1997  // of elements will have their sizes deduced from a dependent
1998  // initializer.  We do no canonicalization here at all, which is okay
1999  // because they can't be used in most locations.
2000  if (!numElements) {
2001    DependentSizedArrayType *newType
2002      = new (*this, TypeAlignment)
2003          DependentSizedArrayType(*this, elementType, QualType(),
2004                                  numElements, ASM, elementTypeQuals,
2005                                  brackets);
2006    Types.push_back(newType);
2007    return QualType(newType, 0);
2008  }
2009
2010  // Otherwise, we actually build a new type every time, but we
2011  // also build a canonical type.
2012
2013  SplitQualType canonElementType = getCanonicalType(elementType).split();
2014
2015  void *insertPos = 0;
2016  llvm::FoldingSetNodeID ID;
2017  DependentSizedArrayType::Profile(ID, *this,
2018                                   QualType(canonElementType.Ty, 0),
2019                                   ASM, elementTypeQuals, numElements);
2020
2021  // Look for an existing type with these properties.
2022  DependentSizedArrayType *canonTy =
2023    DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2024
2025  // If we don't have one, build one.
2026  if (!canonTy) {
2027    canonTy = new (*this, TypeAlignment)
2028      DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2029                              QualType(), numElements, ASM, elementTypeQuals,
2030                              brackets);
2031    DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2032    Types.push_back(canonTy);
2033  }
2034
2035  // Apply qualifiers from the element type to the array.
2036  QualType canon = getQualifiedType(QualType(canonTy,0),
2037                                    canonElementType.Quals);
2038
2039  // If we didn't need extra canonicalization for the element type,
2040  // then just use that as our result.
2041  if (QualType(canonElementType.Ty, 0) == elementType)
2042    return canon;
2043
2044  // Otherwise, we need to build a type which follows the spelling
2045  // of the element type.
2046  DependentSizedArrayType *sugaredType
2047    = new (*this, TypeAlignment)
2048        DependentSizedArrayType(*this, elementType, canon, numElements,
2049                                ASM, elementTypeQuals, brackets);
2050  Types.push_back(sugaredType);
2051  return QualType(sugaredType, 0);
2052}
2053
2054QualType ASTContext::getIncompleteArrayType(QualType elementType,
2055                                            ArrayType::ArraySizeModifier ASM,
2056                                            unsigned elementTypeQuals) const {
2057  llvm::FoldingSetNodeID ID;
2058  IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2059
2060  void *insertPos = 0;
2061  if (IncompleteArrayType *iat =
2062       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2063    return QualType(iat, 0);
2064
2065  // If the element type isn't canonical, this won't be a canonical type
2066  // either, so fill in the canonical type field.  We also have to pull
2067  // qualifiers off the element type.
2068  QualType canon;
2069
2070  if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2071    SplitQualType canonSplit = getCanonicalType(elementType).split();
2072    canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2073                                   ASM, elementTypeQuals);
2074    canon = getQualifiedType(canon, canonSplit.Quals);
2075
2076    // Get the new insert position for the node we care about.
2077    IncompleteArrayType *existing =
2078      IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2079    assert(!existing && "Shouldn't be in the map!"); (void) existing;
2080  }
2081
2082  IncompleteArrayType *newType = new (*this, TypeAlignment)
2083    IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2084
2085  IncompleteArrayTypes.InsertNode(newType, insertPos);
2086  Types.push_back(newType);
2087  return QualType(newType, 0);
2088}
2089
2090/// getVectorType - Return the unique reference to a vector type of
2091/// the specified element type and size. VectorType must be a built-in type.
2092QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2093                                   VectorType::VectorKind VecKind) const {
2094  assert(vecType->isBuiltinType());
2095
2096  // Check if we've already instantiated a vector of this type.
2097  llvm::FoldingSetNodeID ID;
2098  VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2099
2100  void *InsertPos = 0;
2101  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2102    return QualType(VTP, 0);
2103
2104  // If the element type isn't canonical, this won't be a canonical type either,
2105  // so fill in the canonical type field.
2106  QualType Canonical;
2107  if (!vecType.isCanonical()) {
2108    Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2109
2110    // Get the new insert position for the node we care about.
2111    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2112    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2113  }
2114  VectorType *New = new (*this, TypeAlignment)
2115    VectorType(vecType, NumElts, Canonical, VecKind);
2116  VectorTypes.InsertNode(New, InsertPos);
2117  Types.push_back(New);
2118  return QualType(New, 0);
2119}
2120
2121/// getExtVectorType - Return the unique reference to an extended vector type of
2122/// the specified element type and size. VectorType must be a built-in type.
2123QualType
2124ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2125  assert(vecType->isBuiltinType() || vecType->isDependentType());
2126
2127  // Check if we've already instantiated a vector of this type.
2128  llvm::FoldingSetNodeID ID;
2129  VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2130                      VectorType::GenericVector);
2131  void *InsertPos = 0;
2132  if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2133    return QualType(VTP, 0);
2134
2135  // If the element type isn't canonical, this won't be a canonical type either,
2136  // so fill in the canonical type field.
2137  QualType Canonical;
2138  if (!vecType.isCanonical()) {
2139    Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2140
2141    // Get the new insert position for the node we care about.
2142    VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2143    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2144  }
2145  ExtVectorType *New = new (*this, TypeAlignment)
2146    ExtVectorType(vecType, NumElts, Canonical);
2147  VectorTypes.InsertNode(New, InsertPos);
2148  Types.push_back(New);
2149  return QualType(New, 0);
2150}
2151
2152QualType
2153ASTContext::getDependentSizedExtVectorType(QualType vecType,
2154                                           Expr *SizeExpr,
2155                                           SourceLocation AttrLoc) const {
2156  llvm::FoldingSetNodeID ID;
2157  DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2158                                       SizeExpr);
2159
2160  void *InsertPos = 0;
2161  DependentSizedExtVectorType *Canon
2162    = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2163  DependentSizedExtVectorType *New;
2164  if (Canon) {
2165    // We already have a canonical version of this array type; use it as
2166    // the canonical type for a newly-built type.
2167    New = new (*this, TypeAlignment)
2168      DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2169                                  SizeExpr, AttrLoc);
2170  } else {
2171    QualType CanonVecTy = getCanonicalType(vecType);
2172    if (CanonVecTy == vecType) {
2173      New = new (*this, TypeAlignment)
2174        DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2175                                    AttrLoc);
2176
2177      DependentSizedExtVectorType *CanonCheck
2178        = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2179      assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2180      (void)CanonCheck;
2181      DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2182    } else {
2183      QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2184                                                      SourceLocation());
2185      New = new (*this, TypeAlignment)
2186        DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2187    }
2188  }
2189
2190  Types.push_back(New);
2191  return QualType(New, 0);
2192}
2193
2194/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2195///
2196QualType
2197ASTContext::getFunctionNoProtoType(QualType ResultTy,
2198                                   const FunctionType::ExtInfo &Info) const {
2199  const CallingConv DefaultCC = Info.getCC();
2200  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2201                               CC_X86StdCall : DefaultCC;
2202  // Unique functions, to guarantee there is only one function of a particular
2203  // structure.
2204  llvm::FoldingSetNodeID ID;
2205  FunctionNoProtoType::Profile(ID, ResultTy, Info);
2206
2207  void *InsertPos = 0;
2208  if (FunctionNoProtoType *FT =
2209        FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2210    return QualType(FT, 0);
2211
2212  QualType Canonical;
2213  if (!ResultTy.isCanonical() ||
2214      getCanonicalCallConv(CallConv) != CallConv) {
2215    Canonical =
2216      getFunctionNoProtoType(getCanonicalType(ResultTy),
2217                     Info.withCallingConv(getCanonicalCallConv(CallConv)));
2218
2219    // Get the new insert position for the node we care about.
2220    FunctionNoProtoType *NewIP =
2221      FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2222    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2223  }
2224
2225  FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2226  FunctionNoProtoType *New = new (*this, TypeAlignment)
2227    FunctionNoProtoType(ResultTy, Canonical, newInfo);
2228  Types.push_back(New);
2229  FunctionNoProtoTypes.InsertNode(New, InsertPos);
2230  return QualType(New, 0);
2231}
2232
2233/// getFunctionType - Return a normal function type with a typed argument
2234/// list.  isVariadic indicates whether the argument list includes '...'.
2235QualType
2236ASTContext::getFunctionType(QualType ResultTy,
2237                            const QualType *ArgArray, unsigned NumArgs,
2238                            const FunctionProtoType::ExtProtoInfo &EPI) const {
2239  // Unique functions, to guarantee there is only one function of a particular
2240  // structure.
2241  llvm::FoldingSetNodeID ID;
2242  FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this);
2243
2244  void *InsertPos = 0;
2245  if (FunctionProtoType *FTP =
2246        FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2247    return QualType(FTP, 0);
2248
2249  // Determine whether the type being created is already canonical or not.
2250  bool isCanonical =
2251    EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() &&
2252    !EPI.HasTrailingReturn;
2253  for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2254    if (!ArgArray[i].isCanonicalAsParam())
2255      isCanonical = false;
2256
2257  const CallingConv DefaultCC = EPI.ExtInfo.getCC();
2258  const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ?
2259                               CC_X86StdCall : DefaultCC;
2260
2261  // If this type isn't canonical, get the canonical version of it.
2262  // The exception spec is not part of the canonical type.
2263  QualType Canonical;
2264  if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) {
2265    SmallVector<QualType, 16> CanonicalArgs;
2266    CanonicalArgs.reserve(NumArgs);
2267    for (unsigned i = 0; i != NumArgs; ++i)
2268      CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2269
2270    FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2271    CanonicalEPI.HasTrailingReturn = false;
2272    CanonicalEPI.ExceptionSpecType = EST_None;
2273    CanonicalEPI.NumExceptions = 0;
2274    CanonicalEPI.ExtInfo
2275      = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv));
2276
2277    Canonical = getFunctionType(getCanonicalType(ResultTy),
2278                                CanonicalArgs.data(), NumArgs,
2279                                CanonicalEPI);
2280
2281    // Get the new insert position for the node we care about.
2282    FunctionProtoType *NewIP =
2283      FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2284    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
2285  }
2286
2287  // FunctionProtoType objects are allocated with extra bytes after
2288  // them for three variable size arrays at the end:
2289  //  - parameter types
2290  //  - exception types
2291  //  - consumed-arguments flags
2292  // Instead of the exception types, there could be a noexcept
2293  // expression.
2294  size_t Size = sizeof(FunctionProtoType) +
2295                NumArgs * sizeof(QualType);
2296  if (EPI.ExceptionSpecType == EST_Dynamic)
2297    Size += EPI.NumExceptions * sizeof(QualType);
2298  else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) {
2299    Size += sizeof(Expr*);
2300  } else if (EPI.ExceptionSpecType == EST_Uninstantiated) {
2301    Size += 2 * sizeof(FunctionDecl*);
2302  }
2303  if (EPI.ConsumedArguments)
2304    Size += NumArgs * sizeof(bool);
2305
2306  FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
2307  FunctionProtoType::ExtProtoInfo newEPI = EPI;
2308  newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv);
2309  new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI);
2310  Types.push_back(FTP);
2311  FunctionProtoTypes.InsertNode(FTP, InsertPos);
2312  return QualType(FTP, 0);
2313}
2314
2315#ifndef NDEBUG
2316static bool NeedsInjectedClassNameType(const RecordDecl *D) {
2317  if (!isa<CXXRecordDecl>(D)) return false;
2318  const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
2319  if (isa<ClassTemplatePartialSpecializationDecl>(RD))
2320    return true;
2321  if (RD->getDescribedClassTemplate() &&
2322      !isa<ClassTemplateSpecializationDecl>(RD))
2323    return true;
2324  return false;
2325}
2326#endif
2327
2328/// getInjectedClassNameType - Return the unique reference to the
2329/// injected class name type for the specified templated declaration.
2330QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
2331                                              QualType TST) const {
2332  assert(NeedsInjectedClassNameType(Decl));
2333  if (Decl->TypeForDecl) {
2334    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2335  } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
2336    assert(PrevDecl->TypeForDecl && "previous declaration has no type");
2337    Decl->TypeForDecl = PrevDecl->TypeForDecl;
2338    assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
2339  } else {
2340    Type *newType =
2341      new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
2342    Decl->TypeForDecl = newType;
2343    Types.push_back(newType);
2344  }
2345  return QualType(Decl->TypeForDecl, 0);
2346}
2347
2348/// getTypeDeclType - Return the unique reference to the type for the
2349/// specified type declaration.
2350QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
2351  assert(Decl && "Passed null for Decl param");
2352  assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
2353
2354  if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
2355    return getTypedefType(Typedef);
2356
2357  assert(!isa<TemplateTypeParmDecl>(Decl) &&
2358         "Template type parameter types are always available.");
2359
2360  if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
2361    assert(!Record->getPreviousDecl() &&
2362           "struct/union has previous declaration");
2363    assert(!NeedsInjectedClassNameType(Record));
2364    return getRecordType(Record);
2365  } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
2366    assert(!Enum->getPreviousDecl() &&
2367           "enum has previous declaration");
2368    return getEnumType(Enum);
2369  } else if (const UnresolvedUsingTypenameDecl *Using =
2370               dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
2371    Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
2372    Decl->TypeForDecl = newType;
2373    Types.push_back(newType);
2374  } else
2375    llvm_unreachable("TypeDecl without a type?");
2376
2377  return QualType(Decl->TypeForDecl, 0);
2378}
2379
2380/// getTypedefType - Return the unique reference to the type for the
2381/// specified typedef name decl.
2382QualType
2383ASTContext::getTypedefType(const TypedefNameDecl *Decl,
2384                           QualType Canonical) const {
2385  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2386
2387  if (Canonical.isNull())
2388    Canonical = getCanonicalType(Decl->getUnderlyingType());
2389  TypedefType *newType = new(*this, TypeAlignment)
2390    TypedefType(Type::Typedef, Decl, Canonical);
2391  Decl->TypeForDecl = newType;
2392  Types.push_back(newType);
2393  return QualType(newType, 0);
2394}
2395
2396QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
2397  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2398
2399  if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
2400    if (PrevDecl->TypeForDecl)
2401      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2402
2403  RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
2404  Decl->TypeForDecl = newType;
2405  Types.push_back(newType);
2406  return QualType(newType, 0);
2407}
2408
2409QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
2410  if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
2411
2412  if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
2413    if (PrevDecl->TypeForDecl)
2414      return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
2415
2416  EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
2417  Decl->TypeForDecl = newType;
2418  Types.push_back(newType);
2419  return QualType(newType, 0);
2420}
2421
2422QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
2423                                       QualType modifiedType,
2424                                       QualType equivalentType) {
2425  llvm::FoldingSetNodeID id;
2426  AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
2427
2428  void *insertPos = 0;
2429  AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
2430  if (type) return QualType(type, 0);
2431
2432  QualType canon = getCanonicalType(equivalentType);
2433  type = new (*this, TypeAlignment)
2434           AttributedType(canon, attrKind, modifiedType, equivalentType);
2435
2436  Types.push_back(type);
2437  AttributedTypes.InsertNode(type, insertPos);
2438
2439  return QualType(type, 0);
2440}
2441
2442
2443/// \brief Retrieve a substitution-result type.
2444QualType
2445ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
2446                                         QualType Replacement) const {
2447  assert(Replacement.isCanonical()
2448         && "replacement types must always be canonical");
2449
2450  llvm::FoldingSetNodeID ID;
2451  SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
2452  void *InsertPos = 0;
2453  SubstTemplateTypeParmType *SubstParm
2454    = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2455
2456  if (!SubstParm) {
2457    SubstParm = new (*this, TypeAlignment)
2458      SubstTemplateTypeParmType(Parm, Replacement);
2459    Types.push_back(SubstParm);
2460    SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2461  }
2462
2463  return QualType(SubstParm, 0);
2464}
2465
2466/// \brief Retrieve a
2467QualType ASTContext::getSubstTemplateTypeParmPackType(
2468                                          const TemplateTypeParmType *Parm,
2469                                              const TemplateArgument &ArgPack) {
2470#ifndef NDEBUG
2471  for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(),
2472                                    PEnd = ArgPack.pack_end();
2473       P != PEnd; ++P) {
2474    assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type");
2475    assert(P->getAsType().isCanonical() && "Pack contains non-canonical type");
2476  }
2477#endif
2478
2479  llvm::FoldingSetNodeID ID;
2480  SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
2481  void *InsertPos = 0;
2482  if (SubstTemplateTypeParmPackType *SubstParm
2483        = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
2484    return QualType(SubstParm, 0);
2485
2486  QualType Canon;
2487  if (!Parm->isCanonicalUnqualified()) {
2488    Canon = getCanonicalType(QualType(Parm, 0));
2489    Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
2490                                             ArgPack);
2491    SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
2492  }
2493
2494  SubstTemplateTypeParmPackType *SubstParm
2495    = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
2496                                                               ArgPack);
2497  Types.push_back(SubstParm);
2498  SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
2499  return QualType(SubstParm, 0);
2500}
2501
2502/// \brief Retrieve the template type parameter type for a template
2503/// parameter or parameter pack with the given depth, index, and (optionally)
2504/// name.
2505QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
2506                                             bool ParameterPack,
2507                                             TemplateTypeParmDecl *TTPDecl) const {
2508  llvm::FoldingSetNodeID ID;
2509  TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
2510  void *InsertPos = 0;
2511  TemplateTypeParmType *TypeParm
2512    = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2513
2514  if (TypeParm)
2515    return QualType(TypeParm, 0);
2516
2517  if (TTPDecl) {
2518    QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
2519    TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
2520
2521    TemplateTypeParmType *TypeCheck
2522      = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
2523    assert(!TypeCheck && "Template type parameter canonical type broken");
2524    (void)TypeCheck;
2525  } else
2526    TypeParm = new (*this, TypeAlignment)
2527      TemplateTypeParmType(Depth, Index, ParameterPack);
2528
2529  Types.push_back(TypeParm);
2530  TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
2531
2532  return QualType(TypeParm, 0);
2533}
2534
2535TypeSourceInfo *
2536ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
2537                                              SourceLocation NameLoc,
2538                                        const TemplateArgumentListInfo &Args,
2539                                              QualType Underlying) const {
2540  assert(!Name.getAsDependentTemplateName() &&
2541         "No dependent template names here!");
2542  QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
2543
2544  TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
2545  TemplateSpecializationTypeLoc TL
2546    = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc());
2547  TL.setTemplateKeywordLoc(SourceLocation());
2548  TL.setTemplateNameLoc(NameLoc);
2549  TL.setLAngleLoc(Args.getLAngleLoc());
2550  TL.setRAngleLoc(Args.getRAngleLoc());
2551  for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
2552    TL.setArgLocInfo(i, Args[i].getLocInfo());
2553  return DI;
2554}
2555
2556QualType
2557ASTContext::getTemplateSpecializationType(TemplateName Template,
2558                                          const TemplateArgumentListInfo &Args,
2559                                          QualType Underlying) const {
2560  assert(!Template.getAsDependentTemplateName() &&
2561         "No dependent template names here!");
2562
2563  unsigned NumArgs = Args.size();
2564
2565  SmallVector<TemplateArgument, 4> ArgVec;
2566  ArgVec.reserve(NumArgs);
2567  for (unsigned i = 0; i != NumArgs; ++i)
2568    ArgVec.push_back(Args[i].getArgument());
2569
2570  return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
2571                                       Underlying);
2572}
2573
2574#ifndef NDEBUG
2575static bool hasAnyPackExpansions(const TemplateArgument *Args,
2576                                 unsigned NumArgs) {
2577  for (unsigned I = 0; I != NumArgs; ++I)
2578    if (Args[I].isPackExpansion())
2579      return true;
2580
2581  return true;
2582}
2583#endif
2584
2585QualType
2586ASTContext::getTemplateSpecializationType(TemplateName Template,
2587                                          const TemplateArgument *Args,
2588                                          unsigned NumArgs,
2589                                          QualType Underlying) const {
2590  assert(!Template.getAsDependentTemplateName() &&
2591         "No dependent template names here!");
2592  // Look through qualified template names.
2593  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2594    Template = TemplateName(QTN->getTemplateDecl());
2595
2596  bool IsTypeAlias =
2597    Template.getAsTemplateDecl() &&
2598    isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
2599  QualType CanonType;
2600  if (!Underlying.isNull())
2601    CanonType = getCanonicalType(Underlying);
2602  else {
2603    // We can get here with an alias template when the specialization contains
2604    // a pack expansion that does not match up with a parameter pack.
2605    assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
2606           "Caller must compute aliased type");
2607    IsTypeAlias = false;
2608    CanonType = getCanonicalTemplateSpecializationType(Template, Args,
2609                                                       NumArgs);
2610  }
2611
2612  // Allocate the (non-canonical) template specialization type, but don't
2613  // try to unique it: these types typically have location information that
2614  // we don't unique and don't want to lose.
2615  void *Mem = Allocate(sizeof(TemplateSpecializationType) +
2616                       sizeof(TemplateArgument) * NumArgs +
2617                       (IsTypeAlias? sizeof(QualType) : 0),
2618                       TypeAlignment);
2619  TemplateSpecializationType *Spec
2620    = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
2621                                         IsTypeAlias ? Underlying : QualType());
2622
2623  Types.push_back(Spec);
2624  return QualType(Spec, 0);
2625}
2626
2627QualType
2628ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
2629                                                   const TemplateArgument *Args,
2630                                                   unsigned NumArgs) const {
2631  assert(!Template.getAsDependentTemplateName() &&
2632         "No dependent template names here!");
2633
2634  // Look through qualified template names.
2635  if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
2636    Template = TemplateName(QTN->getTemplateDecl());
2637
2638  // Build the canonical template specialization type.
2639  TemplateName CanonTemplate = getCanonicalTemplateName(Template);
2640  SmallVector<TemplateArgument, 4> CanonArgs;
2641  CanonArgs.reserve(NumArgs);
2642  for (unsigned I = 0; I != NumArgs; ++I)
2643    CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
2644
2645  // Determine whether this canonical template specialization type already
2646  // exists.
2647  llvm::FoldingSetNodeID ID;
2648  TemplateSpecializationType::Profile(ID, CanonTemplate,
2649                                      CanonArgs.data(), NumArgs, *this);
2650
2651  void *InsertPos = 0;
2652  TemplateSpecializationType *Spec
2653    = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2654
2655  if (!Spec) {
2656    // Allocate a new canonical template specialization type.
2657    void *Mem = Allocate((sizeof(TemplateSpecializationType) +
2658                          sizeof(TemplateArgument) * NumArgs),
2659                         TypeAlignment);
2660    Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
2661                                                CanonArgs.data(), NumArgs,
2662                                                QualType(), QualType());
2663    Types.push_back(Spec);
2664    TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
2665  }
2666
2667  assert(Spec->isDependentType() &&
2668         "Non-dependent template-id type must have a canonical type");
2669  return QualType(Spec, 0);
2670}
2671
2672QualType
2673ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
2674                              NestedNameSpecifier *NNS,
2675                              QualType NamedType) const {
2676  llvm::FoldingSetNodeID ID;
2677  ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
2678
2679  void *InsertPos = 0;
2680  ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2681  if (T)
2682    return QualType(T, 0);
2683
2684  QualType Canon = NamedType;
2685  if (!Canon.isCanonical()) {
2686    Canon = getCanonicalType(NamedType);
2687    ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
2688    assert(!CheckT && "Elaborated canonical type broken");
2689    (void)CheckT;
2690  }
2691
2692  T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon);
2693  Types.push_back(T);
2694  ElaboratedTypes.InsertNode(T, InsertPos);
2695  return QualType(T, 0);
2696}
2697
2698QualType
2699ASTContext::getParenType(QualType InnerType) const {
2700  llvm::FoldingSetNodeID ID;
2701  ParenType::Profile(ID, InnerType);
2702
2703  void *InsertPos = 0;
2704  ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2705  if (T)
2706    return QualType(T, 0);
2707
2708  QualType Canon = InnerType;
2709  if (!Canon.isCanonical()) {
2710    Canon = getCanonicalType(InnerType);
2711    ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
2712    assert(!CheckT && "Paren canonical type broken");
2713    (void)CheckT;
2714  }
2715
2716  T = new (*this) ParenType(InnerType, Canon);
2717  Types.push_back(T);
2718  ParenTypes.InsertNode(T, InsertPos);
2719  return QualType(T, 0);
2720}
2721
2722QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
2723                                          NestedNameSpecifier *NNS,
2724                                          const IdentifierInfo *Name,
2725                                          QualType Canon) const {
2726  assert(NNS->isDependent() && "nested-name-specifier must be dependent");
2727
2728  if (Canon.isNull()) {
2729    NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2730    ElaboratedTypeKeyword CanonKeyword = Keyword;
2731    if (Keyword == ETK_None)
2732      CanonKeyword = ETK_Typename;
2733
2734    if (CanonNNS != NNS || CanonKeyword != Keyword)
2735      Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
2736  }
2737
2738  llvm::FoldingSetNodeID ID;
2739  DependentNameType::Profile(ID, Keyword, NNS, Name);
2740
2741  void *InsertPos = 0;
2742  DependentNameType *T
2743    = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
2744  if (T)
2745    return QualType(T, 0);
2746
2747  T = new (*this) DependentNameType(Keyword, NNS, Name, Canon);
2748  Types.push_back(T);
2749  DependentNameTypes.InsertNode(T, InsertPos);
2750  return QualType(T, 0);
2751}
2752
2753QualType
2754ASTContext::getDependentTemplateSpecializationType(
2755                                 ElaboratedTypeKeyword Keyword,
2756                                 NestedNameSpecifier *NNS,
2757                                 const IdentifierInfo *Name,
2758                                 const TemplateArgumentListInfo &Args) const {
2759  // TODO: avoid this copy
2760  SmallVector<TemplateArgument, 16> ArgCopy;
2761  for (unsigned I = 0, E = Args.size(); I != E; ++I)
2762    ArgCopy.push_back(Args[I].getArgument());
2763  return getDependentTemplateSpecializationType(Keyword, NNS, Name,
2764                                                ArgCopy.size(),
2765                                                ArgCopy.data());
2766}
2767
2768QualType
2769ASTContext::getDependentTemplateSpecializationType(
2770                                 ElaboratedTypeKeyword Keyword,
2771                                 NestedNameSpecifier *NNS,
2772                                 const IdentifierInfo *Name,
2773                                 unsigned NumArgs,
2774                                 const TemplateArgument *Args) const {
2775  assert((!NNS || NNS->isDependent()) &&
2776         "nested-name-specifier must be dependent");
2777
2778  llvm::FoldingSetNodeID ID;
2779  DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
2780                                               Name, NumArgs, Args);
2781
2782  void *InsertPos = 0;
2783  DependentTemplateSpecializationType *T
2784    = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2785  if (T)
2786    return QualType(T, 0);
2787
2788  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
2789
2790  ElaboratedTypeKeyword CanonKeyword = Keyword;
2791  if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
2792
2793  bool AnyNonCanonArgs = false;
2794  SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
2795  for (unsigned I = 0; I != NumArgs; ++I) {
2796    CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
2797    if (!CanonArgs[I].structurallyEquals(Args[I]))
2798      AnyNonCanonArgs = true;
2799  }
2800
2801  QualType Canon;
2802  if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
2803    Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
2804                                                   Name, NumArgs,
2805                                                   CanonArgs.data());
2806
2807    // Find the insert position again.
2808    DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
2809  }
2810
2811  void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
2812                        sizeof(TemplateArgument) * NumArgs),
2813                       TypeAlignment);
2814  T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
2815                                                    Name, NumArgs, Args, Canon);
2816  Types.push_back(T);
2817  DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
2818  return QualType(T, 0);
2819}
2820
2821QualType ASTContext::getPackExpansionType(QualType Pattern,
2822                                      llvm::Optional<unsigned> NumExpansions) {
2823  llvm::FoldingSetNodeID ID;
2824  PackExpansionType::Profile(ID, Pattern, NumExpansions);
2825
2826  assert(Pattern->containsUnexpandedParameterPack() &&
2827         "Pack expansions must expand one or more parameter packs");
2828  void *InsertPos = 0;
2829  PackExpansionType *T
2830    = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2831  if (T)
2832    return QualType(T, 0);
2833
2834  QualType Canon;
2835  if (!Pattern.isCanonical()) {
2836    Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions);
2837
2838    // Find the insert position again.
2839    PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
2840  }
2841
2842  T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions);
2843  Types.push_back(T);
2844  PackExpansionTypes.InsertNode(T, InsertPos);
2845  return QualType(T, 0);
2846}
2847
2848/// CmpProtocolNames - Comparison predicate for sorting protocols
2849/// alphabetically.
2850static bool CmpProtocolNames(const ObjCProtocolDecl *LHS,
2851                            const ObjCProtocolDecl *RHS) {
2852  return LHS->getDeclName() < RHS->getDeclName();
2853}
2854
2855static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
2856                                unsigned NumProtocols) {
2857  if (NumProtocols == 0) return true;
2858
2859  if (Protocols[0]->getCanonicalDecl() != Protocols[0])
2860    return false;
2861
2862  for (unsigned i = 1; i != NumProtocols; ++i)
2863    if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) ||
2864        Protocols[i]->getCanonicalDecl() != Protocols[i])
2865      return false;
2866  return true;
2867}
2868
2869static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
2870                                   unsigned &NumProtocols) {
2871  ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
2872
2873  // Sort protocols, keyed by name.
2874  std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames);
2875
2876  // Canonicalize.
2877  for (unsigned I = 0, N = NumProtocols; I != N; ++I)
2878    Protocols[I] = Protocols[I]->getCanonicalDecl();
2879
2880  // Remove duplicates.
2881  ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
2882  NumProtocols = ProtocolsEnd-Protocols;
2883}
2884
2885QualType ASTContext::getObjCObjectType(QualType BaseType,
2886                                       ObjCProtocolDecl * const *Protocols,
2887                                       unsigned NumProtocols) const {
2888  // If the base type is an interface and there aren't any protocols
2889  // to add, then the interface type will do just fine.
2890  if (!NumProtocols && isa<ObjCInterfaceType>(BaseType))
2891    return BaseType;
2892
2893  // Look in the folding set for an existing type.
2894  llvm::FoldingSetNodeID ID;
2895  ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols);
2896  void *InsertPos = 0;
2897  if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
2898    return QualType(QT, 0);
2899
2900  // Build the canonical type, which has the canonical base type and
2901  // a sorted-and-uniqued list of protocols.
2902  QualType Canonical;
2903  bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols);
2904  if (!ProtocolsSorted || !BaseType.isCanonical()) {
2905    if (!ProtocolsSorted) {
2906      SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols,
2907                                                     Protocols + NumProtocols);
2908      unsigned UniqueCount = NumProtocols;
2909
2910      SortAndUniqueProtocols(&Sorted[0], UniqueCount);
2911      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2912                                    &Sorted[0], UniqueCount);
2913    } else {
2914      Canonical = getObjCObjectType(getCanonicalType(BaseType),
2915                                    Protocols, NumProtocols);
2916    }
2917
2918    // Regenerate InsertPos.
2919    ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
2920  }
2921
2922  unsigned Size = sizeof(ObjCObjectTypeImpl);
2923  Size += NumProtocols * sizeof(ObjCProtocolDecl *);
2924  void *Mem = Allocate(Size, TypeAlignment);
2925  ObjCObjectTypeImpl *T =
2926    new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols);
2927
2928  Types.push_back(T);
2929  ObjCObjectTypes.InsertNode(T, InsertPos);
2930  return QualType(T, 0);
2931}
2932
2933/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
2934/// the given object type.
2935QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
2936  llvm::FoldingSetNodeID ID;
2937  ObjCObjectPointerType::Profile(ID, ObjectT);
2938
2939  void *InsertPos = 0;
2940  if (ObjCObjectPointerType *QT =
2941              ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2942    return QualType(QT, 0);
2943
2944  // Find the canonical object type.
2945  QualType Canonical;
2946  if (!ObjectT.isCanonical()) {
2947    Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
2948
2949    // Regenerate InsertPos.
2950    ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2951  }
2952
2953  // No match.
2954  void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
2955  ObjCObjectPointerType *QType =
2956    new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
2957
2958  Types.push_back(QType);
2959  ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
2960  return QualType(QType, 0);
2961}
2962
2963/// getObjCInterfaceType - Return the unique reference to the type for the
2964/// specified ObjC interface decl. The list of protocols is optional.
2965QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
2966                                          ObjCInterfaceDecl *PrevDecl) const {
2967  if (Decl->TypeForDecl)
2968    return QualType(Decl->TypeForDecl, 0);
2969
2970  if (PrevDecl) {
2971    assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
2972    Decl->TypeForDecl = PrevDecl->TypeForDecl;
2973    return QualType(PrevDecl->TypeForDecl, 0);
2974  }
2975
2976  // Prefer the definition, if there is one.
2977  if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
2978    Decl = Def;
2979
2980  void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
2981  ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
2982  Decl->TypeForDecl = T;
2983  Types.push_back(T);
2984  return QualType(T, 0);
2985}
2986
2987/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
2988/// TypeOfExprType AST's (since expression's are never shared). For example,
2989/// multiple declarations that refer to "typeof(x)" all contain different
2990/// DeclRefExpr's. This doesn't effect the type checker, since it operates
2991/// on canonical type's (which are always unique).
2992QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
2993  TypeOfExprType *toe;
2994  if (tofExpr->isTypeDependent()) {
2995    llvm::FoldingSetNodeID ID;
2996    DependentTypeOfExprType::Profile(ID, *this, tofExpr);
2997
2998    void *InsertPos = 0;
2999    DependentTypeOfExprType *Canon
3000      = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3001    if (Canon) {
3002      // We already have a "canonical" version of an identical, dependent
3003      // typeof(expr) type. Use that as our canonical type.
3004      toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3005                                          QualType((TypeOfExprType*)Canon, 0));
3006    } else {
3007      // Build a new, canonical typeof(expr) type.
3008      Canon
3009        = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3010      DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3011      toe = Canon;
3012    }
3013  } else {
3014    QualType Canonical = getCanonicalType(tofExpr->getType());
3015    toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3016  }
3017  Types.push_back(toe);
3018  return QualType(toe, 0);
3019}
3020
3021/// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
3022/// TypeOfType AST's. The only motivation to unique these nodes would be
3023/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3024/// an issue. This doesn't effect the type checker, since it operates
3025/// on canonical type's (which are always unique).
3026QualType ASTContext::getTypeOfType(QualType tofType) const {
3027  QualType Canonical = getCanonicalType(tofType);
3028  TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3029  Types.push_back(tot);
3030  return QualType(tot, 0);
3031}
3032
3033
3034/// getDecltypeType -  Unlike many "get<Type>" functions, we don't unique
3035/// DecltypeType AST's. The only motivation to unique these nodes would be
3036/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be
3037/// an issue. This doesn't effect the type checker, since it operates
3038/// on canonical types (which are always unique).
3039QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3040  DecltypeType *dt;
3041
3042  // C++0x [temp.type]p2:
3043  //   If an expression e involves a template parameter, decltype(e) denotes a
3044  //   unique dependent type. Two such decltype-specifiers refer to the same
3045  //   type only if their expressions are equivalent (14.5.6.1).
3046  if (e->isInstantiationDependent()) {
3047    llvm::FoldingSetNodeID ID;
3048    DependentDecltypeType::Profile(ID, *this, e);
3049
3050    void *InsertPos = 0;
3051    DependentDecltypeType *Canon
3052      = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3053    if (Canon) {
3054      // We already have a "canonical" version of an equivalent, dependent
3055      // decltype type. Use that as our canonical type.
3056      dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy,
3057                                       QualType((DecltypeType*)Canon, 0));
3058    } else {
3059      // Build a new, canonical typeof(expr) type.
3060      Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3061      DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3062      dt = Canon;
3063    }
3064  } else {
3065    dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType,
3066                                      getCanonicalType(UnderlyingType));
3067  }
3068  Types.push_back(dt);
3069  return QualType(dt, 0);
3070}
3071
3072/// getUnaryTransformationType - We don't unique these, since the memory
3073/// savings are minimal and these are rare.
3074QualType ASTContext::getUnaryTransformType(QualType BaseType,
3075                                           QualType UnderlyingType,
3076                                           UnaryTransformType::UTTKind Kind)
3077    const {
3078  UnaryTransformType *Ty =
3079    new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3080                                                   Kind,
3081                                 UnderlyingType->isDependentType() ?
3082                                 QualType() : getCanonicalType(UnderlyingType));
3083  Types.push_back(Ty);
3084  return QualType(Ty, 0);
3085}
3086
3087/// getAutoType - We only unique auto types after they've been deduced.
3088QualType ASTContext::getAutoType(QualType DeducedType) const {
3089  void *InsertPos = 0;
3090  if (!DeducedType.isNull()) {
3091    // Look in the folding set for an existing type.
3092    llvm::FoldingSetNodeID ID;
3093    AutoType::Profile(ID, DeducedType);
3094    if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3095      return QualType(AT, 0);
3096  }
3097
3098  AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
3099  Types.push_back(AT);
3100  if (InsertPos)
3101    AutoTypes.InsertNode(AT, InsertPos);
3102  return QualType(AT, 0);
3103}
3104
3105/// getAtomicType - Return the uniqued reference to the atomic type for
3106/// the given value type.
3107QualType ASTContext::getAtomicType(QualType T) const {
3108  // Unique pointers, to guarantee there is only one pointer of a particular
3109  // structure.
3110  llvm::FoldingSetNodeID ID;
3111  AtomicType::Profile(ID, T);
3112
3113  void *InsertPos = 0;
3114  if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3115    return QualType(AT, 0);
3116
3117  // If the atomic value type isn't canonical, this won't be a canonical type
3118  // either, so fill in the canonical type field.
3119  QualType Canonical;
3120  if (!T.isCanonical()) {
3121    Canonical = getAtomicType(getCanonicalType(T));
3122
3123    // Get the new insert position for the node we care about.
3124    AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3125    assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP;
3126  }
3127  AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3128  Types.push_back(New);
3129  AtomicTypes.InsertNode(New, InsertPos);
3130  return QualType(New, 0);
3131}
3132
3133/// getAutoDeductType - Get type pattern for deducing against 'auto'.
3134QualType ASTContext::getAutoDeductType() const {
3135  if (AutoDeductTy.isNull())
3136    AutoDeductTy = getAutoType(QualType());
3137  assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
3138  return AutoDeductTy;
3139}
3140
3141/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
3142QualType ASTContext::getAutoRRefDeductType() const {
3143  if (AutoRRefDeductTy.isNull())
3144    AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3145  assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3146  return AutoRRefDeductTy;
3147}
3148
3149/// getTagDeclType - Return the unique reference to the type for the
3150/// specified TagDecl (struct/union/class/enum) decl.
3151QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3152  assert (Decl);
3153  // FIXME: What is the design on getTagDeclType when it requires casting
3154  // away const?  mutable?
3155  return getTypeDeclType(const_cast<TagDecl*>(Decl));
3156}
3157
3158/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
3159/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
3160/// needs to agree with the definition in <stddef.h>.
3161CanQualType ASTContext::getSizeType() const {
3162  return getFromTargetType(Target->getSizeType());
3163}
3164
3165/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
3166CanQualType ASTContext::getIntMaxType() const {
3167  return getFromTargetType(Target->getIntMaxType());
3168}
3169
3170/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
3171CanQualType ASTContext::getUIntMaxType() const {
3172  return getFromTargetType(Target->getUIntMaxType());
3173}
3174
3175/// getSignedWCharType - Return the type of "signed wchar_t".
3176/// Used when in C++, as a GCC extension.
3177QualType ASTContext::getSignedWCharType() const {
3178  // FIXME: derive from "Target" ?
3179  return WCharTy;
3180}
3181
3182/// getUnsignedWCharType - Return the type of "unsigned wchar_t".
3183/// Used when in C++, as a GCC extension.
3184QualType ASTContext::getUnsignedWCharType() const {
3185  // FIXME: derive from "Target" ?
3186  return UnsignedIntTy;
3187}
3188
3189/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
3190/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
3191QualType ASTContext::getPointerDiffType() const {
3192  return getFromTargetType(Target->getPtrDiffType(0));
3193}
3194
3195//===----------------------------------------------------------------------===//
3196//                              Type Operators
3197//===----------------------------------------------------------------------===//
3198
3199CanQualType ASTContext::getCanonicalParamType(QualType T) const {
3200  // Push qualifiers into arrays, and then discard any remaining
3201  // qualifiers.
3202  T = getCanonicalType(T);
3203  T = getVariableArrayDecayedType(T);
3204  const Type *Ty = T.getTypePtr();
3205  QualType Result;
3206  if (isa<ArrayType>(Ty)) {
3207    Result = getArrayDecayedType(QualType(Ty,0));
3208  } else if (isa<FunctionType>(Ty)) {
3209    Result = getPointerType(QualType(Ty, 0));
3210  } else {
3211    Result = QualType(Ty, 0);
3212  }
3213
3214  return CanQualType::CreateUnsafe(Result);
3215}
3216
3217QualType ASTContext::getUnqualifiedArrayType(QualType type,
3218                                             Qualifiers &quals) {
3219  SplitQualType splitType = type.getSplitUnqualifiedType();
3220
3221  // FIXME: getSplitUnqualifiedType() actually walks all the way to
3222  // the unqualified desugared type and then drops it on the floor.
3223  // We then have to strip that sugar back off with
3224  // getUnqualifiedDesugaredType(), which is silly.
3225  const ArrayType *AT =
3226    dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
3227
3228  // If we don't have an array, just use the results in splitType.
3229  if (!AT) {
3230    quals = splitType.Quals;
3231    return QualType(splitType.Ty, 0);
3232  }
3233
3234  // Otherwise, recurse on the array's element type.
3235  QualType elementType = AT->getElementType();
3236  QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
3237
3238  // If that didn't change the element type, AT has no qualifiers, so we
3239  // can just use the results in splitType.
3240  if (elementType == unqualElementType) {
3241    assert(quals.empty()); // from the recursive call
3242    quals = splitType.Quals;
3243    return QualType(splitType.Ty, 0);
3244  }
3245
3246  // Otherwise, add in the qualifiers from the outermost type, then
3247  // build the type back up.
3248  quals.addConsistentQualifiers(splitType.Quals);
3249
3250  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3251    return getConstantArrayType(unqualElementType, CAT->getSize(),
3252                                CAT->getSizeModifier(), 0);
3253  }
3254
3255  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
3256    return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
3257  }
3258
3259  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
3260    return getVariableArrayType(unqualElementType,
3261                                VAT->getSizeExpr(),
3262                                VAT->getSizeModifier(),
3263                                VAT->getIndexTypeCVRQualifiers(),
3264                                VAT->getBracketsRange());
3265  }
3266
3267  const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
3268  return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
3269                                    DSAT->getSizeModifier(), 0,
3270                                    SourceRange());
3271}
3272
3273/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
3274/// may be similar (C++ 4.4), replaces T1 and T2 with the type that
3275/// they point to and return true. If T1 and T2 aren't pointer types
3276/// or pointer-to-member types, or if they are not similar at this
3277/// level, returns false and leaves T1 and T2 unchanged. Top-level
3278/// qualifiers on T1 and T2 are ignored. This function will typically
3279/// be called in a loop that successively "unwraps" pointer and
3280/// pointer-to-member types to compare them at each level.
3281bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
3282  const PointerType *T1PtrType = T1->getAs<PointerType>(),
3283                    *T2PtrType = T2->getAs<PointerType>();
3284  if (T1PtrType && T2PtrType) {
3285    T1 = T1PtrType->getPointeeType();
3286    T2 = T2PtrType->getPointeeType();
3287    return true;
3288  }
3289
3290  const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
3291                          *T2MPType = T2->getAs<MemberPointerType>();
3292  if (T1MPType && T2MPType &&
3293      hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
3294                             QualType(T2MPType->getClass(), 0))) {
3295    T1 = T1MPType->getPointeeType();
3296    T2 = T2MPType->getPointeeType();
3297    return true;
3298  }
3299
3300  if (getLangOpts().ObjC1) {
3301    const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
3302                                *T2OPType = T2->getAs<ObjCObjectPointerType>();
3303    if (T1OPType && T2OPType) {
3304      T1 = T1OPType->getPointeeType();
3305      T2 = T2OPType->getPointeeType();
3306      return true;
3307    }
3308  }
3309
3310  // FIXME: Block pointers, too?
3311
3312  return false;
3313}
3314
3315DeclarationNameInfo
3316ASTContext::getNameForTemplate(TemplateName Name,
3317                               SourceLocation NameLoc) const {
3318  switch (Name.getKind()) {
3319  case TemplateName::QualifiedTemplate:
3320  case TemplateName::Template:
3321    // DNInfo work in progress: CHECKME: what about DNLoc?
3322    return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
3323                               NameLoc);
3324
3325  case TemplateName::OverloadedTemplate: {
3326    OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
3327    // DNInfo work in progress: CHECKME: what about DNLoc?
3328    return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
3329  }
3330
3331  case TemplateName::DependentTemplate: {
3332    DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3333    DeclarationName DName;
3334    if (DTN->isIdentifier()) {
3335      DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
3336      return DeclarationNameInfo(DName, NameLoc);
3337    } else {
3338      DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
3339      // DNInfo work in progress: FIXME: source locations?
3340      DeclarationNameLoc DNLoc;
3341      DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
3342      DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
3343      return DeclarationNameInfo(DName, NameLoc, DNLoc);
3344    }
3345  }
3346
3347  case TemplateName::SubstTemplateTemplateParm: {
3348    SubstTemplateTemplateParmStorage *subst
3349      = Name.getAsSubstTemplateTemplateParm();
3350    return DeclarationNameInfo(subst->getParameter()->getDeclName(),
3351                               NameLoc);
3352  }
3353
3354  case TemplateName::SubstTemplateTemplateParmPack: {
3355    SubstTemplateTemplateParmPackStorage *subst
3356      = Name.getAsSubstTemplateTemplateParmPack();
3357    return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
3358                               NameLoc);
3359  }
3360  }
3361
3362  llvm_unreachable("bad template name kind!");
3363}
3364
3365TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
3366  switch (Name.getKind()) {
3367  case TemplateName::QualifiedTemplate:
3368  case TemplateName::Template: {
3369    TemplateDecl *Template = Name.getAsTemplateDecl();
3370    if (TemplateTemplateParmDecl *TTP
3371          = dyn_cast<TemplateTemplateParmDecl>(Template))
3372      Template = getCanonicalTemplateTemplateParmDecl(TTP);
3373
3374    // The canonical template name is the canonical template declaration.
3375    return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
3376  }
3377
3378  case TemplateName::OverloadedTemplate:
3379    llvm_unreachable("cannot canonicalize overloaded template");
3380
3381  case TemplateName::DependentTemplate: {
3382    DependentTemplateName *DTN = Name.getAsDependentTemplateName();
3383    assert(DTN && "Non-dependent template names must refer to template decls.");
3384    return DTN->CanonicalTemplateName;
3385  }
3386
3387  case TemplateName::SubstTemplateTemplateParm: {
3388    SubstTemplateTemplateParmStorage *subst
3389      = Name.getAsSubstTemplateTemplateParm();
3390    return getCanonicalTemplateName(subst->getReplacement());
3391  }
3392
3393  case TemplateName::SubstTemplateTemplateParmPack: {
3394    SubstTemplateTemplateParmPackStorage *subst
3395                                  = Name.getAsSubstTemplateTemplateParmPack();
3396    TemplateTemplateParmDecl *canonParameter
3397      = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
3398    TemplateArgument canonArgPack
3399      = getCanonicalTemplateArgument(subst->getArgumentPack());
3400    return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
3401  }
3402  }
3403
3404  llvm_unreachable("bad template name!");
3405}
3406
3407bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
3408  X = getCanonicalTemplateName(X);
3409  Y = getCanonicalTemplateName(Y);
3410  return X.getAsVoidPointer() == Y.getAsVoidPointer();
3411}
3412
3413TemplateArgument
3414ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
3415  switch (Arg.getKind()) {
3416    case TemplateArgument::Null:
3417      return Arg;
3418
3419    case TemplateArgument::Expression:
3420      return Arg;
3421
3422    case TemplateArgument::Declaration: {
3423      if (Decl *D = Arg.getAsDecl())
3424          return TemplateArgument(D->getCanonicalDecl());
3425      return TemplateArgument((Decl*)0);
3426    }
3427
3428    case TemplateArgument::Template:
3429      return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
3430
3431    case TemplateArgument::TemplateExpansion:
3432      return TemplateArgument(getCanonicalTemplateName(
3433                                         Arg.getAsTemplateOrTemplatePattern()),
3434                              Arg.getNumTemplateExpansions());
3435
3436    case TemplateArgument::Integral:
3437      return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
3438
3439    case TemplateArgument::Type:
3440      return TemplateArgument(getCanonicalType(Arg.getAsType()));
3441
3442    case TemplateArgument::Pack: {
3443      if (Arg.pack_size() == 0)
3444        return Arg;
3445
3446      TemplateArgument *CanonArgs
3447        = new (*this) TemplateArgument[Arg.pack_size()];
3448      unsigned Idx = 0;
3449      for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
3450                                        AEnd = Arg.pack_end();
3451           A != AEnd; (void)++A, ++Idx)
3452        CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
3453
3454      return TemplateArgument(CanonArgs, Arg.pack_size());
3455    }
3456  }
3457
3458  // Silence GCC warning
3459  llvm_unreachable("Unhandled template argument kind");
3460}
3461
3462NestedNameSpecifier *
3463ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
3464  if (!NNS)
3465    return 0;
3466
3467  switch (NNS->getKind()) {
3468  case NestedNameSpecifier::Identifier:
3469    // Canonicalize the prefix but keep the identifier the same.
3470    return NestedNameSpecifier::Create(*this,
3471                         getCanonicalNestedNameSpecifier(NNS->getPrefix()),
3472                                       NNS->getAsIdentifier());
3473
3474  case NestedNameSpecifier::Namespace:
3475    // A namespace is canonical; build a nested-name-specifier with
3476    // this namespace and no prefix.
3477    return NestedNameSpecifier::Create(*this, 0,
3478                                 NNS->getAsNamespace()->getOriginalNamespace());
3479
3480  case NestedNameSpecifier::NamespaceAlias:
3481    // A namespace is canonical; build a nested-name-specifier with
3482    // this namespace and no prefix.
3483    return NestedNameSpecifier::Create(*this, 0,
3484                                    NNS->getAsNamespaceAlias()->getNamespace()
3485                                                      ->getOriginalNamespace());
3486
3487  case NestedNameSpecifier::TypeSpec:
3488  case NestedNameSpecifier::TypeSpecWithTemplate: {
3489    QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
3490
3491    // If we have some kind of dependent-named type (e.g., "typename T::type"),
3492    // break it apart into its prefix and identifier, then reconsititute those
3493    // as the canonical nested-name-specifier. This is required to canonicalize
3494    // a dependent nested-name-specifier involving typedefs of dependent-name
3495    // types, e.g.,
3496    //   typedef typename T::type T1;
3497    //   typedef typename T1::type T2;
3498    if (const DependentNameType *DNT = T->getAs<DependentNameType>())
3499      return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
3500                           const_cast<IdentifierInfo *>(DNT->getIdentifier()));
3501
3502    // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
3503    // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
3504    // first place?
3505    return NestedNameSpecifier::Create(*this, 0, false,
3506                                       const_cast<Type*>(T.getTypePtr()));
3507  }
3508
3509  case NestedNameSpecifier::Global:
3510    // The global specifier is canonical and unique.
3511    return NNS;
3512  }
3513
3514  llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
3515}
3516
3517
3518const ArrayType *ASTContext::getAsArrayType(QualType T) const {
3519  // Handle the non-qualified case efficiently.
3520  if (!T.hasLocalQualifiers()) {
3521    // Handle the common positive case fast.
3522    if (const ArrayType *AT = dyn_cast<ArrayType>(T))
3523      return AT;
3524  }
3525
3526  // Handle the common negative case fast.
3527  if (!isa<ArrayType>(T.getCanonicalType()))
3528    return 0;
3529
3530  // Apply any qualifiers from the array type to the element type.  This
3531  // implements C99 6.7.3p8: "If the specification of an array type includes
3532  // any type qualifiers, the element type is so qualified, not the array type."
3533
3534  // If we get here, we either have type qualifiers on the type, or we have
3535  // sugar such as a typedef in the way.  If we have type qualifiers on the type
3536  // we must propagate them down into the element type.
3537
3538  SplitQualType split = T.getSplitDesugaredType();
3539  Qualifiers qs = split.Quals;
3540
3541  // If we have a simple case, just return now.
3542  const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
3543  if (ATy == 0 || qs.empty())
3544    return ATy;
3545
3546  // Otherwise, we have an array and we have qualifiers on it.  Push the
3547  // qualifiers into the array element type and return a new array type.
3548  QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
3549
3550  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
3551    return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
3552                                                CAT->getSizeModifier(),
3553                                           CAT->getIndexTypeCVRQualifiers()));
3554  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
3555    return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
3556                                                  IAT->getSizeModifier(),
3557                                           IAT->getIndexTypeCVRQualifiers()));
3558
3559  if (const DependentSizedArrayType *DSAT
3560        = dyn_cast<DependentSizedArrayType>(ATy))
3561    return cast<ArrayType>(
3562                     getDependentSizedArrayType(NewEltTy,
3563                                                DSAT->getSizeExpr(),
3564                                                DSAT->getSizeModifier(),
3565                                              DSAT->getIndexTypeCVRQualifiers(),
3566                                                DSAT->getBracketsRange()));
3567
3568  const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
3569  return cast<ArrayType>(getVariableArrayType(NewEltTy,
3570                                              VAT->getSizeExpr(),
3571                                              VAT->getSizeModifier(),
3572                                              VAT->getIndexTypeCVRQualifiers(),
3573                                              VAT->getBracketsRange()));
3574}
3575
3576QualType ASTContext::getAdjustedParameterType(QualType T) const {
3577  // C99 6.7.5.3p7:
3578  //   A declaration of a parameter as "array of type" shall be
3579  //   adjusted to "qualified pointer to type", where the type
3580  //   qualifiers (if any) are those specified within the [ and ] of
3581  //   the array type derivation.
3582  if (T->isArrayType())
3583    return getArrayDecayedType(T);
3584
3585  // C99 6.7.5.3p8:
3586  //   A declaration of a parameter as "function returning type"
3587  //   shall be adjusted to "pointer to function returning type", as
3588  //   in 6.3.2.1.
3589  if (T->isFunctionType())
3590    return getPointerType(T);
3591
3592  return T;
3593}
3594
3595QualType ASTContext::getSignatureParameterType(QualType T) const {
3596  T = getVariableArrayDecayedType(T);
3597  T = getAdjustedParameterType(T);
3598  return T.getUnqualifiedType();
3599}
3600
3601/// getArrayDecayedType - Return the properly qualified result of decaying the
3602/// specified array type to a pointer.  This operation is non-trivial when
3603/// handling typedefs etc.  The canonical type of "T" must be an array type,
3604/// this returns a pointer to a properly qualified element of the array.
3605///
3606/// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
3607QualType ASTContext::getArrayDecayedType(QualType Ty) const {
3608  // Get the element type with 'getAsArrayType' so that we don't lose any
3609  // typedefs in the element type of the array.  This also handles propagation
3610  // of type qualifiers from the array type into the element type if present
3611  // (C99 6.7.3p8).
3612  const ArrayType *PrettyArrayType = getAsArrayType(Ty);
3613  assert(PrettyArrayType && "Not an array type!");
3614
3615  QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
3616
3617  // int x[restrict 4] ->  int *restrict
3618  return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
3619}
3620
3621QualType ASTContext::getBaseElementType(const ArrayType *array) const {
3622  return getBaseElementType(array->getElementType());
3623}
3624
3625QualType ASTContext::getBaseElementType(QualType type) const {
3626  Qualifiers qs;
3627  while (true) {
3628    SplitQualType split = type.getSplitDesugaredType();
3629    const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
3630    if (!array) break;
3631
3632    type = array->getElementType();
3633    qs.addConsistentQualifiers(split.Quals);
3634  }
3635
3636  return getQualifiedType(type, qs);
3637}
3638
3639/// getConstantArrayElementCount - Returns number of constant array elements.
3640uint64_t
3641ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
3642  uint64_t ElementCount = 1;
3643  do {
3644    ElementCount *= CA->getSize().getZExtValue();
3645    CA = dyn_cast<ConstantArrayType>(CA->getElementType());
3646  } while (CA);
3647  return ElementCount;
3648}
3649
3650/// getFloatingRank - Return a relative rank for floating point types.
3651/// This routine will assert if passed a built-in type that isn't a float.
3652static FloatingRank getFloatingRank(QualType T) {
3653  if (const ComplexType *CT = T->getAs<ComplexType>())
3654    return getFloatingRank(CT->getElementType());
3655
3656  assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
3657  switch (T->getAs<BuiltinType>()->getKind()) {
3658  default: llvm_unreachable("getFloatingRank(): not a floating type");
3659  case BuiltinType::Half:       return HalfRank;
3660  case BuiltinType::Float:      return FloatRank;
3661  case BuiltinType::Double:     return DoubleRank;
3662  case BuiltinType::LongDouble: return LongDoubleRank;
3663  }
3664}
3665
3666/// getFloatingTypeOfSizeWithinDomain - Returns a real floating
3667/// point or a complex type (based on typeDomain/typeSize).
3668/// 'typeDomain' is a real floating point or complex type.
3669/// 'typeSize' is a real floating point or complex type.
3670QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
3671                                                       QualType Domain) const {
3672  FloatingRank EltRank = getFloatingRank(Size);
3673  if (Domain->isComplexType()) {
3674    switch (EltRank) {
3675    case HalfRank: llvm_unreachable("Complex half is not supported");
3676    case FloatRank:      return FloatComplexTy;
3677    case DoubleRank:     return DoubleComplexTy;
3678    case LongDoubleRank: return LongDoubleComplexTy;
3679    }
3680  }
3681
3682  assert(Domain->isRealFloatingType() && "Unknown domain!");
3683  switch (EltRank) {
3684  case HalfRank: llvm_unreachable("Half ranks are not valid here");
3685  case FloatRank:      return FloatTy;
3686  case DoubleRank:     return DoubleTy;
3687  case LongDoubleRank: return LongDoubleTy;
3688  }
3689  llvm_unreachable("getFloatingRank(): illegal value for rank");
3690}
3691
3692/// getFloatingTypeOrder - Compare the rank of the two specified floating
3693/// point types, ignoring the domain of the type (i.e. 'double' ==
3694/// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3695/// LHS < RHS, return -1.
3696int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
3697  FloatingRank LHSR = getFloatingRank(LHS);
3698  FloatingRank RHSR = getFloatingRank(RHS);
3699
3700  if (LHSR == RHSR)
3701    return 0;
3702  if (LHSR > RHSR)
3703    return 1;
3704  return -1;
3705}
3706
3707/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
3708/// routine will assert if passed a built-in type that isn't an integer or enum,
3709/// or if it is not canonicalized.
3710unsigned ASTContext::getIntegerRank(const Type *T) const {
3711  assert(T->isCanonicalUnqualified() && "T should be canonicalized");
3712
3713  switch (cast<BuiltinType>(T)->getKind()) {
3714  default: llvm_unreachable("getIntegerRank(): not a built-in integer");
3715  case BuiltinType::Bool:
3716    return 1 + (getIntWidth(BoolTy) << 3);
3717  case BuiltinType::Char_S:
3718  case BuiltinType::Char_U:
3719  case BuiltinType::SChar:
3720  case BuiltinType::UChar:
3721    return 2 + (getIntWidth(CharTy) << 3);
3722  case BuiltinType::Short:
3723  case BuiltinType::UShort:
3724    return 3 + (getIntWidth(ShortTy) << 3);
3725  case BuiltinType::Int:
3726  case BuiltinType::UInt:
3727    return 4 + (getIntWidth(IntTy) << 3);
3728  case BuiltinType::Long:
3729  case BuiltinType::ULong:
3730    return 5 + (getIntWidth(LongTy) << 3);
3731  case BuiltinType::LongLong:
3732  case BuiltinType::ULongLong:
3733    return 6 + (getIntWidth(LongLongTy) << 3);
3734  case BuiltinType::Int128:
3735  case BuiltinType::UInt128:
3736    return 7 + (getIntWidth(Int128Ty) << 3);
3737  }
3738}
3739
3740/// \brief Whether this is a promotable bitfield reference according
3741/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
3742///
3743/// \returns the type this bit-field will promote to, or NULL if no
3744/// promotion occurs.
3745QualType ASTContext::isPromotableBitField(Expr *E) const {
3746  if (E->isTypeDependent() || E->isValueDependent())
3747    return QualType();
3748
3749  FieldDecl *Field = E->getBitField();
3750  if (!Field)
3751    return QualType();
3752
3753  QualType FT = Field->getType();
3754
3755  uint64_t BitWidth = Field->getBitWidthValue(*this);
3756  uint64_t IntSize = getTypeSize(IntTy);
3757  // GCC extension compatibility: if the bit-field size is less than or equal
3758  // to the size of int, it gets promoted no matter what its type is.
3759  // For instance, unsigned long bf : 4 gets promoted to signed int.
3760  if (BitWidth < IntSize)
3761    return IntTy;
3762
3763  if (BitWidth == IntSize)
3764    return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
3765
3766  // Types bigger than int are not subject to promotions, and therefore act
3767  // like the base type.
3768  // FIXME: This doesn't quite match what gcc does, but what gcc does here
3769  // is ridiculous.
3770  return QualType();
3771}
3772
3773/// getPromotedIntegerType - Returns the type that Promotable will
3774/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
3775/// integer type.
3776QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
3777  assert(!Promotable.isNull());
3778  assert(Promotable->isPromotableIntegerType());
3779  if (const EnumType *ET = Promotable->getAs<EnumType>())
3780    return ET->getDecl()->getPromotionType();
3781
3782  if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
3783    // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
3784    // (3.9.1) can be converted to a prvalue of the first of the following
3785    // types that can represent all the values of its underlying type:
3786    // int, unsigned int, long int, unsigned long int, long long int, or
3787    // unsigned long long int [...]
3788    // FIXME: Is there some better way to compute this?
3789    if (BT->getKind() == BuiltinType::WChar_S ||
3790        BT->getKind() == BuiltinType::WChar_U ||
3791        BT->getKind() == BuiltinType::Char16 ||
3792        BT->getKind() == BuiltinType::Char32) {
3793      bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
3794      uint64_t FromSize = getTypeSize(BT);
3795      QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
3796                                  LongLongTy, UnsignedLongLongTy };
3797      for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
3798        uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
3799        if (FromSize < ToSize ||
3800            (FromSize == ToSize &&
3801             FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
3802          return PromoteTypes[Idx];
3803      }
3804      llvm_unreachable("char type should fit into long long");
3805    }
3806  }
3807
3808  // At this point, we should have a signed or unsigned integer type.
3809  if (Promotable->isSignedIntegerType())
3810    return IntTy;
3811  uint64_t PromotableSize = getTypeSize(Promotable);
3812  uint64_t IntSize = getTypeSize(IntTy);
3813  assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
3814  return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
3815}
3816
3817/// \brief Recurses in pointer/array types until it finds an objc retainable
3818/// type and returns its ownership.
3819Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
3820  while (!T.isNull()) {
3821    if (T.getObjCLifetime() != Qualifiers::OCL_None)
3822      return T.getObjCLifetime();
3823    if (T->isArrayType())
3824      T = getBaseElementType(T);
3825    else if (const PointerType *PT = T->getAs<PointerType>())
3826      T = PT->getPointeeType();
3827    else if (const ReferenceType *RT = T->getAs<ReferenceType>())
3828      T = RT->getPointeeType();
3829    else
3830      break;
3831  }
3832
3833  return Qualifiers::OCL_None;
3834}
3835
3836/// getIntegerTypeOrder - Returns the highest ranked integer type:
3837/// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
3838/// LHS < RHS, return -1.
3839int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
3840  const Type *LHSC = getCanonicalType(LHS).getTypePtr();
3841  const Type *RHSC = getCanonicalType(RHS).getTypePtr();
3842  if (LHSC == RHSC) return 0;
3843
3844  bool LHSUnsigned = LHSC->isUnsignedIntegerType();
3845  bool RHSUnsigned = RHSC->isUnsignedIntegerType();
3846
3847  unsigned LHSRank = getIntegerRank(LHSC);
3848  unsigned RHSRank = getIntegerRank(RHSC);
3849
3850  if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
3851    if (LHSRank == RHSRank) return 0;
3852    return LHSRank > RHSRank ? 1 : -1;
3853  }
3854
3855  // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
3856  if (LHSUnsigned) {
3857    // If the unsigned [LHS] type is larger, return it.
3858    if (LHSRank >= RHSRank)
3859      return 1;
3860
3861    // If the signed type can represent all values of the unsigned type, it
3862    // wins.  Because we are dealing with 2's complement and types that are
3863    // powers of two larger than each other, this is always safe.
3864    return -1;
3865  }
3866
3867  // If the unsigned [RHS] type is larger, return it.
3868  if (RHSRank >= LHSRank)
3869    return -1;
3870
3871  // If the signed type can represent all values of the unsigned type, it
3872  // wins.  Because we are dealing with 2's complement and types that are
3873  // powers of two larger than each other, this is always safe.
3874  return 1;
3875}
3876
3877static RecordDecl *
3878CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
3879                 DeclContext *DC, IdentifierInfo *Id) {
3880  SourceLocation Loc;
3881  if (Ctx.getLangOpts().CPlusPlus)
3882    return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3883  else
3884    return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
3885}
3886
3887// getCFConstantStringType - Return the type used for constant CFStrings.
3888QualType ASTContext::getCFConstantStringType() const {
3889  if (!CFConstantStringTypeDecl) {
3890    CFConstantStringTypeDecl =
3891      CreateRecordDecl(*this, TTK_Struct, TUDecl,
3892                       &Idents.get("NSConstantString"));
3893    CFConstantStringTypeDecl->startDefinition();
3894
3895    QualType FieldTypes[4];
3896
3897    // const int *isa;
3898    FieldTypes[0] = getPointerType(IntTy.withConst());
3899    // int flags;
3900    FieldTypes[1] = IntTy;
3901    // const char *str;
3902    FieldTypes[2] = getPointerType(CharTy.withConst());
3903    // long length;
3904    FieldTypes[3] = LongTy;
3905
3906    // Create fields
3907    for (unsigned i = 0; i < 4; ++i) {
3908      FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
3909                                           SourceLocation(),
3910                                           SourceLocation(), 0,
3911                                           FieldTypes[i], /*TInfo=*/0,
3912                                           /*BitWidth=*/0,
3913                                           /*Mutable=*/false,
3914                                           ICIS_NoInit);
3915      Field->setAccess(AS_public);
3916      CFConstantStringTypeDecl->addDecl(Field);
3917    }
3918
3919    CFConstantStringTypeDecl->completeDefinition();
3920  }
3921
3922  return getTagDeclType(CFConstantStringTypeDecl);
3923}
3924
3925void ASTContext::setCFConstantStringType(QualType T) {
3926  const RecordType *Rec = T->getAs<RecordType>();
3927  assert(Rec && "Invalid CFConstantStringType");
3928  CFConstantStringTypeDecl = Rec->getDecl();
3929}
3930
3931QualType ASTContext::getBlockDescriptorType() const {
3932  if (BlockDescriptorType)
3933    return getTagDeclType(BlockDescriptorType);
3934
3935  RecordDecl *T;
3936  // FIXME: Needs the FlagAppleBlock bit.
3937  T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3938                       &Idents.get("__block_descriptor"));
3939  T->startDefinition();
3940
3941  QualType FieldTypes[] = {
3942    UnsignedLongTy,
3943    UnsignedLongTy,
3944  };
3945
3946  const char *FieldNames[] = {
3947    "reserved",
3948    "Size"
3949  };
3950
3951  for (size_t i = 0; i < 2; ++i) {
3952    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3953                                         SourceLocation(),
3954                                         &Idents.get(FieldNames[i]),
3955                                         FieldTypes[i], /*TInfo=*/0,
3956                                         /*BitWidth=*/0,
3957                                         /*Mutable=*/false,
3958                                         ICIS_NoInit);
3959    Field->setAccess(AS_public);
3960    T->addDecl(Field);
3961  }
3962
3963  T->completeDefinition();
3964
3965  BlockDescriptorType = T;
3966
3967  return getTagDeclType(BlockDescriptorType);
3968}
3969
3970QualType ASTContext::getBlockDescriptorExtendedType() const {
3971  if (BlockDescriptorExtendedType)
3972    return getTagDeclType(BlockDescriptorExtendedType);
3973
3974  RecordDecl *T;
3975  // FIXME: Needs the FlagAppleBlock bit.
3976  T = CreateRecordDecl(*this, TTK_Struct, TUDecl,
3977                       &Idents.get("__block_descriptor_withcopydispose"));
3978  T->startDefinition();
3979
3980  QualType FieldTypes[] = {
3981    UnsignedLongTy,
3982    UnsignedLongTy,
3983    getPointerType(VoidPtrTy),
3984    getPointerType(VoidPtrTy)
3985  };
3986
3987  const char *FieldNames[] = {
3988    "reserved",
3989    "Size",
3990    "CopyFuncPtr",
3991    "DestroyFuncPtr"
3992  };
3993
3994  for (size_t i = 0; i < 4; ++i) {
3995    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
3996                                         SourceLocation(),
3997                                         &Idents.get(FieldNames[i]),
3998                                         FieldTypes[i], /*TInfo=*/0,
3999                                         /*BitWidth=*/0,
4000                                         /*Mutable=*/false,
4001                                         ICIS_NoInit);
4002    Field->setAccess(AS_public);
4003    T->addDecl(Field);
4004  }
4005
4006  T->completeDefinition();
4007
4008  BlockDescriptorExtendedType = T;
4009
4010  return getTagDeclType(BlockDescriptorExtendedType);
4011}
4012
4013bool ASTContext::BlockRequiresCopying(QualType Ty) const {
4014  if (Ty->isObjCRetainableType())
4015    return true;
4016  if (getLangOpts().CPlusPlus) {
4017    if (const RecordType *RT = Ty->getAs<RecordType>()) {
4018      CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4019      return RD->hasConstCopyConstructor();
4020
4021    }
4022  }
4023  return false;
4024}
4025
4026QualType
4027ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const {
4028  //  type = struct __Block_byref_1_X {
4029  //    void *__isa;
4030  //    struct __Block_byref_1_X *__forwarding;
4031  //    unsigned int __flags;
4032  //    unsigned int __size;
4033  //    void *__copy_helper;            // as needed
4034  //    void *__destroy_help            // as needed
4035  //    int X;
4036  //  } *
4037
4038  bool HasCopyAndDispose = BlockRequiresCopying(Ty);
4039
4040  // FIXME: Move up
4041  SmallString<36> Name;
4042  llvm::raw_svector_ostream(Name) << "__Block_byref_" <<
4043                                  ++UniqueBlockByRefTypeID << '_' << DeclName;
4044  RecordDecl *T;
4045  T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str()));
4046  T->startDefinition();
4047  QualType Int32Ty = IntTy;
4048  assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported");
4049  QualType FieldTypes[] = {
4050    getPointerType(VoidPtrTy),
4051    getPointerType(getTagDeclType(T)),
4052    Int32Ty,
4053    Int32Ty,
4054    getPointerType(VoidPtrTy),
4055    getPointerType(VoidPtrTy),
4056    Ty
4057  };
4058
4059  StringRef FieldNames[] = {
4060    "__isa",
4061    "__forwarding",
4062    "__flags",
4063    "__size",
4064    "__copy_helper",
4065    "__destroy_helper",
4066    DeclName,
4067  };
4068
4069  for (size_t i = 0; i < 7; ++i) {
4070    if (!HasCopyAndDispose && i >=4 && i <= 5)
4071      continue;
4072    FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(),
4073                                         SourceLocation(),
4074                                         &Idents.get(FieldNames[i]),
4075                                         FieldTypes[i], /*TInfo=*/0,
4076                                         /*BitWidth=*/0, /*Mutable=*/false,
4077                                         ICIS_NoInit);
4078    Field->setAccess(AS_public);
4079    T->addDecl(Field);
4080  }
4081
4082  T->completeDefinition();
4083
4084  return getPointerType(getTagDeclType(T));
4085}
4086
4087TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4088  if (!ObjCInstanceTypeDecl)
4089    ObjCInstanceTypeDecl = TypedefDecl::Create(*this,
4090                                               getTranslationUnitDecl(),
4091                                               SourceLocation(),
4092                                               SourceLocation(),
4093                                               &Idents.get("instancetype"),
4094                                     getTrivialTypeSourceInfo(getObjCIdType()));
4095  return ObjCInstanceTypeDecl;
4096}
4097
4098// This returns true if a type has been typedefed to BOOL:
4099// typedef <type> BOOL;
4100static bool isTypeTypedefedAsBOOL(QualType T) {
4101  if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4102    if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4103      return II->isStr("BOOL");
4104
4105  return false;
4106}
4107
4108/// getObjCEncodingTypeSize returns size of type for objective-c encoding
4109/// purpose.
4110CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4111  if (!type->isIncompleteArrayType() && type->isIncompleteType())
4112    return CharUnits::Zero();
4113
4114  CharUnits sz = getTypeSizeInChars(type);
4115
4116  // Make all integer and enum types at least as large as an int
4117  if (sz.isPositive() && type->isIntegralOrEnumerationType())
4118    sz = std::max(sz, getTypeSizeInChars(IntTy));
4119  // Treat arrays as pointers, since that's how they're passed in.
4120  else if (type->isArrayType())
4121    sz = getTypeSizeInChars(VoidPtrTy);
4122  return sz;
4123}
4124
4125static inline
4126std::string charUnitsToString(const CharUnits &CU) {
4127  return llvm::itostr(CU.getQuantity());
4128}
4129
4130/// getObjCEncodingForBlock - Return the encoded type for this block
4131/// declaration.
4132std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
4133  std::string S;
4134
4135  const BlockDecl *Decl = Expr->getBlockDecl();
4136  QualType BlockTy =
4137      Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
4138  // Encode result type.
4139  getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S);
4140  // Compute size of all parameters.
4141  // Start with computing size of a pointer in number of bytes.
4142  // FIXME: There might(should) be a better way of doing this computation!
4143  SourceLocation Loc;
4144  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4145  CharUnits ParmOffset = PtrSize;
4146  for (BlockDecl::param_const_iterator PI = Decl->param_begin(),
4147       E = Decl->param_end(); PI != E; ++PI) {
4148    QualType PType = (*PI)->getType();
4149    CharUnits sz = getObjCEncodingTypeSize(PType);
4150    assert (sz.isPositive() && "BlockExpr - Incomplete param type");
4151    ParmOffset += sz;
4152  }
4153  // Size of the argument frame
4154  S += charUnitsToString(ParmOffset);
4155  // Block pointer and offset.
4156  S += "@?0";
4157
4158  // Argument types.
4159  ParmOffset = PtrSize;
4160  for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E =
4161       Decl->param_end(); PI != E; ++PI) {
4162    ParmVarDecl *PVDecl = *PI;
4163    QualType PType = PVDecl->getOriginalType();
4164    if (const ArrayType *AT =
4165          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4166      // Use array's original type only if it has known number of
4167      // elements.
4168      if (!isa<ConstantArrayType>(AT))
4169        PType = PVDecl->getType();
4170    } else if (PType->isFunctionType())
4171      PType = PVDecl->getType();
4172    getObjCEncodingForType(PType, S);
4173    S += charUnitsToString(ParmOffset);
4174    ParmOffset += getObjCEncodingTypeSize(PType);
4175  }
4176
4177  return S;
4178}
4179
4180bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
4181                                                std::string& S) {
4182  // Encode result type.
4183  getObjCEncodingForType(Decl->getResultType(), S);
4184  CharUnits ParmOffset;
4185  // Compute size of all parameters.
4186  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4187       E = Decl->param_end(); PI != E; ++PI) {
4188    QualType PType = (*PI)->getType();
4189    CharUnits sz = getObjCEncodingTypeSize(PType);
4190    if (sz.isZero())
4191      return true;
4192
4193    assert (sz.isPositive() &&
4194        "getObjCEncodingForFunctionDecl - Incomplete param type");
4195    ParmOffset += sz;
4196  }
4197  S += charUnitsToString(ParmOffset);
4198  ParmOffset = CharUnits::Zero();
4199
4200  // Argument types.
4201  for (FunctionDecl::param_const_iterator PI = Decl->param_begin(),
4202       E = Decl->param_end(); PI != E; ++PI) {
4203    ParmVarDecl *PVDecl = *PI;
4204    QualType PType = PVDecl->getOriginalType();
4205    if (const ArrayType *AT =
4206          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4207      // Use array's original type only if it has known number of
4208      // elements.
4209      if (!isa<ConstantArrayType>(AT))
4210        PType = PVDecl->getType();
4211    } else if (PType->isFunctionType())
4212      PType = PVDecl->getType();
4213    getObjCEncodingForType(PType, S);
4214    S += charUnitsToString(ParmOffset);
4215    ParmOffset += getObjCEncodingTypeSize(PType);
4216  }
4217
4218  return false;
4219}
4220
4221/// getObjCEncodingForMethodParameter - Return the encoded type for a single
4222/// method parameter or return type. If Extended, include class names and
4223/// block object types.
4224void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
4225                                                   QualType T, std::string& S,
4226                                                   bool Extended) const {
4227  // Encode type qualifer, 'in', 'inout', etc. for the parameter.
4228  getObjCEncodingForTypeQualifier(QT, S);
4229  // Encode parameter type.
4230  getObjCEncodingForTypeImpl(T, S, true, true, 0,
4231                             true     /*OutermostType*/,
4232                             false    /*EncodingProperty*/,
4233                             false    /*StructField*/,
4234                             Extended /*EncodeBlockParameters*/,
4235                             Extended /*EncodeClassNames*/);
4236}
4237
4238/// getObjCEncodingForMethodDecl - Return the encoded type for this method
4239/// declaration.
4240bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
4241                                              std::string& S,
4242                                              bool Extended) const {
4243  // FIXME: This is not very efficient.
4244  // Encode return type.
4245  getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
4246                                    Decl->getResultType(), S, Extended);
4247  // Compute size of all parameters.
4248  // Start with computing size of a pointer in number of bytes.
4249  // FIXME: There might(should) be a better way of doing this computation!
4250  SourceLocation Loc;
4251  CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
4252  // The first two arguments (self and _cmd) are pointers; account for
4253  // their size.
4254  CharUnits ParmOffset = 2 * PtrSize;
4255  for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4256       E = Decl->sel_param_end(); PI != E; ++PI) {
4257    QualType PType = (*PI)->getType();
4258    CharUnits sz = getObjCEncodingTypeSize(PType);
4259    if (sz.isZero())
4260      return true;
4261
4262    assert (sz.isPositive() &&
4263        "getObjCEncodingForMethodDecl - Incomplete param type");
4264    ParmOffset += sz;
4265  }
4266  S += charUnitsToString(ParmOffset);
4267  S += "@0:";
4268  S += charUnitsToString(PtrSize);
4269
4270  // Argument types.
4271  ParmOffset = 2 * PtrSize;
4272  for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
4273       E = Decl->sel_param_end(); PI != E; ++PI) {
4274    const ParmVarDecl *PVDecl = *PI;
4275    QualType PType = PVDecl->getOriginalType();
4276    if (const ArrayType *AT =
4277          dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
4278      // Use array's original type only if it has known number of
4279      // elements.
4280      if (!isa<ConstantArrayType>(AT))
4281        PType = PVDecl->getType();
4282    } else if (PType->isFunctionType())
4283      PType = PVDecl->getType();
4284    getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
4285                                      PType, S, Extended);
4286    S += charUnitsToString(ParmOffset);
4287    ParmOffset += getObjCEncodingTypeSize(PType);
4288  }
4289
4290  return false;
4291}
4292
4293/// getObjCEncodingForPropertyDecl - Return the encoded type for this
4294/// property declaration. If non-NULL, Container must be either an
4295/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
4296/// NULL when getting encodings for protocol properties.
4297/// Property attributes are stored as a comma-delimited C string. The simple
4298/// attributes readonly and bycopy are encoded as single characters. The
4299/// parametrized attributes, getter=name, setter=name, and ivar=name, are
4300/// encoded as single characters, followed by an identifier. Property types
4301/// are also encoded as a parametrized attribute. The characters used to encode
4302/// these attributes are defined by the following enumeration:
4303/// @code
4304/// enum PropertyAttributes {
4305/// kPropertyReadOnly = 'R',   // property is read-only.
4306/// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
4307/// kPropertyByref = '&',  // property is a reference to the value last assigned
4308/// kPropertyDynamic = 'D',    // property is dynamic
4309/// kPropertyGetter = 'G',     // followed by getter selector name
4310/// kPropertySetter = 'S',     // followed by setter selector name
4311/// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
4312/// kPropertyType = 'T'              // followed by old-style type encoding.
4313/// kPropertyWeak = 'W'              // 'weak' property
4314/// kPropertyStrong = 'P'            // property GC'able
4315/// kPropertyNonAtomic = 'N'         // property non-atomic
4316/// };
4317/// @endcode
4318void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
4319                                                const Decl *Container,
4320                                                std::string& S) const {
4321  // Collect information from the property implementation decl(s).
4322  bool Dynamic = false;
4323  ObjCPropertyImplDecl *SynthesizePID = 0;
4324
4325  // FIXME: Duplicated code due to poor abstraction.
4326  if (Container) {
4327    if (const ObjCCategoryImplDecl *CID =
4328        dyn_cast<ObjCCategoryImplDecl>(Container)) {
4329      for (ObjCCategoryImplDecl::propimpl_iterator
4330             i = CID->propimpl_begin(), e = CID->propimpl_end();
4331           i != e; ++i) {
4332        ObjCPropertyImplDecl *PID = *i;
4333        if (PID->getPropertyDecl() == PD) {
4334          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4335            Dynamic = true;
4336          } else {
4337            SynthesizePID = PID;
4338          }
4339        }
4340      }
4341    } else {
4342      const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
4343      for (ObjCCategoryImplDecl::propimpl_iterator
4344             i = OID->propimpl_begin(), e = OID->propimpl_end();
4345           i != e; ++i) {
4346        ObjCPropertyImplDecl *PID = *i;
4347        if (PID->getPropertyDecl() == PD) {
4348          if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) {
4349            Dynamic = true;
4350          } else {
4351            SynthesizePID = PID;
4352          }
4353        }
4354      }
4355    }
4356  }
4357
4358  // FIXME: This is not very efficient.
4359  S = "T";
4360
4361  // Encode result type.
4362  // GCC has some special rules regarding encoding of properties which
4363  // closely resembles encoding of ivars.
4364  getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0,
4365                             true /* outermost type */,
4366                             true /* encoding for property */);
4367
4368  if (PD->isReadOnly()) {
4369    S += ",R";
4370  } else {
4371    switch (PD->getSetterKind()) {
4372    case ObjCPropertyDecl::Assign: break;
4373    case ObjCPropertyDecl::Copy:   S += ",C"; break;
4374    case ObjCPropertyDecl::Retain: S += ",&"; break;
4375    case ObjCPropertyDecl::Weak:   S += ",W"; break;
4376    }
4377  }
4378
4379  // It really isn't clear at all what this means, since properties
4380  // are "dynamic by default".
4381  if (Dynamic)
4382    S += ",D";
4383
4384  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
4385    S += ",N";
4386
4387  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
4388    S += ",G";
4389    S += PD->getGetterName().getAsString();
4390  }
4391
4392  if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
4393    S += ",S";
4394    S += PD->getSetterName().getAsString();
4395  }
4396
4397  if (SynthesizePID) {
4398    const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
4399    S += ",V";
4400    S += OID->getNameAsString();
4401  }
4402
4403  // FIXME: OBJCGC: weak & strong
4404}
4405
4406/// getLegacyIntegralTypeEncoding -
4407/// Another legacy compatibility encoding: 32-bit longs are encoded as
4408/// 'l' or 'L' , but not always.  For typedefs, we need to use
4409/// 'i' or 'I' instead if encoding a struct field, or a pointer!
4410///
4411void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
4412  if (isa<TypedefType>(PointeeTy.getTypePtr())) {
4413    if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
4414      if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
4415        PointeeTy = UnsignedIntTy;
4416      else
4417        if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
4418          PointeeTy = IntTy;
4419    }
4420  }
4421}
4422
4423void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
4424                                        const FieldDecl *Field) const {
4425  // We follow the behavior of gcc, expanding structures which are
4426  // directly pointed to, and expanding embedded structures. Note that
4427  // these rules are sufficient to prevent recursive encoding of the
4428  // same type.
4429  getObjCEncodingForTypeImpl(T, S, true, true, Field,
4430                             true /* outermost type */);
4431}
4432
4433static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) {
4434    switch (T->getAs<BuiltinType>()->getKind()) {
4435    default: llvm_unreachable("Unhandled builtin type kind");
4436    case BuiltinType::Void:       return 'v';
4437    case BuiltinType::Bool:       return 'B';
4438    case BuiltinType::Char_U:
4439    case BuiltinType::UChar:      return 'C';
4440    case BuiltinType::UShort:     return 'S';
4441    case BuiltinType::UInt:       return 'I';
4442    case BuiltinType::ULong:
4443        return C->getIntWidth(T) == 32 ? 'L' : 'Q';
4444    case BuiltinType::UInt128:    return 'T';
4445    case BuiltinType::ULongLong:  return 'Q';
4446    case BuiltinType::Char_S:
4447    case BuiltinType::SChar:      return 'c';
4448    case BuiltinType::Short:      return 's';
4449    case BuiltinType::WChar_S:
4450    case BuiltinType::WChar_U:
4451    case BuiltinType::Int:        return 'i';
4452    case BuiltinType::Long:
4453      return C->getIntWidth(T) == 32 ? 'l' : 'q';
4454    case BuiltinType::LongLong:   return 'q';
4455    case BuiltinType::Int128:     return 't';
4456    case BuiltinType::Float:      return 'f';
4457    case BuiltinType::Double:     return 'd';
4458    case BuiltinType::LongDouble: return 'D';
4459    }
4460}
4461
4462static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
4463  EnumDecl *Enum = ET->getDecl();
4464
4465  // The encoding of an non-fixed enum type is always 'i', regardless of size.
4466  if (!Enum->isFixed())
4467    return 'i';
4468
4469  // The encoding of a fixed enum type matches its fixed underlying type.
4470  return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType());
4471}
4472
4473static void EncodeBitField(const ASTContext *Ctx, std::string& S,
4474                           QualType T, const FieldDecl *FD) {
4475  assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
4476  S += 'b';
4477  // The NeXT runtime encodes bit fields as b followed by the number of bits.
4478  // The GNU runtime requires more information; bitfields are encoded as b,
4479  // then the offset (in bits) of the first element, then the type of the
4480  // bitfield, then the size in bits.  For example, in this structure:
4481  //
4482  // struct
4483  // {
4484  //    int integer;
4485  //    int flags:2;
4486  // };
4487  // On a 32-bit system, the encoding for flags would be b2 for the NeXT
4488  // runtime, but b32i2 for the GNU runtime.  The reason for this extra
4489  // information is not especially sensible, but we're stuck with it for
4490  // compatibility with GCC, although providing it breaks anything that
4491  // actually uses runtime introspection and wants to work on both runtimes...
4492  if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
4493    const RecordDecl *RD = FD->getParent();
4494    const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
4495    S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
4496    if (const EnumType *ET = T->getAs<EnumType>())
4497      S += ObjCEncodingForEnumType(Ctx, ET);
4498    else
4499      S += ObjCEncodingForPrimitiveKind(Ctx, T);
4500  }
4501  S += llvm::utostr(FD->getBitWidthValue(*Ctx));
4502}
4503
4504// FIXME: Use SmallString for accumulating string.
4505void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
4506                                            bool ExpandPointedToStructures,
4507                                            bool ExpandStructures,
4508                                            const FieldDecl *FD,
4509                                            bool OutermostType,
4510                                            bool EncodingProperty,
4511                                            bool StructField,
4512                                            bool EncodeBlockParameters,
4513                                            bool EncodeClassNames) const {
4514  if (T->getAs<BuiltinType>()) {
4515    if (FD && FD->isBitField())
4516      return EncodeBitField(this, S, T, FD);
4517    S += ObjCEncodingForPrimitiveKind(this, T);
4518    return;
4519  }
4520
4521  if (const ComplexType *CT = T->getAs<ComplexType>()) {
4522    S += 'j';
4523    getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false,
4524                               false);
4525    return;
4526  }
4527
4528  // encoding for pointer or r3eference types.
4529  QualType PointeeTy;
4530  if (const PointerType *PT = T->getAs<PointerType>()) {
4531    if (PT->isObjCSelType()) {
4532      S += ':';
4533      return;
4534    }
4535    PointeeTy = PT->getPointeeType();
4536  }
4537  else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4538    PointeeTy = RT->getPointeeType();
4539  if (!PointeeTy.isNull()) {
4540    bool isReadOnly = false;
4541    // For historical/compatibility reasons, the read-only qualifier of the
4542    // pointee gets emitted _before_ the '^'.  The read-only qualifier of
4543    // the pointer itself gets ignored, _unless_ we are looking at a typedef!
4544    // Also, do not emit the 'r' for anything but the outermost type!
4545    if (isa<TypedefType>(T.getTypePtr())) {
4546      if (OutermostType && T.isConstQualified()) {
4547        isReadOnly = true;
4548        S += 'r';
4549      }
4550    } else if (OutermostType) {
4551      QualType P = PointeeTy;
4552      while (P->getAs<PointerType>())
4553        P = P->getAs<PointerType>()->getPointeeType();
4554      if (P.isConstQualified()) {
4555        isReadOnly = true;
4556        S += 'r';
4557      }
4558    }
4559    if (isReadOnly) {
4560      // Another legacy compatibility encoding. Some ObjC qualifier and type
4561      // combinations need to be rearranged.
4562      // Rewrite "in const" from "nr" to "rn"
4563      if (StringRef(S).endswith("nr"))
4564        S.replace(S.end()-2, S.end(), "rn");
4565    }
4566
4567    if (PointeeTy->isCharType()) {
4568      // char pointer types should be encoded as '*' unless it is a
4569      // type that has been typedef'd to 'BOOL'.
4570      if (!isTypeTypedefedAsBOOL(PointeeTy)) {
4571        S += '*';
4572        return;
4573      }
4574    } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
4575      // GCC binary compat: Need to convert "struct objc_class *" to "#".
4576      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
4577        S += '#';
4578        return;
4579      }
4580      // GCC binary compat: Need to convert "struct objc_object *" to "@".
4581      if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
4582        S += '@';
4583        return;
4584      }
4585      // fall through...
4586    }
4587    S += '^';
4588    getLegacyIntegralTypeEncoding(PointeeTy);
4589
4590    getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
4591                               NULL);
4592    return;
4593  }
4594
4595  if (const ArrayType *AT =
4596      // Ignore type qualifiers etc.
4597        dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) {
4598    if (isa<IncompleteArrayType>(AT) && !StructField) {
4599      // Incomplete arrays are encoded as a pointer to the array element.
4600      S += '^';
4601
4602      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4603                                 false, ExpandStructures, FD);
4604    } else {
4605      S += '[';
4606
4607      if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4608        if (getTypeSize(CAT->getElementType()) == 0)
4609          S += '0';
4610        else
4611          S += llvm::utostr(CAT->getSize().getZExtValue());
4612      } else {
4613        //Variable length arrays are encoded as a regular array with 0 elements.
4614        assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
4615               "Unknown array type!");
4616        S += '0';
4617      }
4618
4619      getObjCEncodingForTypeImpl(AT->getElementType(), S,
4620                                 false, ExpandStructures, FD);
4621      S += ']';
4622    }
4623    return;
4624  }
4625
4626  if (T->getAs<FunctionType>()) {
4627    S += '?';
4628    return;
4629  }
4630
4631  if (const RecordType *RTy = T->getAs<RecordType>()) {
4632    RecordDecl *RDecl = RTy->getDecl();
4633    S += RDecl->isUnion() ? '(' : '{';
4634    // Anonymous structures print as '?'
4635    if (const IdentifierInfo *II = RDecl->getIdentifier()) {
4636      S += II->getName();
4637      if (ClassTemplateSpecializationDecl *Spec
4638          = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
4639        const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
4640        std::string TemplateArgsStr
4641          = TemplateSpecializationType::PrintTemplateArgumentList(
4642                                            TemplateArgs.data(),
4643                                            TemplateArgs.size(),
4644                                            (*this).getPrintingPolicy());
4645
4646        S += TemplateArgsStr;
4647      }
4648    } else {
4649      S += '?';
4650    }
4651    if (ExpandStructures) {
4652      S += '=';
4653      if (!RDecl->isUnion()) {
4654        getObjCEncodingForStructureImpl(RDecl, S, FD);
4655      } else {
4656        for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4657                                     FieldEnd = RDecl->field_end();
4658             Field != FieldEnd; ++Field) {
4659          if (FD) {
4660            S += '"';
4661            S += Field->getNameAsString();
4662            S += '"';
4663          }
4664
4665          // Special case bit-fields.
4666          if (Field->isBitField()) {
4667            getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
4668                                       *Field);
4669          } else {
4670            QualType qt = Field->getType();
4671            getLegacyIntegralTypeEncoding(qt);
4672            getObjCEncodingForTypeImpl(qt, S, false, true,
4673                                       FD, /*OutermostType*/false,
4674                                       /*EncodingProperty*/false,
4675                                       /*StructField*/true);
4676          }
4677        }
4678      }
4679    }
4680    S += RDecl->isUnion() ? ')' : '}';
4681    return;
4682  }
4683
4684  if (const EnumType *ET = T->getAs<EnumType>()) {
4685    if (FD && FD->isBitField())
4686      EncodeBitField(this, S, T, FD);
4687    else
4688      S += ObjCEncodingForEnumType(this, ET);
4689    return;
4690  }
4691
4692  if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
4693    S += "@?"; // Unlike a pointer-to-function, which is "^?".
4694    if (EncodeBlockParameters) {
4695      const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>();
4696
4697      S += '<';
4698      // Block return type
4699      getObjCEncodingForTypeImpl(FT->getResultType(), S,
4700                                 ExpandPointedToStructures, ExpandStructures,
4701                                 FD,
4702                                 false /* OutermostType */,
4703                                 EncodingProperty,
4704                                 false /* StructField */,
4705                                 EncodeBlockParameters,
4706                                 EncodeClassNames);
4707      // Block self
4708      S += "@?";
4709      // Block parameters
4710      if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
4711        for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(),
4712               E = FPT->arg_type_end(); I && (I != E); ++I) {
4713          getObjCEncodingForTypeImpl(*I, S,
4714                                     ExpandPointedToStructures,
4715                                     ExpandStructures,
4716                                     FD,
4717                                     false /* OutermostType */,
4718                                     EncodingProperty,
4719                                     false /* StructField */,
4720                                     EncodeBlockParameters,
4721                                     EncodeClassNames);
4722        }
4723      }
4724      S += '>';
4725    }
4726    return;
4727  }
4728
4729  // Ignore protocol qualifiers when mangling at this level.
4730  if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>())
4731    T = OT->getBaseType();
4732
4733  if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
4734    // @encode(class_name)
4735    ObjCInterfaceDecl *OI = OIT->getDecl();
4736    S += '{';
4737    const IdentifierInfo *II = OI->getIdentifier();
4738    S += II->getName();
4739    S += '=';
4740    SmallVector<const ObjCIvarDecl*, 32> Ivars;
4741    DeepCollectObjCIvars(OI, true, Ivars);
4742    for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
4743      const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
4744      if (Field->isBitField())
4745        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
4746      else
4747        getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD);
4748    }
4749    S += '}';
4750    return;
4751  }
4752
4753  if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
4754    if (OPT->isObjCIdType()) {
4755      S += '@';
4756      return;
4757    }
4758
4759    if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
4760      // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
4761      // Since this is a binary compatibility issue, need to consult with runtime
4762      // folks. Fortunately, this is a *very* obsure construct.
4763      S += '#';
4764      return;
4765    }
4766
4767    if (OPT->isObjCQualifiedIdType()) {
4768      getObjCEncodingForTypeImpl(getObjCIdType(), S,
4769                                 ExpandPointedToStructures,
4770                                 ExpandStructures, FD);
4771      if (FD || EncodingProperty || EncodeClassNames) {
4772        // Note that we do extended encoding of protocol qualifer list
4773        // Only when doing ivar or property encoding.
4774        S += '"';
4775        for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4776             E = OPT->qual_end(); I != E; ++I) {
4777          S += '<';
4778          S += (*I)->getNameAsString();
4779          S += '>';
4780        }
4781        S += '"';
4782      }
4783      return;
4784    }
4785
4786    QualType PointeeTy = OPT->getPointeeType();
4787    if (!EncodingProperty &&
4788        isa<TypedefType>(PointeeTy.getTypePtr())) {
4789      // Another historical/compatibility reason.
4790      // We encode the underlying type which comes out as
4791      // {...};
4792      S += '^';
4793      getObjCEncodingForTypeImpl(PointeeTy, S,
4794                                 false, ExpandPointedToStructures,
4795                                 NULL);
4796      return;
4797    }
4798
4799    S += '@';
4800    if (OPT->getInterfaceDecl() &&
4801        (FD || EncodingProperty || EncodeClassNames)) {
4802      S += '"';
4803      S += OPT->getInterfaceDecl()->getIdentifier()->getName();
4804      for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
4805           E = OPT->qual_end(); I != E; ++I) {
4806        S += '<';
4807        S += (*I)->getNameAsString();
4808        S += '>';
4809      }
4810      S += '"';
4811    }
4812    return;
4813  }
4814
4815  // gcc just blithely ignores member pointers.
4816  // TODO: maybe there should be a mangling for these
4817  if (T->getAs<MemberPointerType>())
4818    return;
4819
4820  if (T->isVectorType()) {
4821    // This matches gcc's encoding, even though technically it is
4822    // insufficient.
4823    // FIXME. We should do a better job than gcc.
4824    return;
4825  }
4826
4827  llvm_unreachable("@encode for type not implemented!");
4828}
4829
4830void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
4831                                                 std::string &S,
4832                                                 const FieldDecl *FD,
4833                                                 bool includeVBases) const {
4834  assert(RDecl && "Expected non-null RecordDecl");
4835  assert(!RDecl->isUnion() && "Should not be called for unions");
4836  if (!RDecl->getDefinition())
4837    return;
4838
4839  CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
4840  std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
4841  const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
4842
4843  if (CXXRec) {
4844    for (CXXRecordDecl::base_class_iterator
4845           BI = CXXRec->bases_begin(),
4846           BE = CXXRec->bases_end(); BI != BE; ++BI) {
4847      if (!BI->isVirtual()) {
4848        CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4849        if (base->isEmpty())
4850          continue;
4851        uint64_t offs = layout.getBaseClassOffsetInBits(base);
4852        FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4853                                  std::make_pair(offs, base));
4854      }
4855    }
4856  }
4857
4858  unsigned i = 0;
4859  for (RecordDecl::field_iterator Field = RDecl->field_begin(),
4860                               FieldEnd = RDecl->field_end();
4861       Field != FieldEnd; ++Field, ++i) {
4862    uint64_t offs = layout.getFieldOffset(i);
4863    FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4864                              std::make_pair(offs, *Field));
4865  }
4866
4867  if (CXXRec && includeVBases) {
4868    for (CXXRecordDecl::base_class_iterator
4869           BI = CXXRec->vbases_begin(),
4870           BE = CXXRec->vbases_end(); BI != BE; ++BI) {
4871      CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl();
4872      if (base->isEmpty())
4873        continue;
4874      uint64_t offs = layout.getVBaseClassOffsetInBits(base);
4875      if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
4876        FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
4877                                  std::make_pair(offs, base));
4878    }
4879  }
4880
4881  CharUnits size;
4882  if (CXXRec) {
4883    size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
4884  } else {
4885    size = layout.getSize();
4886  }
4887
4888  uint64_t CurOffs = 0;
4889  std::multimap<uint64_t, NamedDecl *>::iterator
4890    CurLayObj = FieldOrBaseOffsets.begin();
4891
4892  if (CXXRec && CXXRec->isDynamicClass() &&
4893      (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
4894    if (FD) {
4895      S += "\"_vptr$";
4896      std::string recname = CXXRec->getNameAsString();
4897      if (recname.empty()) recname = "?";
4898      S += recname;
4899      S += '"';
4900    }
4901    S += "^^?";
4902    CurOffs += getTypeSize(VoidPtrTy);
4903  }
4904
4905  if (!RDecl->hasFlexibleArrayMember()) {
4906    // Mark the end of the structure.
4907    uint64_t offs = toBits(size);
4908    FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
4909                              std::make_pair(offs, (NamedDecl*)0));
4910  }
4911
4912  for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
4913    assert(CurOffs <= CurLayObj->first);
4914
4915    if (CurOffs < CurLayObj->first) {
4916      uint64_t padding = CurLayObj->first - CurOffs;
4917      // FIXME: There doesn't seem to be a way to indicate in the encoding that
4918      // packing/alignment of members is different that normal, in which case
4919      // the encoding will be out-of-sync with the real layout.
4920      // If the runtime switches to just consider the size of types without
4921      // taking into account alignment, we could make padding explicit in the
4922      // encoding (e.g. using arrays of chars). The encoding strings would be
4923      // longer then though.
4924      CurOffs += padding;
4925    }
4926
4927    NamedDecl *dcl = CurLayObj->second;
4928    if (dcl == 0)
4929      break; // reached end of structure.
4930
4931    if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
4932      // We expand the bases without their virtual bases since those are going
4933      // in the initial structure. Note that this differs from gcc which
4934      // expands virtual bases each time one is encountered in the hierarchy,
4935      // making the encoding type bigger than it really is.
4936      getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false);
4937      assert(!base->isEmpty());
4938      CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
4939    } else {
4940      FieldDecl *field = cast<FieldDecl>(dcl);
4941      if (FD) {
4942        S += '"';
4943        S += field->getNameAsString();
4944        S += '"';
4945      }
4946
4947      if (field->isBitField()) {
4948        EncodeBitField(this, S, field->getType(), field);
4949        CurOffs += field->getBitWidthValue(*this);
4950      } else {
4951        QualType qt = field->getType();
4952        getLegacyIntegralTypeEncoding(qt);
4953        getObjCEncodingForTypeImpl(qt, S, false, true, FD,
4954                                   /*OutermostType*/false,
4955                                   /*EncodingProperty*/false,
4956                                   /*StructField*/true);
4957        CurOffs += getTypeSize(field->getType());
4958      }
4959    }
4960  }
4961}
4962
4963void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
4964                                                 std::string& S) const {
4965  if (QT & Decl::OBJC_TQ_In)
4966    S += 'n';
4967  if (QT & Decl::OBJC_TQ_Inout)
4968    S += 'N';
4969  if (QT & Decl::OBJC_TQ_Out)
4970    S += 'o';
4971  if (QT & Decl::OBJC_TQ_Bycopy)
4972    S += 'O';
4973  if (QT & Decl::OBJC_TQ_Byref)
4974    S += 'R';
4975  if (QT & Decl::OBJC_TQ_Oneway)
4976    S += 'V';
4977}
4978
4979TypedefDecl *ASTContext::getObjCIdDecl() const {
4980  if (!ObjCIdDecl) {
4981    QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0);
4982    T = getObjCObjectPointerType(T);
4983    TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T);
4984    ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4985                                     getTranslationUnitDecl(),
4986                                     SourceLocation(), SourceLocation(),
4987                                     &Idents.get("id"), IdInfo);
4988  }
4989
4990  return ObjCIdDecl;
4991}
4992
4993TypedefDecl *ASTContext::getObjCSelDecl() const {
4994  if (!ObjCSelDecl) {
4995    QualType SelT = getPointerType(ObjCBuiltinSelTy);
4996    TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT);
4997    ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
4998                                      getTranslationUnitDecl(),
4999                                      SourceLocation(), SourceLocation(),
5000                                      &Idents.get("SEL"), SelInfo);
5001  }
5002  return ObjCSelDecl;
5003}
5004
5005TypedefDecl *ASTContext::getObjCClassDecl() const {
5006  if (!ObjCClassDecl) {
5007    QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0);
5008    T = getObjCObjectPointerType(T);
5009    TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T);
5010    ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this),
5011                                        getTranslationUnitDecl(),
5012                                        SourceLocation(), SourceLocation(),
5013                                        &Idents.get("Class"), ClassInfo);
5014  }
5015
5016  return ObjCClassDecl;
5017}
5018
5019ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5020  if (!ObjCProtocolClassDecl) {
5021    ObjCProtocolClassDecl
5022      = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5023                                  SourceLocation(),
5024                                  &Idents.get("Protocol"),
5025                                  /*PrevDecl=*/0,
5026                                  SourceLocation(), true);
5027  }
5028
5029  return ObjCProtocolClassDecl;
5030}
5031
5032//===----------------------------------------------------------------------===//
5033// __builtin_va_list Construction Functions
5034//===----------------------------------------------------------------------===//
5035
5036static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
5037  // typedef char* __builtin_va_list;
5038  QualType CharPtrType = Context->getPointerType(Context->CharTy);
5039  TypeSourceInfo *TInfo
5040    = Context->getTrivialTypeSourceInfo(CharPtrType);
5041
5042  TypedefDecl *VaListTypeDecl
5043    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5044                          Context->getTranslationUnitDecl(),
5045                          SourceLocation(), SourceLocation(),
5046                          &Context->Idents.get("__builtin_va_list"),
5047                          TInfo);
5048  return VaListTypeDecl;
5049}
5050
5051static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
5052  // typedef void* __builtin_va_list;
5053  QualType VoidPtrType = Context->getPointerType(Context->VoidTy);
5054  TypeSourceInfo *TInfo
5055    = Context->getTrivialTypeSourceInfo(VoidPtrType);
5056
5057  TypedefDecl *VaListTypeDecl
5058    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5059                          Context->getTranslationUnitDecl(),
5060                          SourceLocation(), SourceLocation(),
5061                          &Context->Idents.get("__builtin_va_list"),
5062                          TInfo);
5063  return VaListTypeDecl;
5064}
5065
5066static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
5067  // typedef struct __va_list_tag {
5068  RecordDecl *VaListTagDecl;
5069
5070  VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5071                                   Context->getTranslationUnitDecl(),
5072                                   &Context->Idents.get("__va_list_tag"));
5073  VaListTagDecl->startDefinition();
5074
5075  const size_t NumFields = 5;
5076  QualType FieldTypes[NumFields];
5077  const char *FieldNames[NumFields];
5078
5079  //   unsigned char gpr;
5080  FieldTypes[0] = Context->UnsignedCharTy;
5081  FieldNames[0] = "gpr";
5082
5083  //   unsigned char fpr;
5084  FieldTypes[1] = Context->UnsignedCharTy;
5085  FieldNames[1] = "fpr";
5086
5087  //   unsigned short reserved;
5088  FieldTypes[2] = Context->UnsignedShortTy;
5089  FieldNames[2] = "reserved";
5090
5091  //   void* overflow_arg_area;
5092  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5093  FieldNames[3] = "overflow_arg_area";
5094
5095  //   void* reg_save_area;
5096  FieldTypes[4] = Context->getPointerType(Context->VoidTy);
5097  FieldNames[4] = "reg_save_area";
5098
5099  // Create fields
5100  for (unsigned i = 0; i < NumFields; ++i) {
5101    FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
5102                                         SourceLocation(),
5103                                         SourceLocation(),
5104                                         &Context->Idents.get(FieldNames[i]),
5105                                         FieldTypes[i], /*TInfo=*/0,
5106                                         /*BitWidth=*/0,
5107                                         /*Mutable=*/false,
5108                                         ICIS_NoInit);
5109    Field->setAccess(AS_public);
5110    VaListTagDecl->addDecl(Field);
5111  }
5112  VaListTagDecl->completeDefinition();
5113  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5114
5115  // } __va_list_tag;
5116  TypedefDecl *VaListTagTypedefDecl
5117    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5118                          Context->getTranslationUnitDecl(),
5119                          SourceLocation(), SourceLocation(),
5120                          &Context->Idents.get("__va_list_tag"),
5121                          Context->getTrivialTypeSourceInfo(VaListTagType));
5122  QualType VaListTagTypedefType =
5123    Context->getTypedefType(VaListTagTypedefDecl);
5124
5125  // typedef __va_list_tag __builtin_va_list[1];
5126  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5127  QualType VaListTagArrayType
5128    = Context->getConstantArrayType(VaListTagTypedefType,
5129                                    Size, ArrayType::Normal, 0);
5130  TypeSourceInfo *TInfo
5131    = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5132  TypedefDecl *VaListTypedefDecl
5133    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5134                          Context->getTranslationUnitDecl(),
5135                          SourceLocation(), SourceLocation(),
5136                          &Context->Idents.get("__builtin_va_list"),
5137                          TInfo);
5138
5139  return VaListTypedefDecl;
5140}
5141
5142static TypedefDecl *
5143CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
5144  // typedef struct __va_list_tag {
5145  RecordDecl *VaListTagDecl;
5146  VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
5147                                   Context->getTranslationUnitDecl(),
5148                                   &Context->Idents.get("__va_list_tag"));
5149  VaListTagDecl->startDefinition();
5150
5151  const size_t NumFields = 4;
5152  QualType FieldTypes[NumFields];
5153  const char *FieldNames[NumFields];
5154
5155  //   unsigned gp_offset;
5156  FieldTypes[0] = Context->UnsignedIntTy;
5157  FieldNames[0] = "gp_offset";
5158
5159  //   unsigned fp_offset;
5160  FieldTypes[1] = Context->UnsignedIntTy;
5161  FieldNames[1] = "fp_offset";
5162
5163  //   void* overflow_arg_area;
5164  FieldTypes[2] = Context->getPointerType(Context->VoidTy);
5165  FieldNames[2] = "overflow_arg_area";
5166
5167  //   void* reg_save_area;
5168  FieldTypes[3] = Context->getPointerType(Context->VoidTy);
5169  FieldNames[3] = "reg_save_area";
5170
5171  // Create fields
5172  for (unsigned i = 0; i < NumFields; ++i) {
5173    FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
5174                                         VaListTagDecl,
5175                                         SourceLocation(),
5176                                         SourceLocation(),
5177                                         &Context->Idents.get(FieldNames[i]),
5178                                         FieldTypes[i], /*TInfo=*/0,
5179                                         /*BitWidth=*/0,
5180                                         /*Mutable=*/false,
5181                                         ICIS_NoInit);
5182    Field->setAccess(AS_public);
5183    VaListTagDecl->addDecl(Field);
5184  }
5185  VaListTagDecl->completeDefinition();
5186  QualType VaListTagType = Context->getRecordType(VaListTagDecl);
5187
5188  // } __va_list_tag;
5189  TypedefDecl *VaListTagTypedefDecl
5190    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5191                          Context->getTranslationUnitDecl(),
5192                          SourceLocation(), SourceLocation(),
5193                          &Context->Idents.get("__va_list_tag"),
5194                          Context->getTrivialTypeSourceInfo(VaListTagType));
5195  QualType VaListTagTypedefType =
5196    Context->getTypedefType(VaListTagTypedefDecl);
5197
5198  // typedef __va_list_tag __builtin_va_list[1];
5199  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
5200  QualType VaListTagArrayType
5201    = Context->getConstantArrayType(VaListTagTypedefType,
5202                                      Size, ArrayType::Normal,0);
5203  TypeSourceInfo *TInfo
5204    = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
5205  TypedefDecl *VaListTypedefDecl
5206    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5207                          Context->getTranslationUnitDecl(),
5208                          SourceLocation(), SourceLocation(),
5209                          &Context->Idents.get("__builtin_va_list"),
5210                          TInfo);
5211
5212  return VaListTypedefDecl;
5213}
5214
5215static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
5216  // typedef int __builtin_va_list[4];
5217  llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
5218  QualType IntArrayType
5219    = Context->getConstantArrayType(Context->IntTy,
5220				    Size, ArrayType::Normal, 0);
5221  TypedefDecl *VaListTypedefDecl
5222    = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
5223                          Context->getTranslationUnitDecl(),
5224                          SourceLocation(), SourceLocation(),
5225                          &Context->Idents.get("__builtin_va_list"),
5226                          Context->getTrivialTypeSourceInfo(IntArrayType));
5227
5228  return VaListTypedefDecl;
5229}
5230
5231static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
5232                                     TargetInfo::BuiltinVaListKind Kind) {
5233  switch (Kind) {
5234  case TargetInfo::CharPtrBuiltinVaList:
5235    return CreateCharPtrBuiltinVaListDecl(Context);
5236  case TargetInfo::VoidPtrBuiltinVaList:
5237    return CreateVoidPtrBuiltinVaListDecl(Context);
5238  case TargetInfo::PowerABIBuiltinVaList:
5239    return CreatePowerABIBuiltinVaListDecl(Context);
5240  case TargetInfo::X86_64ABIBuiltinVaList:
5241    return CreateX86_64ABIBuiltinVaListDecl(Context);
5242  case TargetInfo::PNaClABIBuiltinVaList:
5243    return CreatePNaClABIBuiltinVaListDecl(Context);
5244  }
5245
5246  llvm_unreachable("Unhandled __builtin_va_list type kind");
5247}
5248
5249TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
5250  if (!BuiltinVaListDecl)
5251    BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
5252
5253  return BuiltinVaListDecl;
5254}
5255
5256void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
5257  assert(ObjCConstantStringType.isNull() &&
5258         "'NSConstantString' type already set!");
5259
5260  ObjCConstantStringType = getObjCInterfaceType(Decl);
5261}
5262
5263/// \brief Retrieve the template name that corresponds to a non-empty
5264/// lookup.
5265TemplateName
5266ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
5267                                      UnresolvedSetIterator End) const {
5268  unsigned size = End - Begin;
5269  assert(size > 1 && "set is not overloaded!");
5270
5271  void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
5272                          size * sizeof(FunctionTemplateDecl*));
5273  OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
5274
5275  NamedDecl **Storage = OT->getStorage();
5276  for (UnresolvedSetIterator I = Begin; I != End; ++I) {
5277    NamedDecl *D = *I;
5278    assert(isa<FunctionTemplateDecl>(D) ||
5279           (isa<UsingShadowDecl>(D) &&
5280            isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
5281    *Storage++ = D;
5282  }
5283
5284  return TemplateName(OT);
5285}
5286
5287/// \brief Retrieve the template name that represents a qualified
5288/// template name such as \c std::vector.
5289TemplateName
5290ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
5291                                     bool TemplateKeyword,
5292                                     TemplateDecl *Template) const {
5293  assert(NNS && "Missing nested-name-specifier in qualified template name");
5294
5295  // FIXME: Canonicalization?
5296  llvm::FoldingSetNodeID ID;
5297  QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
5298
5299  void *InsertPos = 0;
5300  QualifiedTemplateName *QTN =
5301    QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5302  if (!QTN) {
5303    QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template);
5304    QualifiedTemplateNames.InsertNode(QTN, InsertPos);
5305  }
5306
5307  return TemplateName(QTN);
5308}
5309
5310/// \brief Retrieve the template name that represents a dependent
5311/// template name such as \c MetaFun::template apply.
5312TemplateName
5313ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5314                                     const IdentifierInfo *Name) const {
5315  assert((!NNS || NNS->isDependent()) &&
5316         "Nested name specifier must be dependent");
5317
5318  llvm::FoldingSetNodeID ID;
5319  DependentTemplateName::Profile(ID, NNS, Name);
5320
5321  void *InsertPos = 0;
5322  DependentTemplateName *QTN =
5323    DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5324
5325  if (QTN)
5326    return TemplateName(QTN);
5327
5328  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5329  if (CanonNNS == NNS) {
5330    QTN = new (*this,4) DependentTemplateName(NNS, Name);
5331  } else {
5332    TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
5333    QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon);
5334    DependentTemplateName *CheckQTN =
5335      DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5336    assert(!CheckQTN && "Dependent type name canonicalization broken");
5337    (void)CheckQTN;
5338  }
5339
5340  DependentTemplateNames.InsertNode(QTN, InsertPos);
5341  return TemplateName(QTN);
5342}
5343
5344/// \brief Retrieve the template name that represents a dependent
5345/// template name such as \c MetaFun::template operator+.
5346TemplateName
5347ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
5348                                     OverloadedOperatorKind Operator) const {
5349  assert((!NNS || NNS->isDependent()) &&
5350         "Nested name specifier must be dependent");
5351
5352  llvm::FoldingSetNodeID ID;
5353  DependentTemplateName::Profile(ID, NNS, Operator);
5354
5355  void *InsertPos = 0;
5356  DependentTemplateName *QTN
5357    = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5358
5359  if (QTN)
5360    return TemplateName(QTN);
5361
5362  NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
5363  if (CanonNNS == NNS) {
5364    QTN = new (*this,4) DependentTemplateName(NNS, Operator);
5365  } else {
5366    TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
5367    QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon);
5368
5369    DependentTemplateName *CheckQTN
5370      = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
5371    assert(!CheckQTN && "Dependent template name canonicalization broken");
5372    (void)CheckQTN;
5373  }
5374
5375  DependentTemplateNames.InsertNode(QTN, InsertPos);
5376  return TemplateName(QTN);
5377}
5378
5379TemplateName
5380ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
5381                                         TemplateName replacement) const {
5382  llvm::FoldingSetNodeID ID;
5383  SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
5384
5385  void *insertPos = 0;
5386  SubstTemplateTemplateParmStorage *subst
5387    = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
5388
5389  if (!subst) {
5390    subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
5391    SubstTemplateTemplateParms.InsertNode(subst, insertPos);
5392  }
5393
5394  return TemplateName(subst);
5395}
5396
5397TemplateName
5398ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
5399                                       const TemplateArgument &ArgPack) const {
5400  ASTContext &Self = const_cast<ASTContext &>(*this);
5401  llvm::FoldingSetNodeID ID;
5402  SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
5403
5404  void *InsertPos = 0;
5405  SubstTemplateTemplateParmPackStorage *Subst
5406    = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
5407
5408  if (!Subst) {
5409    Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
5410                                                           ArgPack.pack_size(),
5411                                                         ArgPack.pack_begin());
5412    SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
5413  }
5414
5415  return TemplateName(Subst);
5416}
5417
5418/// getFromTargetType - Given one of the integer types provided by
5419/// TargetInfo, produce the corresponding type. The unsigned @p Type
5420/// is actually a value of type @c TargetInfo::IntType.
5421CanQualType ASTContext::getFromTargetType(unsigned Type) const {
5422  switch (Type) {
5423  case TargetInfo::NoInt: return CanQualType();
5424  case TargetInfo::SignedShort: return ShortTy;
5425  case TargetInfo::UnsignedShort: return UnsignedShortTy;
5426  case TargetInfo::SignedInt: return IntTy;
5427  case TargetInfo::UnsignedInt: return UnsignedIntTy;
5428  case TargetInfo::SignedLong: return LongTy;
5429  case TargetInfo::UnsignedLong: return UnsignedLongTy;
5430  case TargetInfo::SignedLongLong: return LongLongTy;
5431  case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
5432  }
5433
5434  llvm_unreachable("Unhandled TargetInfo::IntType value");
5435}
5436
5437//===----------------------------------------------------------------------===//
5438//                        Type Predicates.
5439//===----------------------------------------------------------------------===//
5440
5441/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
5442/// garbage collection attribute.
5443///
5444Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
5445  if (getLangOpts().getGC() == LangOptions::NonGC)
5446    return Qualifiers::GCNone;
5447
5448  assert(getLangOpts().ObjC1);
5449  Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
5450
5451  // Default behaviour under objective-C's gc is for ObjC pointers
5452  // (or pointers to them) be treated as though they were declared
5453  // as __strong.
5454  if (GCAttrs == Qualifiers::GCNone) {
5455    if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
5456      return Qualifiers::Strong;
5457    else if (Ty->isPointerType())
5458      return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
5459  } else {
5460    // It's not valid to set GC attributes on anything that isn't a
5461    // pointer.
5462#ifndef NDEBUG
5463    QualType CT = Ty->getCanonicalTypeInternal();
5464    while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
5465      CT = AT->getElementType();
5466    assert(CT->isAnyPointerType() || CT->isBlockPointerType());
5467#endif
5468  }
5469  return GCAttrs;
5470}
5471
5472//===----------------------------------------------------------------------===//
5473//                        Type Compatibility Testing
5474//===----------------------------------------------------------------------===//
5475
5476/// areCompatVectorTypes - Return true if the two specified vector types are
5477/// compatible.
5478static bool areCompatVectorTypes(const VectorType *LHS,
5479                                 const VectorType *RHS) {
5480  assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
5481  return LHS->getElementType() == RHS->getElementType() &&
5482         LHS->getNumElements() == RHS->getNumElements();
5483}
5484
5485bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
5486                                          QualType SecondVec) {
5487  assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
5488  assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
5489
5490  if (hasSameUnqualifiedType(FirstVec, SecondVec))
5491    return true;
5492
5493  // Treat Neon vector types and most AltiVec vector types as if they are the
5494  // equivalent GCC vector types.
5495  const VectorType *First = FirstVec->getAs<VectorType>();
5496  const VectorType *Second = SecondVec->getAs<VectorType>();
5497  if (First->getNumElements() == Second->getNumElements() &&
5498      hasSameType(First->getElementType(), Second->getElementType()) &&
5499      First->getVectorKind() != VectorType::AltiVecPixel &&
5500      First->getVectorKind() != VectorType::AltiVecBool &&
5501      Second->getVectorKind() != VectorType::AltiVecPixel &&
5502      Second->getVectorKind() != VectorType::AltiVecBool)
5503    return true;
5504
5505  return false;
5506}
5507
5508//===----------------------------------------------------------------------===//
5509// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
5510//===----------------------------------------------------------------------===//
5511
5512/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
5513/// inheritance hierarchy of 'rProto'.
5514bool
5515ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
5516                                           ObjCProtocolDecl *rProto) const {
5517  if (declaresSameEntity(lProto, rProto))
5518    return true;
5519  for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(),
5520       E = rProto->protocol_end(); PI != E; ++PI)
5521    if (ProtocolCompatibleWithProtocol(lProto, *PI))
5522      return true;
5523  return false;
5524}
5525
5526/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
5527/// return true if lhs's protocols conform to rhs's protocol; false
5528/// otherwise.
5529bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) {
5530  if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType())
5531    return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false);
5532  return false;
5533}
5534
5535/// ObjCQualifiedClassTypesAreCompatible - compare  Class<p,...> and
5536/// Class<p1, ...>.
5537bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
5538                                                      QualType rhs) {
5539  const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
5540  const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5541  assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
5542
5543  for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5544       E = lhsQID->qual_end(); I != E; ++I) {
5545    bool match = false;
5546    ObjCProtocolDecl *lhsProto = *I;
5547    for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5548         E = rhsOPT->qual_end(); J != E; ++J) {
5549      ObjCProtocolDecl *rhsProto = *J;
5550      if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
5551        match = true;
5552        break;
5553      }
5554    }
5555    if (!match)
5556      return false;
5557  }
5558  return true;
5559}
5560
5561/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
5562/// ObjCQualifiedIDType.
5563bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
5564                                                   bool compare) {
5565  // Allow id<P..> and an 'id' or void* type in all cases.
5566  if (lhs->isVoidPointerType() ||
5567      lhs->isObjCIdType() || lhs->isObjCClassType())
5568    return true;
5569  else if (rhs->isVoidPointerType() ||
5570           rhs->isObjCIdType() || rhs->isObjCClassType())
5571    return true;
5572
5573  if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
5574    const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
5575
5576    if (!rhsOPT) return false;
5577
5578    if (rhsOPT->qual_empty()) {
5579      // If the RHS is a unqualified interface pointer "NSString*",
5580      // make sure we check the class hierarchy.
5581      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5582        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5583             E = lhsQID->qual_end(); I != E; ++I) {
5584          // when comparing an id<P> on lhs with a static type on rhs,
5585          // see if static class implements all of id's protocols, directly or
5586          // through its super class and categories.
5587          if (!rhsID->ClassImplementsProtocol(*I, true))
5588            return false;
5589        }
5590      }
5591      // If there are no qualifiers and no interface, we have an 'id'.
5592      return true;
5593    }
5594    // Both the right and left sides have qualifiers.
5595    for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5596         E = lhsQID->qual_end(); I != E; ++I) {
5597      ObjCProtocolDecl *lhsProto = *I;
5598      bool match = false;
5599
5600      // when comparing an id<P> on lhs with a static type on rhs,
5601      // see if static class implements all of id's protocols, directly or
5602      // through its super class and categories.
5603      for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(),
5604           E = rhsOPT->qual_end(); J != E; ++J) {
5605        ObjCProtocolDecl *rhsProto = *J;
5606        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5607            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5608          match = true;
5609          break;
5610        }
5611      }
5612      // If the RHS is a qualified interface pointer "NSString<P>*",
5613      // make sure we check the class hierarchy.
5614      if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
5615        for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(),
5616             E = lhsQID->qual_end(); I != E; ++I) {
5617          // when comparing an id<P> on lhs with a static type on rhs,
5618          // see if static class implements all of id's protocols, directly or
5619          // through its super class and categories.
5620          if (rhsID->ClassImplementsProtocol(*I, true)) {
5621            match = true;
5622            break;
5623          }
5624        }
5625      }
5626      if (!match)
5627        return false;
5628    }
5629
5630    return true;
5631  }
5632
5633  const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
5634  assert(rhsQID && "One of the LHS/RHS should be id<x>");
5635
5636  if (const ObjCObjectPointerType *lhsOPT =
5637        lhs->getAsObjCInterfacePointerType()) {
5638    // If both the right and left sides have qualifiers.
5639    for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(),
5640         E = lhsOPT->qual_end(); I != E; ++I) {
5641      ObjCProtocolDecl *lhsProto = *I;
5642      bool match = false;
5643
5644      // when comparing an id<P> on rhs with a static type on lhs,
5645      // see if static class implements all of id's protocols, directly or
5646      // through its super class and categories.
5647      // First, lhs protocols in the qualifier list must be found, direct
5648      // or indirect in rhs's qualifier list or it is a mismatch.
5649      for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5650           E = rhsQID->qual_end(); J != E; ++J) {
5651        ObjCProtocolDecl *rhsProto = *J;
5652        if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5653            (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5654          match = true;
5655          break;
5656        }
5657      }
5658      if (!match)
5659        return false;
5660    }
5661
5662    // Static class's protocols, or its super class or category protocols
5663    // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
5664    if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
5665      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5666      CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
5667      // This is rather dubious but matches gcc's behavior. If lhs has
5668      // no type qualifier and its class has no static protocol(s)
5669      // assume that it is mismatch.
5670      if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
5671        return false;
5672      for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5673           LHSInheritedProtocols.begin(),
5674           E = LHSInheritedProtocols.end(); I != E; ++I) {
5675        bool match = false;
5676        ObjCProtocolDecl *lhsProto = (*I);
5677        for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(),
5678             E = rhsQID->qual_end(); J != E; ++J) {
5679          ObjCProtocolDecl *rhsProto = *J;
5680          if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
5681              (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
5682            match = true;
5683            break;
5684          }
5685        }
5686        if (!match)
5687          return false;
5688      }
5689    }
5690    return true;
5691  }
5692  return false;
5693}
5694
5695/// canAssignObjCInterfaces - Return true if the two interface types are
5696/// compatible for assignment from RHS to LHS.  This handles validation of any
5697/// protocol qualifiers on the LHS or RHS.
5698///
5699bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
5700                                         const ObjCObjectPointerType *RHSOPT) {
5701  const ObjCObjectType* LHS = LHSOPT->getObjectType();
5702  const ObjCObjectType* RHS = RHSOPT->getObjectType();
5703
5704  // If either type represents the built-in 'id' or 'Class' types, return true.
5705  if (LHS->isObjCUnqualifiedIdOrClass() ||
5706      RHS->isObjCUnqualifiedIdOrClass())
5707    return true;
5708
5709  if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId())
5710    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5711                                             QualType(RHSOPT,0),
5712                                             false);
5713
5714  if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass())
5715    return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
5716                                                QualType(RHSOPT,0));
5717
5718  // If we have 2 user-defined types, fall into that path.
5719  if (LHS->getInterface() && RHS->getInterface())
5720    return canAssignObjCInterfaces(LHS, RHS);
5721
5722  return false;
5723}
5724
5725/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
5726/// for providing type-safety for objective-c pointers used to pass/return
5727/// arguments in block literals. When passed as arguments, passing 'A*' where
5728/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
5729/// not OK. For the return type, the opposite is not OK.
5730bool ASTContext::canAssignObjCInterfacesInBlockPointer(
5731                                         const ObjCObjectPointerType *LHSOPT,
5732                                         const ObjCObjectPointerType *RHSOPT,
5733                                         bool BlockReturnType) {
5734  if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
5735    return true;
5736
5737  if (LHSOPT->isObjCBuiltinType()) {
5738    return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType();
5739  }
5740
5741  if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
5742    return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
5743                                             QualType(RHSOPT,0),
5744                                             false);
5745
5746  const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
5747  const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
5748  if (LHS && RHS)  { // We have 2 user-defined types.
5749    if (LHS != RHS) {
5750      if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
5751        return BlockReturnType;
5752      if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
5753        return !BlockReturnType;
5754    }
5755    else
5756      return true;
5757  }
5758  return false;
5759}
5760
5761/// getIntersectionOfProtocols - This routine finds the intersection of set
5762/// of protocols inherited from two distinct objective-c pointer objects.
5763/// It is used to build composite qualifier list of the composite type of
5764/// the conditional expression involving two objective-c pointer objects.
5765static
5766void getIntersectionOfProtocols(ASTContext &Context,
5767                                const ObjCObjectPointerType *LHSOPT,
5768                                const ObjCObjectPointerType *RHSOPT,
5769      SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) {
5770
5771  const ObjCObjectType* LHS = LHSOPT->getObjectType();
5772  const ObjCObjectType* RHS = RHSOPT->getObjectType();
5773  assert(LHS->getInterface() && "LHS must have an interface base");
5774  assert(RHS->getInterface() && "RHS must have an interface base");
5775
5776  llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet;
5777  unsigned LHSNumProtocols = LHS->getNumProtocols();
5778  if (LHSNumProtocols > 0)
5779    InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end());
5780  else {
5781    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
5782    Context.CollectInheritedProtocols(LHS->getInterface(),
5783                                      LHSInheritedProtocols);
5784    InheritedProtocolSet.insert(LHSInheritedProtocols.begin(),
5785                                LHSInheritedProtocols.end());
5786  }
5787
5788  unsigned RHSNumProtocols = RHS->getNumProtocols();
5789  if (RHSNumProtocols > 0) {
5790    ObjCProtocolDecl **RHSProtocols =
5791      const_cast<ObjCProtocolDecl **>(RHS->qual_begin());
5792    for (unsigned i = 0; i < RHSNumProtocols; ++i)
5793      if (InheritedProtocolSet.count(RHSProtocols[i]))
5794        IntersectionOfProtocols.push_back(RHSProtocols[i]);
5795  } else {
5796    llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols;
5797    Context.CollectInheritedProtocols(RHS->getInterface(),
5798                                      RHSInheritedProtocols);
5799    for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5800         RHSInheritedProtocols.begin(),
5801         E = RHSInheritedProtocols.end(); I != E; ++I)
5802      if (InheritedProtocolSet.count((*I)))
5803        IntersectionOfProtocols.push_back((*I));
5804  }
5805}
5806
5807/// areCommonBaseCompatible - Returns common base class of the two classes if
5808/// one found. Note that this is O'2 algorithm. But it will be called as the
5809/// last type comparison in a ?-exp of ObjC pointer types before a
5810/// warning is issued. So, its invokation is extremely rare.
5811QualType ASTContext::areCommonBaseCompatible(
5812                                          const ObjCObjectPointerType *Lptr,
5813                                          const ObjCObjectPointerType *Rptr) {
5814  const ObjCObjectType *LHS = Lptr->getObjectType();
5815  const ObjCObjectType *RHS = Rptr->getObjectType();
5816  const ObjCInterfaceDecl* LDecl = LHS->getInterface();
5817  const ObjCInterfaceDecl* RDecl = RHS->getInterface();
5818  if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl)))
5819    return QualType();
5820
5821  do {
5822    LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl));
5823    if (canAssignObjCInterfaces(LHS, RHS)) {
5824      SmallVector<ObjCProtocolDecl *, 8> Protocols;
5825      getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols);
5826
5827      QualType Result = QualType(LHS, 0);
5828      if (!Protocols.empty())
5829        Result = getObjCObjectType(Result, Protocols.data(), Protocols.size());
5830      Result = getObjCObjectPointerType(Result);
5831      return Result;
5832    }
5833  } while ((LDecl = LDecl->getSuperClass()));
5834
5835  return QualType();
5836}
5837
5838bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
5839                                         const ObjCObjectType *RHS) {
5840  assert(LHS->getInterface() && "LHS is not an interface type");
5841  assert(RHS->getInterface() && "RHS is not an interface type");
5842
5843  // Verify that the base decls are compatible: the RHS must be a subclass of
5844  // the LHS.
5845  if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface()))
5846    return false;
5847
5848  // RHS must have a superset of the protocols in the LHS.  If the LHS is not
5849  // protocol qualified at all, then we are good.
5850  if (LHS->getNumProtocols() == 0)
5851    return true;
5852
5853  // Okay, we know the LHS has protocol qualifiers.  If the RHS doesn't,
5854  // more detailed analysis is required.
5855  if (RHS->getNumProtocols() == 0) {
5856    // OK, if LHS is a superclass of RHS *and*
5857    // this superclass is assignment compatible with LHS.
5858    // false otherwise.
5859    bool IsSuperClass =
5860      LHS->getInterface()->isSuperClassOf(RHS->getInterface());
5861    if (IsSuperClass) {
5862      // OK if conversion of LHS to SuperClass results in narrowing of types
5863      // ; i.e., SuperClass may implement at least one of the protocols
5864      // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
5865      // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
5866      llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
5867      CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
5868      // If super class has no protocols, it is not a match.
5869      if (SuperClassInheritedProtocols.empty())
5870        return false;
5871
5872      for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5873           LHSPE = LHS->qual_end();
5874           LHSPI != LHSPE; LHSPI++) {
5875        bool SuperImplementsProtocol = false;
5876        ObjCProtocolDecl *LHSProto = (*LHSPI);
5877
5878        for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I =
5879             SuperClassInheritedProtocols.begin(),
5880             E = SuperClassInheritedProtocols.end(); I != E; ++I) {
5881          ObjCProtocolDecl *SuperClassProto = (*I);
5882          if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
5883            SuperImplementsProtocol = true;
5884            break;
5885          }
5886        }
5887        if (!SuperImplementsProtocol)
5888          return false;
5889      }
5890      return true;
5891    }
5892    return false;
5893  }
5894
5895  for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(),
5896                                     LHSPE = LHS->qual_end();
5897       LHSPI != LHSPE; LHSPI++) {
5898    bool RHSImplementsProtocol = false;
5899
5900    // If the RHS doesn't implement the protocol on the left, the types
5901    // are incompatible.
5902    for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(),
5903                                       RHSPE = RHS->qual_end();
5904         RHSPI != RHSPE; RHSPI++) {
5905      if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) {
5906        RHSImplementsProtocol = true;
5907        break;
5908      }
5909    }
5910    // FIXME: For better diagnostics, consider passing back the protocol name.
5911    if (!RHSImplementsProtocol)
5912      return false;
5913  }
5914  // The RHS implements all protocols listed on the LHS.
5915  return true;
5916}
5917
5918bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
5919  // get the "pointed to" types
5920  const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
5921  const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
5922
5923  if (!LHSOPT || !RHSOPT)
5924    return false;
5925
5926  return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
5927         canAssignObjCInterfaces(RHSOPT, LHSOPT);
5928}
5929
5930bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
5931  return canAssignObjCInterfaces(
5932                getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
5933                getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
5934}
5935
5936/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
5937/// both shall have the identically qualified version of a compatible type.
5938/// C99 6.2.7p1: Two types have compatible types if their types are the
5939/// same. See 6.7.[2,3,5] for additional rules.
5940bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
5941                                    bool CompareUnqualified) {
5942  if (getLangOpts().CPlusPlus)
5943    return hasSameType(LHS, RHS);
5944
5945  return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
5946}
5947
5948bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
5949  return typesAreCompatible(LHS, RHS);
5950}
5951
5952bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
5953  return !mergeTypes(LHS, RHS, true).isNull();
5954}
5955
5956/// mergeTransparentUnionType - if T is a transparent union type and a member
5957/// of T is compatible with SubType, return the merged type, else return
5958/// QualType()
5959QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
5960                                               bool OfBlockPointer,
5961                                               bool Unqualified) {
5962  if (const RecordType *UT = T->getAsUnionType()) {
5963    RecordDecl *UD = UT->getDecl();
5964    if (UD->hasAttr<TransparentUnionAttr>()) {
5965      for (RecordDecl::field_iterator it = UD->field_begin(),
5966           itend = UD->field_end(); it != itend; ++it) {
5967        QualType ET = it->getType().getUnqualifiedType();
5968        QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
5969        if (!MT.isNull())
5970          return MT;
5971      }
5972    }
5973  }
5974
5975  return QualType();
5976}
5977
5978/// mergeFunctionArgumentTypes - merge two types which appear as function
5979/// argument types
5980QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs,
5981                                                bool OfBlockPointer,
5982                                                bool Unqualified) {
5983  // GNU extension: two types are compatible if they appear as a function
5984  // argument, one of the types is a transparent union type and the other
5985  // type is compatible with a union member
5986  QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
5987                                              Unqualified);
5988  if (!lmerge.isNull())
5989    return lmerge;
5990
5991  QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
5992                                              Unqualified);
5993  if (!rmerge.isNull())
5994    return rmerge;
5995
5996  return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
5997}
5998
5999QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
6000                                        bool OfBlockPointer,
6001                                        bool Unqualified) {
6002  const FunctionType *lbase = lhs->getAs<FunctionType>();
6003  const FunctionType *rbase = rhs->getAs<FunctionType>();
6004  const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
6005  const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
6006  bool allLTypes = true;
6007  bool allRTypes = true;
6008
6009  // Check return type
6010  QualType retType;
6011  if (OfBlockPointer) {
6012    QualType RHS = rbase->getResultType();
6013    QualType LHS = lbase->getResultType();
6014    bool UnqualifiedResult = Unqualified;
6015    if (!UnqualifiedResult)
6016      UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
6017    retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
6018  }
6019  else
6020    retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false,
6021                         Unqualified);
6022  if (retType.isNull()) return QualType();
6023
6024  if (Unqualified)
6025    retType = retType.getUnqualifiedType();
6026
6027  CanQualType LRetType = getCanonicalType(lbase->getResultType());
6028  CanQualType RRetType = getCanonicalType(rbase->getResultType());
6029  if (Unqualified) {
6030    LRetType = LRetType.getUnqualifiedType();
6031    RRetType = RRetType.getUnqualifiedType();
6032  }
6033
6034  if (getCanonicalType(retType) != LRetType)
6035    allLTypes = false;
6036  if (getCanonicalType(retType) != RRetType)
6037    allRTypes = false;
6038
6039  // FIXME: double check this
6040  // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
6041  //                           rbase->getRegParmAttr() != 0 &&
6042  //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
6043  FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
6044  FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
6045
6046  // Compatible functions must have compatible calling conventions
6047  if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC()))
6048    return QualType();
6049
6050  // Regparm is part of the calling convention.
6051  if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
6052    return QualType();
6053  if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
6054    return QualType();
6055
6056  if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
6057    return QualType();
6058
6059  // functypes which return are preferred over those that do not.
6060  if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn())
6061    allLTypes = false;
6062  else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn())
6063    allRTypes = false;
6064  // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
6065  bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
6066
6067  FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
6068
6069  if (lproto && rproto) { // two C99 style function prototypes
6070    assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
6071           "C++ shouldn't be here");
6072    unsigned lproto_nargs = lproto->getNumArgs();
6073    unsigned rproto_nargs = rproto->getNumArgs();
6074
6075    // Compatible functions must have the same number of arguments
6076    if (lproto_nargs != rproto_nargs)
6077      return QualType();
6078
6079    // Variadic and non-variadic functions aren't compatible
6080    if (lproto->isVariadic() != rproto->isVariadic())
6081      return QualType();
6082
6083    if (lproto->getTypeQuals() != rproto->getTypeQuals())
6084      return QualType();
6085
6086    if (LangOpts.ObjCAutoRefCount &&
6087        !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
6088      return QualType();
6089
6090    // Check argument compatibility
6091    SmallVector<QualType, 10> types;
6092    for (unsigned i = 0; i < lproto_nargs; i++) {
6093      QualType largtype = lproto->getArgType(i).getUnqualifiedType();
6094      QualType rargtype = rproto->getArgType(i).getUnqualifiedType();
6095      QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype,
6096                                                    OfBlockPointer,
6097                                                    Unqualified);
6098      if (argtype.isNull()) return QualType();
6099
6100      if (Unqualified)
6101        argtype = argtype.getUnqualifiedType();
6102
6103      types.push_back(argtype);
6104      if (Unqualified) {
6105        largtype = largtype.getUnqualifiedType();
6106        rargtype = rargtype.getUnqualifiedType();
6107      }
6108
6109      if (getCanonicalType(argtype) != getCanonicalType(largtype))
6110        allLTypes = false;
6111      if (getCanonicalType(argtype) != getCanonicalType(rargtype))
6112        allRTypes = false;
6113    }
6114
6115    if (allLTypes) return lhs;
6116    if (allRTypes) return rhs;
6117
6118    FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
6119    EPI.ExtInfo = einfo;
6120    return getFunctionType(retType, types.begin(), types.size(), EPI);
6121  }
6122
6123  if (lproto) allRTypes = false;
6124  if (rproto) allLTypes = false;
6125
6126  const FunctionProtoType *proto = lproto ? lproto : rproto;
6127  if (proto) {
6128    assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
6129    if (proto->isVariadic()) return QualType();
6130    // Check that the types are compatible with the types that
6131    // would result from default argument promotions (C99 6.7.5.3p15).
6132    // The only types actually affected are promotable integer
6133    // types and floats, which would be passed as a different
6134    // type depending on whether the prototype is visible.
6135    unsigned proto_nargs = proto->getNumArgs();
6136    for (unsigned i = 0; i < proto_nargs; ++i) {
6137      QualType argTy = proto->getArgType(i);
6138
6139      // Look at the promotion type of enum types, since that is the type used
6140      // to pass enum values.
6141      if (const EnumType *Enum = argTy->getAs<EnumType>())
6142        argTy = Enum->getDecl()->getPromotionType();
6143
6144      if (argTy->isPromotableIntegerType() ||
6145          getCanonicalType(argTy).getUnqualifiedType() == FloatTy)
6146        return QualType();
6147    }
6148
6149    if (allLTypes) return lhs;
6150    if (allRTypes) return rhs;
6151
6152    FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
6153    EPI.ExtInfo = einfo;
6154    return getFunctionType(retType, proto->arg_type_begin(),
6155                           proto->getNumArgs(), EPI);
6156  }
6157
6158  if (allLTypes) return lhs;
6159  if (allRTypes) return rhs;
6160  return getFunctionNoProtoType(retType, einfo);
6161}
6162
6163QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
6164                                bool OfBlockPointer,
6165                                bool Unqualified, bool BlockReturnType) {
6166  // C++ [expr]: If an expression initially has the type "reference to T", the
6167  // type is adjusted to "T" prior to any further analysis, the expression
6168  // designates the object or function denoted by the reference, and the
6169  // expression is an lvalue unless the reference is an rvalue reference and
6170  // the expression is a function call (possibly inside parentheses).
6171  assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
6172  assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
6173
6174  if (Unqualified) {
6175    LHS = LHS.getUnqualifiedType();
6176    RHS = RHS.getUnqualifiedType();
6177  }
6178
6179  QualType LHSCan = getCanonicalType(LHS),
6180           RHSCan = getCanonicalType(RHS);
6181
6182  // If two types are identical, they are compatible.
6183  if (LHSCan == RHSCan)
6184    return LHS;
6185
6186  // If the qualifiers are different, the types aren't compatible... mostly.
6187  Qualifiers LQuals = LHSCan.getLocalQualifiers();
6188  Qualifiers RQuals = RHSCan.getLocalQualifiers();
6189  if (LQuals != RQuals) {
6190    // If any of these qualifiers are different, we have a type
6191    // mismatch.
6192    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6193        LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
6194        LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
6195      return QualType();
6196
6197    // Exactly one GC qualifier difference is allowed: __strong is
6198    // okay if the other type has no GC qualifier but is an Objective
6199    // C object pointer (i.e. implicitly strong by default).  We fix
6200    // this by pretending that the unqualified type was actually
6201    // qualified __strong.
6202    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6203    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6204    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6205
6206    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6207      return QualType();
6208
6209    if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
6210      return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
6211    }
6212    if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
6213      return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
6214    }
6215    return QualType();
6216  }
6217
6218  // Okay, qualifiers are equal.
6219
6220  Type::TypeClass LHSClass = LHSCan->getTypeClass();
6221  Type::TypeClass RHSClass = RHSCan->getTypeClass();
6222
6223  // We want to consider the two function types to be the same for these
6224  // comparisons, just force one to the other.
6225  if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
6226  if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
6227
6228  // Same as above for arrays
6229  if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
6230    LHSClass = Type::ConstantArray;
6231  if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
6232    RHSClass = Type::ConstantArray;
6233
6234  // ObjCInterfaces are just specialized ObjCObjects.
6235  if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
6236  if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
6237
6238  // Canonicalize ExtVector -> Vector.
6239  if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
6240  if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
6241
6242  // If the canonical type classes don't match.
6243  if (LHSClass != RHSClass) {
6244    // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
6245    // a signed integer type, or an unsigned integer type.
6246    // Compatibility is based on the underlying type, not the promotion
6247    // type.
6248    if (const EnumType* ETy = LHS->getAs<EnumType>()) {
6249      QualType TINT = ETy->getDecl()->getIntegerType();
6250      if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType()))
6251        return RHS;
6252    }
6253    if (const EnumType* ETy = RHS->getAs<EnumType>()) {
6254      QualType TINT = ETy->getDecl()->getIntegerType();
6255      if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType()))
6256        return LHS;
6257    }
6258    // allow block pointer type to match an 'id' type.
6259    if (OfBlockPointer && !BlockReturnType) {
6260       if (LHS->isObjCIdType() && RHS->isBlockPointerType())
6261         return LHS;
6262      if (RHS->isObjCIdType() && LHS->isBlockPointerType())
6263        return RHS;
6264    }
6265
6266    return QualType();
6267  }
6268
6269  // The canonical type classes match.
6270  switch (LHSClass) {
6271#define TYPE(Class, Base)
6272#define ABSTRACT_TYPE(Class, Base)
6273#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
6274#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
6275#define DEPENDENT_TYPE(Class, Base) case Type::Class:
6276#include "clang/AST/TypeNodes.def"
6277    llvm_unreachable("Non-canonical and dependent types shouldn't get here");
6278
6279  case Type::LValueReference:
6280  case Type::RValueReference:
6281  case Type::MemberPointer:
6282    llvm_unreachable("C++ should never be in mergeTypes");
6283
6284  case Type::ObjCInterface:
6285  case Type::IncompleteArray:
6286  case Type::VariableArray:
6287  case Type::FunctionProto:
6288  case Type::ExtVector:
6289    llvm_unreachable("Types are eliminated above");
6290
6291  case Type::Pointer:
6292  {
6293    // Merge two pointer types, while trying to preserve typedef info
6294    QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
6295    QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
6296    if (Unqualified) {
6297      LHSPointee = LHSPointee.getUnqualifiedType();
6298      RHSPointee = RHSPointee.getUnqualifiedType();
6299    }
6300    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
6301                                     Unqualified);
6302    if (ResultType.isNull()) return QualType();
6303    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6304      return LHS;
6305    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6306      return RHS;
6307    return getPointerType(ResultType);
6308  }
6309  case Type::BlockPointer:
6310  {
6311    // Merge two block pointer types, while trying to preserve typedef info
6312    QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
6313    QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
6314    if (Unqualified) {
6315      LHSPointee = LHSPointee.getUnqualifiedType();
6316      RHSPointee = RHSPointee.getUnqualifiedType();
6317    }
6318    QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
6319                                     Unqualified);
6320    if (ResultType.isNull()) return QualType();
6321    if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
6322      return LHS;
6323    if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
6324      return RHS;
6325    return getBlockPointerType(ResultType);
6326  }
6327  case Type::Atomic:
6328  {
6329    // Merge two pointer types, while trying to preserve typedef info
6330    QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
6331    QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
6332    if (Unqualified) {
6333      LHSValue = LHSValue.getUnqualifiedType();
6334      RHSValue = RHSValue.getUnqualifiedType();
6335    }
6336    QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
6337                                     Unqualified);
6338    if (ResultType.isNull()) return QualType();
6339    if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
6340      return LHS;
6341    if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
6342      return RHS;
6343    return getAtomicType(ResultType);
6344  }
6345  case Type::ConstantArray:
6346  {
6347    const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
6348    const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
6349    if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
6350      return QualType();
6351
6352    QualType LHSElem = getAsArrayType(LHS)->getElementType();
6353    QualType RHSElem = getAsArrayType(RHS)->getElementType();
6354    if (Unqualified) {
6355      LHSElem = LHSElem.getUnqualifiedType();
6356      RHSElem = RHSElem.getUnqualifiedType();
6357    }
6358
6359    QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
6360    if (ResultType.isNull()) return QualType();
6361    if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6362      return LHS;
6363    if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6364      return RHS;
6365    if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
6366                                          ArrayType::ArraySizeModifier(), 0);
6367    if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
6368                                          ArrayType::ArraySizeModifier(), 0);
6369    const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
6370    const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
6371    if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
6372      return LHS;
6373    if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
6374      return RHS;
6375    if (LVAT) {
6376      // FIXME: This isn't correct! But tricky to implement because
6377      // the array's size has to be the size of LHS, but the type
6378      // has to be different.
6379      return LHS;
6380    }
6381    if (RVAT) {
6382      // FIXME: This isn't correct! But tricky to implement because
6383      // the array's size has to be the size of RHS, but the type
6384      // has to be different.
6385      return RHS;
6386    }
6387    if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
6388    if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
6389    return getIncompleteArrayType(ResultType,
6390                                  ArrayType::ArraySizeModifier(), 0);
6391  }
6392  case Type::FunctionNoProto:
6393    return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
6394  case Type::Record:
6395  case Type::Enum:
6396    return QualType();
6397  case Type::Builtin:
6398    // Only exactly equal builtin types are compatible, which is tested above.
6399    return QualType();
6400  case Type::Complex:
6401    // Distinct complex types are incompatible.
6402    return QualType();
6403  case Type::Vector:
6404    // FIXME: The merged type should be an ExtVector!
6405    if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
6406                             RHSCan->getAs<VectorType>()))
6407      return LHS;
6408    return QualType();
6409  case Type::ObjCObject: {
6410    // Check if the types are assignment compatible.
6411    // FIXME: This should be type compatibility, e.g. whether
6412    // "LHS x; RHS x;" at global scope is legal.
6413    const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
6414    const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
6415    if (canAssignObjCInterfaces(LHSIface, RHSIface))
6416      return LHS;
6417
6418    return QualType();
6419  }
6420  case Type::ObjCObjectPointer: {
6421    if (OfBlockPointer) {
6422      if (canAssignObjCInterfacesInBlockPointer(
6423                                          LHS->getAs<ObjCObjectPointerType>(),
6424                                          RHS->getAs<ObjCObjectPointerType>(),
6425                                          BlockReturnType))
6426        return LHS;
6427      return QualType();
6428    }
6429    if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
6430                                RHS->getAs<ObjCObjectPointerType>()))
6431      return LHS;
6432
6433    return QualType();
6434  }
6435  }
6436
6437  llvm_unreachable("Invalid Type::Class!");
6438}
6439
6440bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
6441                   const FunctionProtoType *FromFunctionType,
6442                   const FunctionProtoType *ToFunctionType) {
6443  if (FromFunctionType->hasAnyConsumedArgs() !=
6444      ToFunctionType->hasAnyConsumedArgs())
6445    return false;
6446  FunctionProtoType::ExtProtoInfo FromEPI =
6447    FromFunctionType->getExtProtoInfo();
6448  FunctionProtoType::ExtProtoInfo ToEPI =
6449    ToFunctionType->getExtProtoInfo();
6450  if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
6451    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
6452         ArgIdx != NumArgs; ++ArgIdx)  {
6453      if (FromEPI.ConsumedArguments[ArgIdx] !=
6454          ToEPI.ConsumedArguments[ArgIdx])
6455        return false;
6456    }
6457  return true;
6458}
6459
6460/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
6461/// 'RHS' attributes and returns the merged version; including for function
6462/// return types.
6463QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
6464  QualType LHSCan = getCanonicalType(LHS),
6465  RHSCan = getCanonicalType(RHS);
6466  // If two types are identical, they are compatible.
6467  if (LHSCan == RHSCan)
6468    return LHS;
6469  if (RHSCan->isFunctionType()) {
6470    if (!LHSCan->isFunctionType())
6471      return QualType();
6472    QualType OldReturnType =
6473      cast<FunctionType>(RHSCan.getTypePtr())->getResultType();
6474    QualType NewReturnType =
6475      cast<FunctionType>(LHSCan.getTypePtr())->getResultType();
6476    QualType ResReturnType =
6477      mergeObjCGCQualifiers(NewReturnType, OldReturnType);
6478    if (ResReturnType.isNull())
6479      return QualType();
6480    if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
6481      // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
6482      // In either case, use OldReturnType to build the new function type.
6483      const FunctionType *F = LHS->getAs<FunctionType>();
6484      if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
6485        FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
6486        EPI.ExtInfo = getFunctionExtInfo(LHS);
6487        QualType ResultType
6488          = getFunctionType(OldReturnType, FPT->arg_type_begin(),
6489                            FPT->getNumArgs(), EPI);
6490        return ResultType;
6491      }
6492    }
6493    return QualType();
6494  }
6495
6496  // If the qualifiers are different, the types can still be merged.
6497  Qualifiers LQuals = LHSCan.getLocalQualifiers();
6498  Qualifiers RQuals = RHSCan.getLocalQualifiers();
6499  if (LQuals != RQuals) {
6500    // If any of these qualifiers are different, we have a type mismatch.
6501    if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
6502        LQuals.getAddressSpace() != RQuals.getAddressSpace())
6503      return QualType();
6504
6505    // Exactly one GC qualifier difference is allowed: __strong is
6506    // okay if the other type has no GC qualifier but is an Objective
6507    // C object pointer (i.e. implicitly strong by default).  We fix
6508    // this by pretending that the unqualified type was actually
6509    // qualified __strong.
6510    Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
6511    Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
6512    assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
6513
6514    if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
6515      return QualType();
6516
6517    if (GC_L == Qualifiers::Strong)
6518      return LHS;
6519    if (GC_R == Qualifiers::Strong)
6520      return RHS;
6521    return QualType();
6522  }
6523
6524  if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
6525    QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6526    QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
6527    QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
6528    if (ResQT == LHSBaseQT)
6529      return LHS;
6530    if (ResQT == RHSBaseQT)
6531      return RHS;
6532  }
6533  return QualType();
6534}
6535
6536//===----------------------------------------------------------------------===//
6537//                         Integer Predicates
6538//===----------------------------------------------------------------------===//
6539
6540unsigned ASTContext::getIntWidth(QualType T) const {
6541  if (const EnumType *ET = dyn_cast<EnumType>(T))
6542    T = ET->getDecl()->getIntegerType();
6543  if (T->isBooleanType())
6544    return 1;
6545  // For builtin types, just use the standard type sizing method
6546  return (unsigned)getTypeSize(T);
6547}
6548
6549QualType ASTContext::getCorrespondingUnsignedType(QualType T) {
6550  assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
6551
6552  // Turn <4 x signed int> -> <4 x unsigned int>
6553  if (const VectorType *VTy = T->getAs<VectorType>())
6554    return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
6555                         VTy->getNumElements(), VTy->getVectorKind());
6556
6557  // For enums, we return the unsigned version of the base type.
6558  if (const EnumType *ETy = T->getAs<EnumType>())
6559    T = ETy->getDecl()->getIntegerType();
6560
6561  const BuiltinType *BTy = T->getAs<BuiltinType>();
6562  assert(BTy && "Unexpected signed integer type");
6563  switch (BTy->getKind()) {
6564  case BuiltinType::Char_S:
6565  case BuiltinType::SChar:
6566    return UnsignedCharTy;
6567  case BuiltinType::Short:
6568    return UnsignedShortTy;
6569  case BuiltinType::Int:
6570    return UnsignedIntTy;
6571  case BuiltinType::Long:
6572    return UnsignedLongTy;
6573  case BuiltinType::LongLong:
6574    return UnsignedLongLongTy;
6575  case BuiltinType::Int128:
6576    return UnsignedInt128Ty;
6577  default:
6578    llvm_unreachable("Unexpected signed integer type");
6579  }
6580}
6581
6582ASTMutationListener::~ASTMutationListener() { }
6583
6584
6585//===----------------------------------------------------------------------===//
6586//                          Builtin Type Computation
6587//===----------------------------------------------------------------------===//
6588
6589/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
6590/// pointer over the consumed characters.  This returns the resultant type.  If
6591/// AllowTypeModifiers is false then modifier like * are not parsed, just basic
6592/// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
6593/// a vector of "i*".
6594///
6595/// RequiresICE is filled in on return to indicate whether the value is required
6596/// to be an Integer Constant Expression.
6597static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
6598                                  ASTContext::GetBuiltinTypeError &Error,
6599                                  bool &RequiresICE,
6600                                  bool AllowTypeModifiers) {
6601  // Modifiers.
6602  int HowLong = 0;
6603  bool Signed = false, Unsigned = false;
6604  RequiresICE = false;
6605
6606  // Read the prefixed modifiers first.
6607  bool Done = false;
6608  while (!Done) {
6609    switch (*Str++) {
6610    default: Done = true; --Str; break;
6611    case 'I':
6612      RequiresICE = true;
6613      break;
6614    case 'S':
6615      assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
6616      assert(!Signed && "Can't use 'S' modifier multiple times!");
6617      Signed = true;
6618      break;
6619    case 'U':
6620      assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
6621      assert(!Unsigned && "Can't use 'S' modifier multiple times!");
6622      Unsigned = true;
6623      break;
6624    case 'L':
6625      assert(HowLong <= 2 && "Can't have LLLL modifier");
6626      ++HowLong;
6627      break;
6628    }
6629  }
6630
6631  QualType Type;
6632
6633  // Read the base type.
6634  switch (*Str++) {
6635  default: llvm_unreachable("Unknown builtin type letter!");
6636  case 'v':
6637    assert(HowLong == 0 && !Signed && !Unsigned &&
6638           "Bad modifiers used with 'v'!");
6639    Type = Context.VoidTy;
6640    break;
6641  case 'f':
6642    assert(HowLong == 0 && !Signed && !Unsigned &&
6643           "Bad modifiers used with 'f'!");
6644    Type = Context.FloatTy;
6645    break;
6646  case 'd':
6647    assert(HowLong < 2 && !Signed && !Unsigned &&
6648           "Bad modifiers used with 'd'!");
6649    if (HowLong)
6650      Type = Context.LongDoubleTy;
6651    else
6652      Type = Context.DoubleTy;
6653    break;
6654  case 's':
6655    assert(HowLong == 0 && "Bad modifiers used with 's'!");
6656    if (Unsigned)
6657      Type = Context.UnsignedShortTy;
6658    else
6659      Type = Context.ShortTy;
6660    break;
6661  case 'i':
6662    if (HowLong == 3)
6663      Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
6664    else if (HowLong == 2)
6665      Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
6666    else if (HowLong == 1)
6667      Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
6668    else
6669      Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
6670    break;
6671  case 'c':
6672    assert(HowLong == 0 && "Bad modifiers used with 'c'!");
6673    if (Signed)
6674      Type = Context.SignedCharTy;
6675    else if (Unsigned)
6676      Type = Context.UnsignedCharTy;
6677    else
6678      Type = Context.CharTy;
6679    break;
6680  case 'b': // boolean
6681    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
6682    Type = Context.BoolTy;
6683    break;
6684  case 'z':  // size_t.
6685    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
6686    Type = Context.getSizeType();
6687    break;
6688  case 'F':
6689    Type = Context.getCFConstantStringType();
6690    break;
6691  case 'G':
6692    Type = Context.getObjCIdType();
6693    break;
6694  case 'H':
6695    Type = Context.getObjCSelType();
6696    break;
6697  case 'a':
6698    Type = Context.getBuiltinVaListType();
6699    assert(!Type.isNull() && "builtin va list type not initialized!");
6700    break;
6701  case 'A':
6702    // This is a "reference" to a va_list; however, what exactly
6703    // this means depends on how va_list is defined. There are two
6704    // different kinds of va_list: ones passed by value, and ones
6705    // passed by reference.  An example of a by-value va_list is
6706    // x86, where va_list is a char*. An example of by-ref va_list
6707    // is x86-64, where va_list is a __va_list_tag[1]. For x86,
6708    // we want this argument to be a char*&; for x86-64, we want
6709    // it to be a __va_list_tag*.
6710    Type = Context.getBuiltinVaListType();
6711    assert(!Type.isNull() && "builtin va list type not initialized!");
6712    if (Type->isArrayType())
6713      Type = Context.getArrayDecayedType(Type);
6714    else
6715      Type = Context.getLValueReferenceType(Type);
6716    break;
6717  case 'V': {
6718    char *End;
6719    unsigned NumElements = strtoul(Str, &End, 10);
6720    assert(End != Str && "Missing vector size");
6721    Str = End;
6722
6723    QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
6724                                             RequiresICE, false);
6725    assert(!RequiresICE && "Can't require vector ICE");
6726
6727    // TODO: No way to make AltiVec vectors in builtins yet.
6728    Type = Context.getVectorType(ElementType, NumElements,
6729                                 VectorType::GenericVector);
6730    break;
6731  }
6732  case 'E': {
6733    char *End;
6734
6735    unsigned NumElements = strtoul(Str, &End, 10);
6736    assert(End != Str && "Missing vector size");
6737
6738    Str = End;
6739
6740    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6741                                             false);
6742    Type = Context.getExtVectorType(ElementType, NumElements);
6743    break;
6744  }
6745  case 'X': {
6746    QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
6747                                             false);
6748    assert(!RequiresICE && "Can't require complex ICE");
6749    Type = Context.getComplexType(ElementType);
6750    break;
6751  }
6752  case 'Y' : {
6753    Type = Context.getPointerDiffType();
6754    break;
6755  }
6756  case 'P':
6757    Type = Context.getFILEType();
6758    if (Type.isNull()) {
6759      Error = ASTContext::GE_Missing_stdio;
6760      return QualType();
6761    }
6762    break;
6763  case 'J':
6764    if (Signed)
6765      Type = Context.getsigjmp_bufType();
6766    else
6767      Type = Context.getjmp_bufType();
6768
6769    if (Type.isNull()) {
6770      Error = ASTContext::GE_Missing_setjmp;
6771      return QualType();
6772    }
6773    break;
6774  case 'K':
6775    assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
6776    Type = Context.getucontext_tType();
6777
6778    if (Type.isNull()) {
6779      Error = ASTContext::GE_Missing_ucontext;
6780      return QualType();
6781    }
6782    break;
6783  }
6784
6785  // If there are modifiers and if we're allowed to parse them, go for it.
6786  Done = !AllowTypeModifiers;
6787  while (!Done) {
6788    switch (char c = *Str++) {
6789    default: Done = true; --Str; break;
6790    case '*':
6791    case '&': {
6792      // Both pointers and references can have their pointee types
6793      // qualified with an address space.
6794      char *End;
6795      unsigned AddrSpace = strtoul(Str, &End, 10);
6796      if (End != Str && AddrSpace != 0) {
6797        Type = Context.getAddrSpaceQualType(Type, AddrSpace);
6798        Str = End;
6799      }
6800      if (c == '*')
6801        Type = Context.getPointerType(Type);
6802      else
6803        Type = Context.getLValueReferenceType(Type);
6804      break;
6805    }
6806    // FIXME: There's no way to have a built-in with an rvalue ref arg.
6807    case 'C':
6808      Type = Type.withConst();
6809      break;
6810    case 'D':
6811      Type = Context.getVolatileType(Type);
6812      break;
6813    case 'R':
6814      Type = Type.withRestrict();
6815      break;
6816    }
6817  }
6818
6819  assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
6820         "Integer constant 'I' type must be an integer");
6821
6822  return Type;
6823}
6824
6825/// GetBuiltinType - Return the type for the specified builtin.
6826QualType ASTContext::GetBuiltinType(unsigned Id,
6827                                    GetBuiltinTypeError &Error,
6828                                    unsigned *IntegerConstantArgs) const {
6829  const char *TypeStr = BuiltinInfo.GetTypeString(Id);
6830
6831  SmallVector<QualType, 8> ArgTypes;
6832
6833  bool RequiresICE = false;
6834  Error = GE_None;
6835  QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
6836                                       RequiresICE, true);
6837  if (Error != GE_None)
6838    return QualType();
6839
6840  assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
6841
6842  while (TypeStr[0] && TypeStr[0] != '.') {
6843    QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
6844    if (Error != GE_None)
6845      return QualType();
6846
6847    // If this argument is required to be an IntegerConstantExpression and the
6848    // caller cares, fill in the bitmask we return.
6849    if (RequiresICE && IntegerConstantArgs)
6850      *IntegerConstantArgs |= 1 << ArgTypes.size();
6851
6852    // Do array -> pointer decay.  The builtin should use the decayed type.
6853    if (Ty->isArrayType())
6854      Ty = getArrayDecayedType(Ty);
6855
6856    ArgTypes.push_back(Ty);
6857  }
6858
6859  assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
6860         "'.' should only occur at end of builtin type list!");
6861
6862  FunctionType::ExtInfo EI;
6863  if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
6864
6865  bool Variadic = (TypeStr[0] == '.');
6866
6867  // We really shouldn't be making a no-proto type here, especially in C++.
6868  if (ArgTypes.empty() && Variadic)
6869    return getFunctionNoProtoType(ResType, EI);
6870
6871  FunctionProtoType::ExtProtoInfo EPI;
6872  EPI.ExtInfo = EI;
6873  EPI.Variadic = Variadic;
6874
6875  return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI);
6876}
6877
6878GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) {
6879  GVALinkage External = GVA_StrongExternal;
6880
6881  Linkage L = FD->getLinkage();
6882  switch (L) {
6883  case NoLinkage:
6884  case InternalLinkage:
6885  case UniqueExternalLinkage:
6886    return GVA_Internal;
6887
6888  case ExternalLinkage:
6889    switch (FD->getTemplateSpecializationKind()) {
6890    case TSK_Undeclared:
6891    case TSK_ExplicitSpecialization:
6892      External = GVA_StrongExternal;
6893      break;
6894
6895    case TSK_ExplicitInstantiationDefinition:
6896      return GVA_ExplicitTemplateInstantiation;
6897
6898    case TSK_ExplicitInstantiationDeclaration:
6899    case TSK_ImplicitInstantiation:
6900      External = GVA_TemplateInstantiation;
6901      break;
6902    }
6903  }
6904
6905  if (!FD->isInlined())
6906    return External;
6907
6908  if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
6909    // GNU or C99 inline semantics. Determine whether this symbol should be
6910    // externally visible.
6911    if (FD->isInlineDefinitionExternallyVisible())
6912      return External;
6913
6914    // C99 inline semantics, where the symbol is not externally visible.
6915    return GVA_C99Inline;
6916  }
6917
6918  // C++0x [temp.explicit]p9:
6919  //   [ Note: The intent is that an inline function that is the subject of
6920  //   an explicit instantiation declaration will still be implicitly
6921  //   instantiated when used so that the body can be considered for
6922  //   inlining, but that no out-of-line copy of the inline function would be
6923  //   generated in the translation unit. -- end note ]
6924  if (FD->getTemplateSpecializationKind()
6925                                       == TSK_ExplicitInstantiationDeclaration)
6926    return GVA_C99Inline;
6927
6928  return GVA_CXXInline;
6929}
6930
6931GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
6932  // If this is a static data member, compute the kind of template
6933  // specialization. Otherwise, this variable is not part of a
6934  // template.
6935  TemplateSpecializationKind TSK = TSK_Undeclared;
6936  if (VD->isStaticDataMember())
6937    TSK = VD->getTemplateSpecializationKind();
6938
6939  Linkage L = VD->getLinkage();
6940  if (L == ExternalLinkage && getLangOpts().CPlusPlus &&
6941      VD->getType()->getLinkage() == UniqueExternalLinkage)
6942    L = UniqueExternalLinkage;
6943
6944  switch (L) {
6945  case NoLinkage:
6946  case InternalLinkage:
6947  case UniqueExternalLinkage:
6948    return GVA_Internal;
6949
6950  case ExternalLinkage:
6951    switch (TSK) {
6952    case TSK_Undeclared:
6953    case TSK_ExplicitSpecialization:
6954      return GVA_StrongExternal;
6955
6956    case TSK_ExplicitInstantiationDeclaration:
6957      llvm_unreachable("Variable should not be instantiated");
6958      // Fall through to treat this like any other instantiation.
6959
6960    case TSK_ExplicitInstantiationDefinition:
6961      return GVA_ExplicitTemplateInstantiation;
6962
6963    case TSK_ImplicitInstantiation:
6964      return GVA_TemplateInstantiation;
6965    }
6966  }
6967
6968  llvm_unreachable("Invalid Linkage!");
6969}
6970
6971bool ASTContext::DeclMustBeEmitted(const Decl *D) {
6972  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
6973    if (!VD->isFileVarDecl())
6974      return false;
6975  } else if (!isa<FunctionDecl>(D))
6976    return false;
6977
6978  // Weak references don't produce any output by themselves.
6979  if (D->hasAttr<WeakRefAttr>())
6980    return false;
6981
6982  // Aliases and used decls are required.
6983  if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
6984    return true;
6985
6986  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
6987    // Forward declarations aren't required.
6988    if (!FD->doesThisDeclarationHaveABody())
6989      return FD->doesDeclarationForceExternallyVisibleDefinition();
6990
6991    // Constructors and destructors are required.
6992    if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
6993      return true;
6994
6995    // The key function for a class is required.
6996    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6997      const CXXRecordDecl *RD = MD->getParent();
6998      if (MD->isOutOfLine() && RD->isDynamicClass()) {
6999        const CXXMethodDecl *KeyFunc = getKeyFunction(RD);
7000        if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
7001          return true;
7002      }
7003    }
7004
7005    GVALinkage Linkage = GetGVALinkageForFunction(FD);
7006
7007    // static, static inline, always_inline, and extern inline functions can
7008    // always be deferred.  Normal inline functions can be deferred in C99/C++.
7009    // Implicit template instantiations can also be deferred in C++.
7010    if (Linkage == GVA_Internal  || Linkage == GVA_C99Inline ||
7011        Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
7012      return false;
7013    return true;
7014  }
7015
7016  const VarDecl *VD = cast<VarDecl>(D);
7017  assert(VD->isFileVarDecl() && "Expected file scoped var");
7018
7019  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly)
7020    return false;
7021
7022  // Structs that have non-trivial constructors or destructors are required.
7023
7024  // FIXME: Handle references.
7025  // FIXME: Be more selective about which constructors we care about.
7026  if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
7027    if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
7028      if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() &&
7029                                   RD->hasTrivialCopyConstructor() &&
7030                                   RD->hasTrivialMoveConstructor() &&
7031                                   RD->hasTrivialDestructor()))
7032        return true;
7033    }
7034  }
7035
7036  GVALinkage L = GetGVALinkageForVariable(VD);
7037  if (L == GVA_Internal || L == GVA_TemplateInstantiation) {
7038    if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this)))
7039      return false;
7040  }
7041
7042  return true;
7043}
7044
7045CallingConv ASTContext::getDefaultMethodCallConv() {
7046  // Pass through to the C++ ABI object
7047  return ABI->getDefaultMethodCallConv();
7048}
7049
7050bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
7051  // Pass through to the C++ ABI object
7052  return ABI->isNearlyEmpty(RD);
7053}
7054
7055MangleContext *ASTContext::createMangleContext() {
7056  switch (Target->getCXXABI()) {
7057  case CXXABI_ARM:
7058  case CXXABI_Itanium:
7059    return createItaniumMangleContext(*this, getDiagnostics());
7060  case CXXABI_Microsoft:
7061    return createMicrosoftMangleContext(*this, getDiagnostics());
7062  }
7063  llvm_unreachable("Unsupported ABI");
7064}
7065
7066CXXABI::~CXXABI() {}
7067
7068size_t ASTContext::getSideTableAllocatedMemory() const {
7069  return ASTRecordLayouts.getMemorySize()
7070    + llvm::capacity_in_bytes(ObjCLayouts)
7071    + llvm::capacity_in_bytes(KeyFunctions)
7072    + llvm::capacity_in_bytes(ObjCImpls)
7073    + llvm::capacity_in_bytes(BlockVarCopyInits)
7074    + llvm::capacity_in_bytes(DeclAttrs)
7075    + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember)
7076    + llvm::capacity_in_bytes(InstantiatedFromUsingDecl)
7077    + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl)
7078    + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl)
7079    + llvm::capacity_in_bytes(OverriddenMethods)
7080    + llvm::capacity_in_bytes(Types)
7081    + llvm::capacity_in_bytes(VariableArrayTypes)
7082    + llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
7083}
7084
7085unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) {
7086  CXXRecordDecl *Lambda = CallOperator->getParent();
7087  return LambdaMangleContexts[Lambda->getDeclContext()]
7088           .getManglingNumber(CallOperator);
7089}
7090
7091
7092void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
7093  ParamIndices[D] = index;
7094}
7095
7096unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
7097  ParameterIndexTable::const_iterator I = ParamIndices.find(D);
7098  assert(I != ParamIndices.end() &&
7099         "ParmIndices lacks entry set by ParmVarDecl");
7100  return I->second;
7101}
7102