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