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