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