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