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