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