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