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