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