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