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