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