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