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