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