1 //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
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 //  This file implements C++ template instantiation for declarations.
10 //
11 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/DependentDiagnostic.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/PrettyDeclStackTrace.h"
25 #include "clang/Sema/Template.h"
26 
27 using namespace clang;
28 
29 static bool isDeclWithinFunction(const Decl *D) {
30   const DeclContext *DC = D->getDeclContext();
31   if (DC->isFunctionOrMethod())
32     return true;
33 
34   if (DC->isRecord())
35     return cast<CXXRecordDecl>(DC)->isLocalClass();
36 
37   return false;
38 }
39 
40 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
41                                               DeclaratorDecl *NewDecl) {
42   if (!OldDecl->getQualifierLoc())
43     return false;
44 
45   NestedNameSpecifierLoc NewQualifierLoc
46     = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
47                                           TemplateArgs);
48 
49   if (!NewQualifierLoc)
50     return true;
51 
52   NewDecl->setQualifierInfo(NewQualifierLoc);
53   return false;
54 }
55 
56 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
57                                               TagDecl *NewDecl) {
58   if (!OldDecl->getQualifierLoc())
59     return false;
60 
61   NestedNameSpecifierLoc NewQualifierLoc
62   = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
63                                         TemplateArgs);
64 
65   if (!NewQualifierLoc)
66     return true;
67 
68   NewDecl->setQualifierInfo(NewQualifierLoc);
69   return false;
70 }
71 
72 // Include attribute instantiation code.
73 #include "clang/Sema/AttrTemplateInstantiate.inc"
74 
75 static void instantiateDependentAlignedAttr(
76     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
77     const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
78   if (Aligned->isAlignmentExpr()) {
79     // The alignment expression is a constant expression.
80     EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
81     ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
82     if (!Result.isInvalid())
83       S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
84                        Aligned->getSpellingListIndex(), IsPackExpansion);
85   } else {
86     TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
87                                          TemplateArgs, Aligned->getLocation(),
88                                          DeclarationName());
89     if (Result)
90       S.AddAlignedAttr(Aligned->getLocation(), New, Result,
91                        Aligned->getSpellingListIndex(), IsPackExpansion);
92   }
93 }
94 
95 static void instantiateDependentAlignedAttr(
96     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
97     const AlignedAttr *Aligned, Decl *New) {
98   if (!Aligned->isPackExpansion()) {
99     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
100     return;
101   }
102 
103   SmallVector<UnexpandedParameterPack, 2> Unexpanded;
104   if (Aligned->isAlignmentExpr())
105     S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
106                                       Unexpanded);
107   else
108     S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
109                                       Unexpanded);
110   assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
111 
112   // Determine whether we can expand this attribute pack yet.
113   bool Expand = true, RetainExpansion = false;
114   Optional<unsigned> NumExpansions;
115   // FIXME: Use the actual location of the ellipsis.
116   SourceLocation EllipsisLoc = Aligned->getLocation();
117   if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
118                                         Unexpanded, TemplateArgs, Expand,
119                                         RetainExpansion, NumExpansions))
120     return;
121 
122   if (!Expand) {
123     Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
124     instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
125   } else {
126     for (unsigned I = 0; I != *NumExpansions; ++I) {
127       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
128       instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
129     }
130   }
131 }
132 
133 static void instantiateDependentEnableIfAttr(
134     Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
135     const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
136   Expr *Cond = 0;
137   {
138     EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
139     ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
140     if (Result.isInvalid())
141       return;
142     Cond = Result.takeAs<Expr>();
143   }
144   if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
145     ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
146     if (Converted.isInvalid())
147       return;
148     Cond = Converted.take();
149   }
150 
151   SmallVector<PartialDiagnosticAt, 8> Diags;
152   if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
153       !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
154                                                 Diags)) {
155     S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
156     for (int I = 0, N = Diags.size(); I != N; ++I)
157       S.Diag(Diags[I].first, Diags[I].second);
158     return;
159   }
160 
161   EnableIfAttr *EIA = new (S.getASTContext())
162                         EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
163                                      A->getMessage(),
164                                      A->getSpellingListIndex());
165   New->addAttr(EIA);
166 }
167 
168 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
169                             const Decl *Tmpl, Decl *New,
170                             LateInstantiatedAttrVec *LateAttrs,
171                             LocalInstantiationScope *OuterMostScope) {
172   for (const auto *TmplAttr : Tmpl->attrs()) {
173     // FIXME: This should be generalized to more than just the AlignedAttr.
174     const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
175     if (Aligned && Aligned->isAlignmentDependent()) {
176       instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
177       continue;
178     }
179 
180     const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
181     if (EnableIf && EnableIf->getCond()->isValueDependent()) {
182       instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
183                                        New);
184       continue;
185     }
186 
187     assert(!TmplAttr->isPackExpansion());
188     if (TmplAttr->isLateParsed() && LateAttrs) {
189       // Late parsed attributes must be instantiated and attached after the
190       // enclosing class has been instantiated.  See Sema::InstantiateClass.
191       LocalInstantiationScope *Saved = 0;
192       if (CurrentInstantiationScope)
193         Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
194       LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
195     } else {
196       // Allow 'this' within late-parsed attributes.
197       NamedDecl *ND = dyn_cast<NamedDecl>(New);
198       CXXRecordDecl *ThisContext =
199           dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
200       CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
201                                  ND && ND->isCXXInstanceMember());
202 
203       Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
204                                                          *this, TemplateArgs);
205       if (NewAttr)
206         New->addAttr(NewAttr);
207     }
208   }
209 }
210 
211 Decl *
212 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
213   llvm_unreachable("Translation units cannot be instantiated");
214 }
215 
216 Decl *
217 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
218   LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
219                                       D->getIdentifier());
220   Owner->addDecl(Inst);
221   return Inst;
222 }
223 
224 Decl *
225 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
226   llvm_unreachable("Namespaces cannot be instantiated");
227 }
228 
229 Decl *
230 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
231   NamespaceAliasDecl *Inst
232     = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
233                                  D->getNamespaceLoc(),
234                                  D->getAliasLoc(),
235                                  D->getIdentifier(),
236                                  D->getQualifierLoc(),
237                                  D->getTargetNameLoc(),
238                                  D->getNamespace());
239   Owner->addDecl(Inst);
240   return Inst;
241 }
242 
243 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
244                                                            bool IsTypeAlias) {
245   bool Invalid = false;
246   TypeSourceInfo *DI = D->getTypeSourceInfo();
247   if (DI->getType()->isInstantiationDependentType() ||
248       DI->getType()->isVariablyModifiedType()) {
249     DI = SemaRef.SubstType(DI, TemplateArgs,
250                            D->getLocation(), D->getDeclName());
251     if (!DI) {
252       Invalid = true;
253       DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
254     }
255   } else {
256     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
257   }
258 
259   // HACK: g++ has a bug where it gets the value kind of ?: wrong.
260   // libstdc++ relies upon this bug in its implementation of common_type.
261   // If we happen to be processing that implementation, fake up the g++ ?:
262   // semantics. See LWG issue 2141 for more information on the bug.
263   const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
264   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
265   if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
266       DT->isReferenceType() &&
267       RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
268       RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
269       D->getIdentifier() && D->getIdentifier()->isStr("type") &&
270       SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
271     // Fold it to the (non-reference) type which g++ would have produced.
272     DI = SemaRef.Context.getTrivialTypeSourceInfo(
273       DI->getType().getNonReferenceType());
274 
275   // Create the new typedef
276   TypedefNameDecl *Typedef;
277   if (IsTypeAlias)
278     Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
279                                     D->getLocation(), D->getIdentifier(), DI);
280   else
281     Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
282                                   D->getLocation(), D->getIdentifier(), DI);
283   if (Invalid)
284     Typedef->setInvalidDecl();
285 
286   // If the old typedef was the name for linkage purposes of an anonymous
287   // tag decl, re-establish that relationship for the new typedef.
288   if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
289     TagDecl *oldTag = oldTagType->getDecl();
290     if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
291       TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
292       assert(!newTag->hasNameForLinkage());
293       newTag->setTypedefNameForAnonDecl(Typedef);
294     }
295   }
296 
297   if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
298     NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
299                                                        TemplateArgs);
300     if (!InstPrev)
301       return 0;
302 
303     TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
304 
305     // If the typedef types are not identical, reject them.
306     SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
307 
308     Typedef->setPreviousDecl(InstPrevTypedef);
309   }
310 
311   SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
312 
313   Typedef->setAccess(D->getAccess());
314 
315   return Typedef;
316 }
317 
318 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
319   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
320   Owner->addDecl(Typedef);
321   return Typedef;
322 }
323 
324 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
325   Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
326   Owner->addDecl(Typedef);
327   return Typedef;
328 }
329 
330 Decl *
331 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
332   // Create a local instantiation scope for this type alias template, which
333   // will contain the instantiations of the template parameters.
334   LocalInstantiationScope Scope(SemaRef);
335 
336   TemplateParameterList *TempParams = D->getTemplateParameters();
337   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
338   if (!InstParams)
339     return 0;
340 
341   TypeAliasDecl *Pattern = D->getTemplatedDecl();
342 
343   TypeAliasTemplateDecl *PrevAliasTemplate = 0;
344   if (Pattern->getPreviousDecl()) {
345     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
346     if (!Found.empty()) {
347       PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
348     }
349   }
350 
351   TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
352     InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
353   if (!AliasInst)
354     return 0;
355 
356   TypeAliasTemplateDecl *Inst
357     = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
358                                     D->getDeclName(), InstParams, AliasInst);
359   if (PrevAliasTemplate)
360     Inst->setPreviousDecl(PrevAliasTemplate);
361 
362   Inst->setAccess(D->getAccess());
363 
364   if (!PrevAliasTemplate)
365     Inst->setInstantiatedFromMemberTemplate(D);
366 
367   Owner->addDecl(Inst);
368 
369   return Inst;
370 }
371 
372 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
373   return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
374 }
375 
376 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
377                                              bool InstantiatingVarTemplate) {
378 
379   // If this is the variable for an anonymous struct or union,
380   // instantiate the anonymous struct/union type first.
381   if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
382     if (RecordTy->getDecl()->isAnonymousStructOrUnion())
383       if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
384         return 0;
385 
386   // Do substitution on the type of the declaration
387   TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
388                                          TemplateArgs,
389                                          D->getTypeSpecStartLoc(),
390                                          D->getDeclName());
391   if (!DI)
392     return 0;
393 
394   if (DI->getType()->isFunctionType()) {
395     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
396       << D->isStaticDataMember() << DI->getType();
397     return 0;
398   }
399 
400   DeclContext *DC = Owner;
401   if (D->isLocalExternDecl())
402     SemaRef.adjustContextForLocalExternDecl(DC);
403 
404   // Build the instantiated declaration.
405   VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
406                                  D->getLocation(), D->getIdentifier(),
407                                  DI->getType(), DI, D->getStorageClass());
408 
409   // In ARC, infer 'retaining' for variables of retainable type.
410   if (SemaRef.getLangOpts().ObjCAutoRefCount &&
411       SemaRef.inferObjCARCLifetime(Var))
412     Var->setInvalidDecl();
413 
414   // Substitute the nested name specifier, if any.
415   if (SubstQualifier(D, Var))
416     return 0;
417 
418   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
419                                      StartingScope, InstantiatingVarTemplate);
420   return Var;
421 }
422 
423 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
424   AccessSpecDecl* AD
425     = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
426                              D->getAccessSpecifierLoc(), D->getColonLoc());
427   Owner->addHiddenDecl(AD);
428   return AD;
429 }
430 
431 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
432   bool Invalid = false;
433   TypeSourceInfo *DI = D->getTypeSourceInfo();
434   if (DI->getType()->isInstantiationDependentType() ||
435       DI->getType()->isVariablyModifiedType())  {
436     DI = SemaRef.SubstType(DI, TemplateArgs,
437                            D->getLocation(), D->getDeclName());
438     if (!DI) {
439       DI = D->getTypeSourceInfo();
440       Invalid = true;
441     } else if (DI->getType()->isFunctionType()) {
442       // C++ [temp.arg.type]p3:
443       //   If a declaration acquires a function type through a type
444       //   dependent on a template-parameter and this causes a
445       //   declaration that does not use the syntactic form of a
446       //   function declarator to have function type, the program is
447       //   ill-formed.
448       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
449         << DI->getType();
450       Invalid = true;
451     }
452   } else {
453     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
454   }
455 
456   Expr *BitWidth = D->getBitWidth();
457   if (Invalid)
458     BitWidth = 0;
459   else if (BitWidth) {
460     // The bit-width expression is a constant expression.
461     EnterExpressionEvaluationContext Unevaluated(SemaRef,
462                                                  Sema::ConstantEvaluated);
463 
464     ExprResult InstantiatedBitWidth
465       = SemaRef.SubstExpr(BitWidth, TemplateArgs);
466     if (InstantiatedBitWidth.isInvalid()) {
467       Invalid = true;
468       BitWidth = 0;
469     } else
470       BitWidth = InstantiatedBitWidth.takeAs<Expr>();
471   }
472 
473   FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
474                                             DI->getType(), DI,
475                                             cast<RecordDecl>(Owner),
476                                             D->getLocation(),
477                                             D->isMutable(),
478                                             BitWidth,
479                                             D->getInClassInitStyle(),
480                                             D->getInnerLocStart(),
481                                             D->getAccess(),
482                                             0);
483   if (!Field) {
484     cast<Decl>(Owner)->setInvalidDecl();
485     return 0;
486   }
487 
488   SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
489 
490   if (Field->hasAttrs())
491     SemaRef.CheckAlignasUnderalignment(Field);
492 
493   if (Invalid)
494     Field->setInvalidDecl();
495 
496   if (!Field->getDeclName()) {
497     // Keep track of where this decl came from.
498     SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
499   }
500   if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
501     if (Parent->isAnonymousStructOrUnion() &&
502         Parent->getRedeclContext()->isFunctionOrMethod())
503       SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
504   }
505 
506   Field->setImplicit(D->isImplicit());
507   Field->setAccess(D->getAccess());
508   Owner->addDecl(Field);
509 
510   return Field;
511 }
512 
513 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
514   bool Invalid = false;
515   TypeSourceInfo *DI = D->getTypeSourceInfo();
516 
517   if (DI->getType()->isVariablyModifiedType()) {
518     SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
519       << D;
520     Invalid = true;
521   } else if (DI->getType()->isInstantiationDependentType())  {
522     DI = SemaRef.SubstType(DI, TemplateArgs,
523                            D->getLocation(), D->getDeclName());
524     if (!DI) {
525       DI = D->getTypeSourceInfo();
526       Invalid = true;
527     } else if (DI->getType()->isFunctionType()) {
528       // C++ [temp.arg.type]p3:
529       //   If a declaration acquires a function type through a type
530       //   dependent on a template-parameter and this causes a
531       //   declaration that does not use the syntactic form of a
532       //   function declarator to have function type, the program is
533       //   ill-formed.
534       SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
535       << DI->getType();
536       Invalid = true;
537     }
538   } else {
539     SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
540   }
541 
542   MSPropertyDecl *Property = MSPropertyDecl::Create(
543       SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
544       DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
545 
546   SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
547                            StartingScope);
548 
549   if (Invalid)
550     Property->setInvalidDecl();
551 
552   Property->setAccess(D->getAccess());
553   Owner->addDecl(Property);
554 
555   return Property;
556 }
557 
558 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
559   NamedDecl **NamedChain =
560     new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
561 
562   int i = 0;
563   for (auto *PI : D->chain()) {
564     NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
565                                               TemplateArgs);
566     if (!Next)
567       return 0;
568 
569     NamedChain[i++] = Next;
570   }
571 
572   QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
573   IndirectFieldDecl* IndirectField
574     = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
575                                 D->getIdentifier(), T,
576                                 NamedChain, D->getChainingSize());
577 
578 
579   IndirectField->setImplicit(D->isImplicit());
580   IndirectField->setAccess(D->getAccess());
581   Owner->addDecl(IndirectField);
582   return IndirectField;
583 }
584 
585 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
586   // Handle friend type expressions by simply substituting template
587   // parameters into the pattern type and checking the result.
588   if (TypeSourceInfo *Ty = D->getFriendType()) {
589     TypeSourceInfo *InstTy;
590     // If this is an unsupported friend, don't bother substituting template
591     // arguments into it. The actual type referred to won't be used by any
592     // parts of Clang, and may not be valid for instantiating. Just use the
593     // same info for the instantiated friend.
594     if (D->isUnsupportedFriend()) {
595       InstTy = Ty;
596     } else {
597       InstTy = SemaRef.SubstType(Ty, TemplateArgs,
598                                  D->getLocation(), DeclarationName());
599     }
600     if (!InstTy)
601       return 0;
602 
603     FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
604                                                  D->getFriendLoc(), InstTy);
605     if (!FD)
606       return 0;
607 
608     FD->setAccess(AS_public);
609     FD->setUnsupportedFriend(D->isUnsupportedFriend());
610     Owner->addDecl(FD);
611     return FD;
612   }
613 
614   NamedDecl *ND = D->getFriendDecl();
615   assert(ND && "friend decl must be a decl or a type!");
616 
617   // All of the Visit implementations for the various potential friend
618   // declarations have to be carefully written to work for friend
619   // objects, with the most important detail being that the target
620   // decl should almost certainly not be placed in Owner.
621   Decl *NewND = Visit(ND);
622   if (!NewND) return 0;
623 
624   FriendDecl *FD =
625     FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
626                        cast<NamedDecl>(NewND), D->getFriendLoc());
627   FD->setAccess(AS_public);
628   FD->setUnsupportedFriend(D->isUnsupportedFriend());
629   Owner->addDecl(FD);
630   return FD;
631 }
632 
633 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
634   Expr *AssertExpr = D->getAssertExpr();
635 
636   // The expression in a static assertion is a constant expression.
637   EnterExpressionEvaluationContext Unevaluated(SemaRef,
638                                                Sema::ConstantEvaluated);
639 
640   ExprResult InstantiatedAssertExpr
641     = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
642   if (InstantiatedAssertExpr.isInvalid())
643     return 0;
644 
645   return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
646                                               InstantiatedAssertExpr.get(),
647                                               D->getMessage(),
648                                               D->getRParenLoc(),
649                                               D->isFailed());
650 }
651 
652 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
653   EnumDecl *PrevDecl = 0;
654   if (D->getPreviousDecl()) {
655     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
656                                                    D->getPreviousDecl(),
657                                                    TemplateArgs);
658     if (!Prev) return 0;
659     PrevDecl = cast<EnumDecl>(Prev);
660   }
661 
662   EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
663                                     D->getLocation(), D->getIdentifier(),
664                                     PrevDecl, D->isScoped(),
665                                     D->isScopedUsingClassTag(), D->isFixed());
666   if (D->isFixed()) {
667     if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
668       // If we have type source information for the underlying type, it means it
669       // has been explicitly set by the user. Perform substitution on it before
670       // moving on.
671       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
672       TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
673                                                 DeclarationName());
674       if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
675         Enum->setIntegerType(SemaRef.Context.IntTy);
676       else
677         Enum->setIntegerTypeSourceInfo(NewTI);
678     } else {
679       assert(!D->getIntegerType()->isDependentType()
680              && "Dependent type without type source info");
681       Enum->setIntegerType(D->getIntegerType());
682     }
683   }
684 
685   SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
686 
687   Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
688   Enum->setAccess(D->getAccess());
689   // Forward the mangling number from the template to the instantiated decl.
690   SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
691   if (SubstQualifier(D, Enum)) return 0;
692   Owner->addDecl(Enum);
693 
694   EnumDecl *Def = D->getDefinition();
695   if (Def && Def != D) {
696     // If this is an out-of-line definition of an enum member template, check
697     // that the underlying types match in the instantiation of both
698     // declarations.
699     if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
700       SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
701       QualType DefnUnderlying =
702         SemaRef.SubstType(TI->getType(), TemplateArgs,
703                           UnderlyingLoc, DeclarationName());
704       SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
705                                      DefnUnderlying, Enum);
706     }
707   }
708 
709   // C++11 [temp.inst]p1: The implicit instantiation of a class template
710   // specialization causes the implicit instantiation of the declarations, but
711   // not the definitions of scoped member enumerations.
712   //
713   // DR1484 clarifies that enumeration definitions inside of a template
714   // declaration aren't considered entities that can be separately instantiated
715   // from the rest of the entity they are declared inside of.
716   if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
717     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
718     InstantiateEnumDefinition(Enum, Def);
719   }
720 
721   return Enum;
722 }
723 
724 void TemplateDeclInstantiator::InstantiateEnumDefinition(
725     EnumDecl *Enum, EnumDecl *Pattern) {
726   Enum->startDefinition();
727 
728   // Update the location to refer to the definition.
729   Enum->setLocation(Pattern->getLocation());
730 
731   SmallVector<Decl*, 4> Enumerators;
732 
733   EnumConstantDecl *LastEnumConst = 0;
734   for (auto *EC : Pattern->enumerators()) {
735     // The specified value for the enumerator.
736     ExprResult Value = SemaRef.Owned((Expr *)0);
737     if (Expr *UninstValue = EC->getInitExpr()) {
738       // The enumerator's value expression is a constant expression.
739       EnterExpressionEvaluationContext Unevaluated(SemaRef,
740                                                    Sema::ConstantEvaluated);
741 
742       Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
743     }
744 
745     // Drop the initial value and continue.
746     bool isInvalid = false;
747     if (Value.isInvalid()) {
748       Value = SemaRef.Owned((Expr *)0);
749       isInvalid = true;
750     }
751 
752     EnumConstantDecl *EnumConst
753       = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
754                                   EC->getLocation(), EC->getIdentifier(),
755                                   Value.get());
756 
757     if (isInvalid) {
758       if (EnumConst)
759         EnumConst->setInvalidDecl();
760       Enum->setInvalidDecl();
761     }
762 
763     if (EnumConst) {
764       SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
765 
766       EnumConst->setAccess(Enum->getAccess());
767       Enum->addDecl(EnumConst);
768       Enumerators.push_back(EnumConst);
769       LastEnumConst = EnumConst;
770 
771       if (Pattern->getDeclContext()->isFunctionOrMethod() &&
772           !Enum->isScoped()) {
773         // If the enumeration is within a function or method, record the enum
774         // constant as a local.
775         SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
776       }
777     }
778   }
779 
780   // FIXME: Fixup LBraceLoc
781   SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
782                         Enum->getRBraceLoc(), Enum,
783                         Enumerators,
784                         0, 0);
785 }
786 
787 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
788   llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
789 }
790 
791 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
792   bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
793 
794   // Create a local instantiation scope for this class template, which
795   // will contain the instantiations of the template parameters.
796   LocalInstantiationScope Scope(SemaRef);
797   TemplateParameterList *TempParams = D->getTemplateParameters();
798   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
799   if (!InstParams)
800     return NULL;
801 
802   CXXRecordDecl *Pattern = D->getTemplatedDecl();
803 
804   // Instantiate the qualifier.  We have to do this first in case
805   // we're a friend declaration, because if we are then we need to put
806   // the new declaration in the appropriate context.
807   NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
808   if (QualifierLoc) {
809     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
810                                                        TemplateArgs);
811     if (!QualifierLoc)
812       return 0;
813   }
814 
815   CXXRecordDecl *PrevDecl = 0;
816   ClassTemplateDecl *PrevClassTemplate = 0;
817 
818   if (!isFriend && Pattern->getPreviousDecl()) {
819     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
820     if (!Found.empty()) {
821       PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
822       if (PrevClassTemplate)
823         PrevDecl = PrevClassTemplate->getTemplatedDecl();
824     }
825   }
826 
827   // If this isn't a friend, then it's a member template, in which
828   // case we just want to build the instantiation in the
829   // specialization.  If it is a friend, we want to build it in
830   // the appropriate context.
831   DeclContext *DC = Owner;
832   if (isFriend) {
833     if (QualifierLoc) {
834       CXXScopeSpec SS;
835       SS.Adopt(QualifierLoc);
836       DC = SemaRef.computeDeclContext(SS);
837       if (!DC) return 0;
838     } else {
839       DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
840                                            Pattern->getDeclContext(),
841                                            TemplateArgs);
842     }
843 
844     // Look for a previous declaration of the template in the owning
845     // context.
846     LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
847                    Sema::LookupOrdinaryName, Sema::ForRedeclaration);
848     SemaRef.LookupQualifiedName(R, DC);
849 
850     if (R.isSingleResult()) {
851       PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
852       if (PrevClassTemplate)
853         PrevDecl = PrevClassTemplate->getTemplatedDecl();
854     }
855 
856     if (!PrevClassTemplate && QualifierLoc) {
857       SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
858         << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
859         << QualifierLoc.getSourceRange();
860       return 0;
861     }
862 
863     bool AdoptedPreviousTemplateParams = false;
864     if (PrevClassTemplate) {
865       bool Complain = true;
866 
867       // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
868       // template for struct std::tr1::__detail::_Map_base, where the
869       // template parameters of the friend declaration don't match the
870       // template parameters of the original declaration. In this one
871       // case, we don't complain about the ill-formed friend
872       // declaration.
873       if (isFriend && Pattern->getIdentifier() &&
874           Pattern->getIdentifier()->isStr("_Map_base") &&
875           DC->isNamespace() &&
876           cast<NamespaceDecl>(DC)->getIdentifier() &&
877           cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
878         DeclContext *DCParent = DC->getParent();
879         if (DCParent->isNamespace() &&
880             cast<NamespaceDecl>(DCParent)->getIdentifier() &&
881             cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
882           DeclContext *DCParent2 = DCParent->getParent();
883           if (DCParent2->isNamespace() &&
884               cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
885               cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
886               DCParent2->getParent()->isTranslationUnit())
887             Complain = false;
888         }
889       }
890 
891       TemplateParameterList *PrevParams
892         = PrevClassTemplate->getTemplateParameters();
893 
894       // Make sure the parameter lists match.
895       if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
896                                                   Complain,
897                                                   Sema::TPL_TemplateMatch)) {
898         if (Complain)
899           return 0;
900 
901         AdoptedPreviousTemplateParams = true;
902         InstParams = PrevParams;
903       }
904 
905       // Do some additional validation, then merge default arguments
906       // from the existing declarations.
907       if (!AdoptedPreviousTemplateParams &&
908           SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
909                                              Sema::TPC_ClassTemplate))
910         return 0;
911     }
912   }
913 
914   CXXRecordDecl *RecordInst
915     = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
916                             Pattern->getLocStart(), Pattern->getLocation(),
917                             Pattern->getIdentifier(), PrevDecl,
918                             /*DelayTypeCreation=*/true);
919 
920   if (QualifierLoc)
921     RecordInst->setQualifierInfo(QualifierLoc);
922 
923   ClassTemplateDecl *Inst
924     = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
925                                 D->getIdentifier(), InstParams, RecordInst,
926                                 PrevClassTemplate);
927   RecordInst->setDescribedClassTemplate(Inst);
928 
929   if (isFriend) {
930     if (PrevClassTemplate)
931       Inst->setAccess(PrevClassTemplate->getAccess());
932     else
933       Inst->setAccess(D->getAccess());
934 
935     Inst->setObjectOfFriendDecl();
936     // TODO: do we want to track the instantiation progeny of this
937     // friend target decl?
938   } else {
939     Inst->setAccess(D->getAccess());
940     if (!PrevClassTemplate)
941       Inst->setInstantiatedFromMemberTemplate(D);
942   }
943 
944   // Trigger creation of the type for the instantiation.
945   SemaRef.Context.getInjectedClassNameType(RecordInst,
946                                     Inst->getInjectedClassNameSpecialization());
947 
948   // Finish handling of friends.
949   if (isFriend) {
950     DC->makeDeclVisibleInContext(Inst);
951     Inst->setLexicalDeclContext(Owner);
952     RecordInst->setLexicalDeclContext(Owner);
953     return Inst;
954   }
955 
956   if (D->isOutOfLine()) {
957     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
958     RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
959   }
960 
961   Owner->addDecl(Inst);
962 
963   if (!PrevClassTemplate) {
964     // Queue up any out-of-line partial specializations of this member
965     // class template; the client will force their instantiation once
966     // the enclosing class has been instantiated.
967     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
968     D->getPartialSpecializations(PartialSpecs);
969     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
970       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
971         OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
972   }
973 
974   return Inst;
975 }
976 
977 Decl *
978 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
979                                    ClassTemplatePartialSpecializationDecl *D) {
980   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
981 
982   // Lookup the already-instantiated declaration in the instantiation
983   // of the class template and return that.
984   DeclContext::lookup_result Found
985     = Owner->lookup(ClassTemplate->getDeclName());
986   if (Found.empty())
987     return 0;
988 
989   ClassTemplateDecl *InstClassTemplate
990     = dyn_cast<ClassTemplateDecl>(Found.front());
991   if (!InstClassTemplate)
992     return 0;
993 
994   if (ClassTemplatePartialSpecializationDecl *Result
995         = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
996     return Result;
997 
998   return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
999 }
1000 
1001 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1002   assert(D->getTemplatedDecl()->isStaticDataMember() &&
1003          "Only static data member templates are allowed.");
1004 
1005   // Create a local instantiation scope for this variable template, which
1006   // will contain the instantiations of the template parameters.
1007   LocalInstantiationScope Scope(SemaRef);
1008   TemplateParameterList *TempParams = D->getTemplateParameters();
1009   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1010   if (!InstParams)
1011     return NULL;
1012 
1013   VarDecl *Pattern = D->getTemplatedDecl();
1014   VarTemplateDecl *PrevVarTemplate = 0;
1015 
1016   if (Pattern->getPreviousDecl()) {
1017     DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1018     if (!Found.empty())
1019       PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1020   }
1021 
1022   VarDecl *VarInst =
1023       cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1024                                          /*InstantiatingVarTemplate=*/true));
1025 
1026   DeclContext *DC = Owner;
1027 
1028   VarTemplateDecl *Inst = VarTemplateDecl::Create(
1029       SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1030       VarInst);
1031   VarInst->setDescribedVarTemplate(Inst);
1032   Inst->setPreviousDecl(PrevVarTemplate);
1033 
1034   Inst->setAccess(D->getAccess());
1035   if (!PrevVarTemplate)
1036     Inst->setInstantiatedFromMemberTemplate(D);
1037 
1038   if (D->isOutOfLine()) {
1039     Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1040     VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1041   }
1042 
1043   Owner->addDecl(Inst);
1044 
1045   if (!PrevVarTemplate) {
1046     // Queue up any out-of-line partial specializations of this member
1047     // variable template; the client will force their instantiation once
1048     // the enclosing class has been instantiated.
1049     SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1050     D->getPartialSpecializations(PartialSpecs);
1051     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1052       if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1053         OutOfLineVarPartialSpecs.push_back(
1054             std::make_pair(Inst, PartialSpecs[I]));
1055   }
1056 
1057   return Inst;
1058 }
1059 
1060 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1061     VarTemplatePartialSpecializationDecl *D) {
1062   assert(D->isStaticDataMember() &&
1063          "Only static data member templates are allowed.");
1064 
1065   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1066 
1067   // Lookup the already-instantiated declaration and return that.
1068   DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1069   assert(!Found.empty() && "Instantiation found nothing?");
1070 
1071   VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1072   assert(InstVarTemplate && "Instantiation did not find a variable template?");
1073 
1074   if (VarTemplatePartialSpecializationDecl *Result =
1075           InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1076     return Result;
1077 
1078   return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1079 }
1080 
1081 Decl *
1082 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1083   // Create a local instantiation scope for this function template, which
1084   // will contain the instantiations of the template parameters and then get
1085   // merged with the local instantiation scope for the function template
1086   // itself.
1087   LocalInstantiationScope Scope(SemaRef);
1088 
1089   TemplateParameterList *TempParams = D->getTemplateParameters();
1090   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1091   if (!InstParams)
1092     return NULL;
1093 
1094   FunctionDecl *Instantiated = 0;
1095   if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1096     Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1097                                                                  InstParams));
1098   else
1099     Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1100                                                           D->getTemplatedDecl(),
1101                                                                 InstParams));
1102 
1103   if (!Instantiated)
1104     return 0;
1105 
1106   // Link the instantiated function template declaration to the function
1107   // template from which it was instantiated.
1108   FunctionTemplateDecl *InstTemplate
1109     = Instantiated->getDescribedFunctionTemplate();
1110   InstTemplate->setAccess(D->getAccess());
1111   assert(InstTemplate &&
1112          "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1113 
1114   bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1115 
1116   // Link the instantiation back to the pattern *unless* this is a
1117   // non-definition friend declaration.
1118   if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1119       !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1120     InstTemplate->setInstantiatedFromMemberTemplate(D);
1121 
1122   // Make declarations visible in the appropriate context.
1123   if (!isFriend) {
1124     Owner->addDecl(InstTemplate);
1125   } else if (InstTemplate->getDeclContext()->isRecord() &&
1126              !D->getPreviousDecl()) {
1127     SemaRef.CheckFriendAccess(InstTemplate);
1128   }
1129 
1130   return InstTemplate;
1131 }
1132 
1133 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1134   CXXRecordDecl *PrevDecl = 0;
1135   if (D->isInjectedClassName())
1136     PrevDecl = cast<CXXRecordDecl>(Owner);
1137   else if (D->getPreviousDecl()) {
1138     NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1139                                                    D->getPreviousDecl(),
1140                                                    TemplateArgs);
1141     if (!Prev) return 0;
1142     PrevDecl = cast<CXXRecordDecl>(Prev);
1143   }
1144 
1145   CXXRecordDecl *Record
1146     = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1147                             D->getLocStart(), D->getLocation(),
1148                             D->getIdentifier(), PrevDecl);
1149 
1150   // Substitute the nested name specifier, if any.
1151   if (SubstQualifier(D, Record))
1152     return 0;
1153 
1154   Record->setImplicit(D->isImplicit());
1155   // FIXME: Check against AS_none is an ugly hack to work around the issue that
1156   // the tag decls introduced by friend class declarations don't have an access
1157   // specifier. Remove once this area of the code gets sorted out.
1158   if (D->getAccess() != AS_none)
1159     Record->setAccess(D->getAccess());
1160   if (!D->isInjectedClassName())
1161     Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1162 
1163   // If the original function was part of a friend declaration,
1164   // inherit its namespace state.
1165   if (D->getFriendObjectKind())
1166     Record->setObjectOfFriendDecl();
1167 
1168   // Make sure that anonymous structs and unions are recorded.
1169   if (D->isAnonymousStructOrUnion())
1170     Record->setAnonymousStructOrUnion(true);
1171 
1172   if (D->isLocalClass())
1173     SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1174 
1175   // Forward the mangling number from the template to the instantiated decl.
1176   SemaRef.Context.setManglingNumber(Record,
1177                                     SemaRef.Context.getManglingNumber(D));
1178 
1179   Owner->addDecl(Record);
1180 
1181   // DR1484 clarifies that the members of a local class are instantiated as part
1182   // of the instantiation of their enclosing entity.
1183   if (D->isCompleteDefinition() && D->isLocalClass()) {
1184     SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1185                              TSK_ImplicitInstantiation,
1186                              /*Complain=*/true);
1187     SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1188                                     TSK_ImplicitInstantiation);
1189   }
1190   return Record;
1191 }
1192 
1193 /// \brief Adjust the given function type for an instantiation of the
1194 /// given declaration, to cope with modifications to the function's type that
1195 /// aren't reflected in the type-source information.
1196 ///
1197 /// \param D The declaration we're instantiating.
1198 /// \param TInfo The already-instantiated type.
1199 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1200                                                    FunctionDecl *D,
1201                                                    TypeSourceInfo *TInfo) {
1202   const FunctionProtoType *OrigFunc
1203     = D->getType()->castAs<FunctionProtoType>();
1204   const FunctionProtoType *NewFunc
1205     = TInfo->getType()->castAs<FunctionProtoType>();
1206   if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1207     return TInfo->getType();
1208 
1209   FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1210   NewEPI.ExtInfo = OrigFunc->getExtInfo();
1211   return Context.getFunctionType(NewFunc->getReturnType(),
1212                                  NewFunc->getParamTypes(), NewEPI);
1213 }
1214 
1215 /// Normal class members are of more specific types and therefore
1216 /// don't make it here.  This function serves two purposes:
1217 ///   1) instantiating function templates
1218 ///   2) substituting friend declarations
1219 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1220                                        TemplateParameterList *TemplateParams) {
1221   // Check whether there is already a function template specialization for
1222   // this declaration.
1223   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1224   if (FunctionTemplate && !TemplateParams) {
1225     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1226 
1227     void *InsertPos = 0;
1228     FunctionDecl *SpecFunc
1229       = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
1230                                              InsertPos);
1231 
1232     // If we already have a function template specialization, return it.
1233     if (SpecFunc)
1234       return SpecFunc;
1235   }
1236 
1237   bool isFriend;
1238   if (FunctionTemplate)
1239     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1240   else
1241     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1242 
1243   bool MergeWithParentScope = (TemplateParams != 0) ||
1244     Owner->isFunctionOrMethod() ||
1245     !(isa<Decl>(Owner) &&
1246       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1247   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1248 
1249   SmallVector<ParmVarDecl *, 4> Params;
1250   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1251   if (!TInfo)
1252     return 0;
1253   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1254 
1255   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1256   if (QualifierLoc) {
1257     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1258                                                        TemplateArgs);
1259     if (!QualifierLoc)
1260       return 0;
1261   }
1262 
1263   // If we're instantiating a local function declaration, put the result
1264   // in the enclosing namespace; otherwise we need to find the instantiated
1265   // context.
1266   DeclContext *DC;
1267   if (D->isLocalExternDecl()) {
1268     DC = Owner;
1269     SemaRef.adjustContextForLocalExternDecl(DC);
1270   } else if (isFriend && QualifierLoc) {
1271     CXXScopeSpec SS;
1272     SS.Adopt(QualifierLoc);
1273     DC = SemaRef.computeDeclContext(SS);
1274     if (!DC) return 0;
1275   } else {
1276     DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1277                                          TemplateArgs);
1278   }
1279 
1280   FunctionDecl *Function =
1281       FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1282                            D->getNameInfo(), T, TInfo,
1283                            D->getCanonicalDecl()->getStorageClass(),
1284                            D->isInlineSpecified(), D->hasWrittenPrototype(),
1285                            D->isConstexpr());
1286   Function->setRangeEnd(D->getSourceRange().getEnd());
1287 
1288   if (D->isInlined())
1289     Function->setImplicitlyInline();
1290 
1291   if (QualifierLoc)
1292     Function->setQualifierInfo(QualifierLoc);
1293 
1294   if (D->isLocalExternDecl())
1295     Function->setLocalExternDecl();
1296 
1297   DeclContext *LexicalDC = Owner;
1298   if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1299     assert(D->getDeclContext()->isFileContext());
1300     LexicalDC = D->getDeclContext();
1301   }
1302 
1303   Function->setLexicalDeclContext(LexicalDC);
1304 
1305   // Attach the parameters
1306   for (unsigned P = 0; P < Params.size(); ++P)
1307     if (Params[P])
1308       Params[P]->setOwningFunction(Function);
1309   Function->setParams(Params);
1310 
1311   SourceLocation InstantiateAtPOI;
1312   if (TemplateParams) {
1313     // Our resulting instantiation is actually a function template, since we
1314     // are substituting only the outer template parameters. For example, given
1315     //
1316     //   template<typename T>
1317     //   struct X {
1318     //     template<typename U> friend void f(T, U);
1319     //   };
1320     //
1321     //   X<int> x;
1322     //
1323     // We are instantiating the friend function template "f" within X<int>,
1324     // which means substituting int for T, but leaving "f" as a friend function
1325     // template.
1326     // Build the function template itself.
1327     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1328                                                     Function->getLocation(),
1329                                                     Function->getDeclName(),
1330                                                     TemplateParams, Function);
1331     Function->setDescribedFunctionTemplate(FunctionTemplate);
1332 
1333     FunctionTemplate->setLexicalDeclContext(LexicalDC);
1334 
1335     if (isFriend && D->isThisDeclarationADefinition()) {
1336       // TODO: should we remember this connection regardless of whether
1337       // the friend declaration provided a body?
1338       FunctionTemplate->setInstantiatedFromMemberTemplate(
1339                                            D->getDescribedFunctionTemplate());
1340     }
1341   } else if (FunctionTemplate) {
1342     // Record this function template specialization.
1343     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1344     Function->setFunctionTemplateSpecialization(FunctionTemplate,
1345                             TemplateArgumentList::CreateCopy(SemaRef.Context,
1346                                                              Innermost.begin(),
1347                                                              Innermost.size()),
1348                                                 /*InsertPos=*/0);
1349   } else if (isFriend) {
1350     // Note, we need this connection even if the friend doesn't have a body.
1351     // Its body may exist but not have been attached yet due to deferred
1352     // parsing.
1353     // FIXME: It might be cleaner to set this when attaching the body to the
1354     // friend function declaration, however that would require finding all the
1355     // instantiations and modifying them.
1356     Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1357   }
1358 
1359   if (InitFunctionInstantiation(Function, D))
1360     Function->setInvalidDecl();
1361 
1362   bool isExplicitSpecialization = false;
1363 
1364   LookupResult Previous(
1365       SemaRef, Function->getDeclName(), SourceLocation(),
1366       D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1367                              : Sema::LookupOrdinaryName,
1368       Sema::ForRedeclaration);
1369 
1370   if (DependentFunctionTemplateSpecializationInfo *Info
1371         = D->getDependentSpecializationInfo()) {
1372     assert(isFriend && "non-friend has dependent specialization info?");
1373 
1374     // This needs to be set now for future sanity.
1375     Function->setObjectOfFriendDecl();
1376 
1377     // Instantiate the explicit template arguments.
1378     TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1379                                           Info->getRAngleLoc());
1380     if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1381                       ExplicitArgs, TemplateArgs))
1382       return 0;
1383 
1384     // Map the candidate templates to their instantiations.
1385     for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1386       Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1387                                                 Info->getTemplate(I),
1388                                                 TemplateArgs);
1389       if (!Temp) return 0;
1390 
1391       Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1392     }
1393 
1394     if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1395                                                     &ExplicitArgs,
1396                                                     Previous))
1397       Function->setInvalidDecl();
1398 
1399     isExplicitSpecialization = true;
1400 
1401   } else if (TemplateParams || !FunctionTemplate) {
1402     // Look only into the namespace where the friend would be declared to
1403     // find a previous declaration. This is the innermost enclosing namespace,
1404     // as described in ActOnFriendFunctionDecl.
1405     SemaRef.LookupQualifiedName(Previous, DC);
1406 
1407     // In C++, the previous declaration we find might be a tag type
1408     // (class or enum). In this case, the new declaration will hide the
1409     // tag type. Note that this does does not apply if we're declaring a
1410     // typedef (C++ [dcl.typedef]p4).
1411     if (Previous.isSingleTagDecl())
1412       Previous.clear();
1413   }
1414 
1415   SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1416                                    isExplicitSpecialization);
1417 
1418   NamedDecl *PrincipalDecl = (TemplateParams
1419                               ? cast<NamedDecl>(FunctionTemplate)
1420                               : Function);
1421 
1422   // If the original function was part of a friend declaration,
1423   // inherit its namespace state and add it to the owner.
1424   if (isFriend) {
1425     PrincipalDecl->setObjectOfFriendDecl();
1426     DC->makeDeclVisibleInContext(PrincipalDecl);
1427 
1428     bool QueuedInstantiation = false;
1429 
1430     // C++11 [temp.friend]p4 (DR329):
1431     //   When a function is defined in a friend function declaration in a class
1432     //   template, the function is instantiated when the function is odr-used.
1433     //   The same restrictions on multiple declarations and definitions that
1434     //   apply to non-template function declarations and definitions also apply
1435     //   to these implicit definitions.
1436     if (D->isThisDeclarationADefinition()) {
1437       // Check for a function body.
1438       const FunctionDecl *Definition = 0;
1439       if (Function->isDefined(Definition) &&
1440           Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1441         SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1442             << Function->getDeclName();
1443         SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1444       }
1445       // Check for redefinitions due to other instantiations of this or
1446       // a similar friend function.
1447       else for (auto R : Function->redecls()) {
1448         if (R == Function)
1449           continue;
1450 
1451         // If some prior declaration of this function has been used, we need
1452         // to instantiate its definition.
1453         if (!QueuedInstantiation && R->isUsed(false)) {
1454           if (MemberSpecializationInfo *MSInfo =
1455                   Function->getMemberSpecializationInfo()) {
1456             if (MSInfo->getPointOfInstantiation().isInvalid()) {
1457               SourceLocation Loc = R->getLocation(); // FIXME
1458               MSInfo->setPointOfInstantiation(Loc);
1459               SemaRef.PendingLocalImplicitInstantiations.push_back(
1460                                                std::make_pair(Function, Loc));
1461               QueuedInstantiation = true;
1462             }
1463           }
1464         }
1465 
1466         // If some prior declaration of this function was a friend with an
1467         // uninstantiated definition, reject it.
1468         if (R->getFriendObjectKind()) {
1469           if (const FunctionDecl *RPattern =
1470                   R->getTemplateInstantiationPattern()) {
1471             if (RPattern->isDefined(RPattern)) {
1472               SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1473                 << Function->getDeclName();
1474               SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1475               break;
1476             }
1477           }
1478         }
1479       }
1480     }
1481   }
1482 
1483   if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1484     DC->makeDeclVisibleInContext(PrincipalDecl);
1485 
1486   if (Function->isOverloadedOperator() && !DC->isRecord() &&
1487       PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1488     PrincipalDecl->setNonMemberOperator();
1489 
1490   assert(!D->isDefaulted() && "only methods should be defaulted");
1491   return Function;
1492 }
1493 
1494 Decl *
1495 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1496                                       TemplateParameterList *TemplateParams,
1497                                       bool IsClassScopeSpecialization) {
1498   FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1499   if (FunctionTemplate && !TemplateParams) {
1500     // We are creating a function template specialization from a function
1501     // template. Check whether there is already a function template
1502     // specialization for this particular set of template arguments.
1503     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1504 
1505     void *InsertPos = 0;
1506     FunctionDecl *SpecFunc
1507       = FunctionTemplate->findSpecialization(Innermost.begin(),
1508                                              Innermost.size(),
1509                                              InsertPos);
1510 
1511     // If we already have a function template specialization, return it.
1512     if (SpecFunc)
1513       return SpecFunc;
1514   }
1515 
1516   bool isFriend;
1517   if (FunctionTemplate)
1518     isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1519   else
1520     isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1521 
1522   bool MergeWithParentScope = (TemplateParams != 0) ||
1523     !(isa<Decl>(Owner) &&
1524       cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1525   LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1526 
1527   // Instantiate enclosing template arguments for friends.
1528   SmallVector<TemplateParameterList *, 4> TempParamLists;
1529   unsigned NumTempParamLists = 0;
1530   if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1531     TempParamLists.set_size(NumTempParamLists);
1532     for (unsigned I = 0; I != NumTempParamLists; ++I) {
1533       TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1534       TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1535       if (!InstParams)
1536         return NULL;
1537       TempParamLists[I] = InstParams;
1538     }
1539   }
1540 
1541   SmallVector<ParmVarDecl *, 4> Params;
1542   TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1543   if (!TInfo)
1544     return 0;
1545   QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1546 
1547   NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1548   if (QualifierLoc) {
1549     QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1550                                                  TemplateArgs);
1551     if (!QualifierLoc)
1552       return 0;
1553   }
1554 
1555   DeclContext *DC = Owner;
1556   if (isFriend) {
1557     if (QualifierLoc) {
1558       CXXScopeSpec SS;
1559       SS.Adopt(QualifierLoc);
1560       DC = SemaRef.computeDeclContext(SS);
1561 
1562       if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1563         return 0;
1564     } else {
1565       DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1566                                            D->getDeclContext(),
1567                                            TemplateArgs);
1568     }
1569     if (!DC) return 0;
1570   }
1571 
1572   // Build the instantiated method declaration.
1573   CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1574   CXXMethodDecl *Method = 0;
1575 
1576   SourceLocation StartLoc = D->getInnerLocStart();
1577   DeclarationNameInfo NameInfo
1578     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1579   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1580     Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1581                                         StartLoc, NameInfo, T, TInfo,
1582                                         Constructor->isExplicit(),
1583                                         Constructor->isInlineSpecified(),
1584                                         false, Constructor->isConstexpr());
1585 
1586     // Claim that the instantiation of a constructor or constructor template
1587     // inherits the same constructor that the template does.
1588     if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1589             Constructor->getInheritedConstructor())) {
1590       // If we're instantiating a specialization of a function template, our
1591       // "inherited constructor" will actually itself be a function template.
1592       // Instantiate a declaration of it, too.
1593       if (FunctionTemplate) {
1594         assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1595                !Inh->getParent()->isDependentContext() &&
1596                "inheriting constructor template in dependent context?");
1597         Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1598                                          Inh);
1599         if (Inst.isInvalid())
1600           return 0;
1601         Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1602         LocalInstantiationScope LocalScope(SemaRef);
1603 
1604         // Use the same template arguments that we deduced for the inheriting
1605         // constructor. There's no way they could be deduced differently.
1606         MultiLevelTemplateArgumentList InheritedArgs;
1607         InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1608         Inh = cast_or_null<CXXConstructorDecl>(
1609             SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1610         if (!Inh)
1611           return 0;
1612       }
1613       cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
1614     }
1615   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1616     Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1617                                        StartLoc, NameInfo, T, TInfo,
1618                                        Destructor->isInlineSpecified(),
1619                                        false);
1620   } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1621     Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1622                                        StartLoc, NameInfo, T, TInfo,
1623                                        Conversion->isInlineSpecified(),
1624                                        Conversion->isExplicit(),
1625                                        Conversion->isConstexpr(),
1626                                        Conversion->getLocEnd());
1627   } else {
1628     StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1629     Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1630                                    StartLoc, NameInfo, T, TInfo,
1631                                    SC, D->isInlineSpecified(),
1632                                    D->isConstexpr(), D->getLocEnd());
1633   }
1634 
1635   if (D->isInlined())
1636     Method->setImplicitlyInline();
1637 
1638   if (QualifierLoc)
1639     Method->setQualifierInfo(QualifierLoc);
1640 
1641   if (TemplateParams) {
1642     // Our resulting instantiation is actually a function template, since we
1643     // are substituting only the outer template parameters. For example, given
1644     //
1645     //   template<typename T>
1646     //   struct X {
1647     //     template<typename U> void f(T, U);
1648     //   };
1649     //
1650     //   X<int> x;
1651     //
1652     // We are instantiating the member template "f" within X<int>, which means
1653     // substituting int for T, but leaving "f" as a member function template.
1654     // Build the function template itself.
1655     FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1656                                                     Method->getLocation(),
1657                                                     Method->getDeclName(),
1658                                                     TemplateParams, Method);
1659     if (isFriend) {
1660       FunctionTemplate->setLexicalDeclContext(Owner);
1661       FunctionTemplate->setObjectOfFriendDecl();
1662     } else if (D->isOutOfLine())
1663       FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1664     Method->setDescribedFunctionTemplate(FunctionTemplate);
1665   } else if (FunctionTemplate) {
1666     // Record this function template specialization.
1667     ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1668     Method->setFunctionTemplateSpecialization(FunctionTemplate,
1669                          TemplateArgumentList::CreateCopy(SemaRef.Context,
1670                                                           Innermost.begin(),
1671                                                           Innermost.size()),
1672                                               /*InsertPos=*/0);
1673   } else if (!isFriend) {
1674     // Record that this is an instantiation of a member function.
1675     Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1676   }
1677 
1678   // If we are instantiating a member function defined
1679   // out-of-line, the instantiation will have the same lexical
1680   // context (which will be a namespace scope) as the template.
1681   if (isFriend) {
1682     if (NumTempParamLists)
1683       Method->setTemplateParameterListsInfo(SemaRef.Context,
1684                                             NumTempParamLists,
1685                                             TempParamLists.data());
1686 
1687     Method->setLexicalDeclContext(Owner);
1688     Method->setObjectOfFriendDecl();
1689   } else if (D->isOutOfLine())
1690     Method->setLexicalDeclContext(D->getLexicalDeclContext());
1691 
1692   // Attach the parameters
1693   for (unsigned P = 0; P < Params.size(); ++P)
1694     Params[P]->setOwningFunction(Method);
1695   Method->setParams(Params);
1696 
1697   if (InitMethodInstantiation(Method, D))
1698     Method->setInvalidDecl();
1699 
1700   LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1701                         Sema::ForRedeclaration);
1702 
1703   if (!FunctionTemplate || TemplateParams || isFriend) {
1704     SemaRef.LookupQualifiedName(Previous, Record);
1705 
1706     // In C++, the previous declaration we find might be a tag type
1707     // (class or enum). In this case, the new declaration will hide the
1708     // tag type. Note that this does does not apply if we're declaring a
1709     // typedef (C++ [dcl.typedef]p4).
1710     if (Previous.isSingleTagDecl())
1711       Previous.clear();
1712   }
1713 
1714   if (!IsClassScopeSpecialization)
1715     SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
1716 
1717   if (D->isPure())
1718     SemaRef.CheckPureMethod(Method, SourceRange());
1719 
1720   // Propagate access.  For a non-friend declaration, the access is
1721   // whatever we're propagating from.  For a friend, it should be the
1722   // previous declaration we just found.
1723   if (isFriend && Method->getPreviousDecl())
1724     Method->setAccess(Method->getPreviousDecl()->getAccess());
1725   else
1726     Method->setAccess(D->getAccess());
1727   if (FunctionTemplate)
1728     FunctionTemplate->setAccess(Method->getAccess());
1729 
1730   SemaRef.CheckOverrideControl(Method);
1731 
1732   // If a function is defined as defaulted or deleted, mark it as such now.
1733   if (D->isExplicitlyDefaulted())
1734     SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1735   if (D->isDeletedAsWritten())
1736     SemaRef.SetDeclDeleted(Method, Method->getLocation());
1737 
1738   // If there's a function template, let our caller handle it.
1739   if (FunctionTemplate) {
1740     // do nothing
1741 
1742   // Don't hide a (potentially) valid declaration with an invalid one.
1743   } else if (Method->isInvalidDecl() && !Previous.empty()) {
1744     // do nothing
1745 
1746   // Otherwise, check access to friends and make them visible.
1747   } else if (isFriend) {
1748     // We only need to re-check access for methods which we didn't
1749     // manage to match during parsing.
1750     if (!D->getPreviousDecl())
1751       SemaRef.CheckFriendAccess(Method);
1752 
1753     Record->makeDeclVisibleInContext(Method);
1754 
1755   // Otherwise, add the declaration.  We don't need to do this for
1756   // class-scope specializations because we'll have matched them with
1757   // the appropriate template.
1758   } else if (!IsClassScopeSpecialization) {
1759     Owner->addDecl(Method);
1760   }
1761 
1762   return Method;
1763 }
1764 
1765 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1766   return VisitCXXMethodDecl(D);
1767 }
1768 
1769 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1770   return VisitCXXMethodDecl(D);
1771 }
1772 
1773 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1774   return VisitCXXMethodDecl(D);
1775 }
1776 
1777 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1778   return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1779                                   /*ExpectParameterPack=*/ false);
1780 }
1781 
1782 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1783                                                     TemplateTypeParmDecl *D) {
1784   // TODO: don't always clone when decls are refcounted.
1785   assert(D->getTypeForDecl()->isTemplateTypeParmType());
1786 
1787   TemplateTypeParmDecl *Inst =
1788     TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1789                                  D->getLocStart(), D->getLocation(),
1790                                  D->getDepth() - TemplateArgs.getNumLevels(),
1791                                  D->getIndex(), D->getIdentifier(),
1792                                  D->wasDeclaredWithTypename(),
1793                                  D->isParameterPack());
1794   Inst->setAccess(AS_public);
1795 
1796   if (D->hasDefaultArgument()) {
1797     TypeSourceInfo *InstantiatedDefaultArg =
1798         SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1799                           D->getDefaultArgumentLoc(), D->getDeclName());
1800     if (InstantiatedDefaultArg)
1801       Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1802   }
1803 
1804   // Introduce this template parameter's instantiation into the instantiation
1805   // scope.
1806   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1807 
1808   return Inst;
1809 }
1810 
1811 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1812                                                  NonTypeTemplateParmDecl *D) {
1813   // Substitute into the type of the non-type template parameter.
1814   TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1815   SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1816   SmallVector<QualType, 4> ExpandedParameterPackTypes;
1817   bool IsExpandedParameterPack = false;
1818   TypeSourceInfo *DI;
1819   QualType T;
1820   bool Invalid = false;
1821 
1822   if (D->isExpandedParameterPack()) {
1823     // The non-type template parameter pack is an already-expanded pack
1824     // expansion of types. Substitute into each of the expanded types.
1825     ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1826     ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1827     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1828       TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1829                                                TemplateArgs,
1830                                                D->getLocation(),
1831                                                D->getDeclName());
1832       if (!NewDI)
1833         return 0;
1834 
1835       ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1836       QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1837                                                               D->getLocation());
1838       if (NewT.isNull())
1839         return 0;
1840       ExpandedParameterPackTypes.push_back(NewT);
1841     }
1842 
1843     IsExpandedParameterPack = true;
1844     DI = D->getTypeSourceInfo();
1845     T = DI->getType();
1846   } else if (D->isPackExpansion()) {
1847     // The non-type template parameter pack's type is a pack expansion of types.
1848     // Determine whether we need to expand this parameter pack into separate
1849     // types.
1850     PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
1851     TypeLoc Pattern = Expansion.getPatternLoc();
1852     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1853     SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1854 
1855     // Determine whether the set of unexpanded parameter packs can and should
1856     // be expanded.
1857     bool Expand = true;
1858     bool RetainExpansion = false;
1859     Optional<unsigned> OrigNumExpansions
1860       = Expansion.getTypePtr()->getNumExpansions();
1861     Optional<unsigned> NumExpansions = OrigNumExpansions;
1862     if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1863                                                 Pattern.getSourceRange(),
1864                                                 Unexpanded,
1865                                                 TemplateArgs,
1866                                                 Expand, RetainExpansion,
1867                                                 NumExpansions))
1868       return 0;
1869 
1870     if (Expand) {
1871       for (unsigned I = 0; I != *NumExpansions; ++I) {
1872         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1873         TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1874                                                   D->getLocation(),
1875                                                   D->getDeclName());
1876         if (!NewDI)
1877           return 0;
1878 
1879         ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1880         QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1881                                                               NewDI->getType(),
1882                                                               D->getLocation());
1883         if (NewT.isNull())
1884           return 0;
1885         ExpandedParameterPackTypes.push_back(NewT);
1886       }
1887 
1888       // Note that we have an expanded parameter pack. The "type" of this
1889       // expanded parameter pack is the original expansion type, but callers
1890       // will end up using the expanded parameter pack types for type-checking.
1891       IsExpandedParameterPack = true;
1892       DI = D->getTypeSourceInfo();
1893       T = DI->getType();
1894     } else {
1895       // We cannot fully expand the pack expansion now, so substitute into the
1896       // pattern and create a new pack expansion type.
1897       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1898       TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1899                                                      D->getLocation(),
1900                                                      D->getDeclName());
1901       if (!NewPattern)
1902         return 0;
1903 
1904       DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1905                                       NumExpansions);
1906       if (!DI)
1907         return 0;
1908 
1909       T = DI->getType();
1910     }
1911   } else {
1912     // Simple case: substitution into a parameter that is not a parameter pack.
1913     DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1914                            D->getLocation(), D->getDeclName());
1915     if (!DI)
1916       return 0;
1917 
1918     // Check that this type is acceptable for a non-type template parameter.
1919     T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1920                                                   D->getLocation());
1921     if (T.isNull()) {
1922       T = SemaRef.Context.IntTy;
1923       Invalid = true;
1924     }
1925   }
1926 
1927   NonTypeTemplateParmDecl *Param;
1928   if (IsExpandedParameterPack)
1929     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1930                                             D->getInnerLocStart(),
1931                                             D->getLocation(),
1932                                     D->getDepth() - TemplateArgs.getNumLevels(),
1933                                             D->getPosition(),
1934                                             D->getIdentifier(), T,
1935                                             DI,
1936                                             ExpandedParameterPackTypes.data(),
1937                                             ExpandedParameterPackTypes.size(),
1938                                     ExpandedParameterPackTypesAsWritten.data());
1939   else
1940     Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1941                                             D->getInnerLocStart(),
1942                                             D->getLocation(),
1943                                     D->getDepth() - TemplateArgs.getNumLevels(),
1944                                             D->getPosition(),
1945                                             D->getIdentifier(), T,
1946                                             D->isParameterPack(), DI);
1947 
1948   Param->setAccess(AS_public);
1949   if (Invalid)
1950     Param->setInvalidDecl();
1951 
1952   if (D->hasDefaultArgument()) {
1953     ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1954     if (!Value.isInvalid())
1955       Param->setDefaultArgument(Value.get(), false);
1956   }
1957 
1958   // Introduce this template parameter's instantiation into the instantiation
1959   // scope.
1960   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1961   return Param;
1962 }
1963 
1964 static void collectUnexpandedParameterPacks(
1965     Sema &S,
1966     TemplateParameterList *Params,
1967     SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1968   for (TemplateParameterList::const_iterator I = Params->begin(),
1969                                              E = Params->end(); I != E; ++I) {
1970     if ((*I)->isTemplateParameterPack())
1971       continue;
1972     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1973       S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1974                                         Unexpanded);
1975     if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1976       collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1977                                       Unexpanded);
1978   }
1979 }
1980 
1981 Decl *
1982 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1983                                                   TemplateTemplateParmDecl *D) {
1984   // Instantiate the template parameter list of the template template parameter.
1985   TemplateParameterList *TempParams = D->getTemplateParameters();
1986   TemplateParameterList *InstParams;
1987   SmallVector<TemplateParameterList*, 8> ExpandedParams;
1988 
1989   bool IsExpandedParameterPack = false;
1990 
1991   if (D->isExpandedParameterPack()) {
1992     // The template template parameter pack is an already-expanded pack
1993     // expansion of template parameters. Substitute into each of the expanded
1994     // parameters.
1995     ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1996     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1997          I != N; ++I) {
1998       LocalInstantiationScope Scope(SemaRef);
1999       TemplateParameterList *Expansion =
2000         SubstTemplateParams(D->getExpansionTemplateParameters(I));
2001       if (!Expansion)
2002         return 0;
2003       ExpandedParams.push_back(Expansion);
2004     }
2005 
2006     IsExpandedParameterPack = true;
2007     InstParams = TempParams;
2008   } else if (D->isPackExpansion()) {
2009     // The template template parameter pack expands to a pack of template
2010     // template parameters. Determine whether we need to expand this parameter
2011     // pack into separate parameters.
2012     SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2013     collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2014                                     Unexpanded);
2015 
2016     // Determine whether the set of unexpanded parameter packs can and should
2017     // be expanded.
2018     bool Expand = true;
2019     bool RetainExpansion = false;
2020     Optional<unsigned> NumExpansions;
2021     if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2022                                                 TempParams->getSourceRange(),
2023                                                 Unexpanded,
2024                                                 TemplateArgs,
2025                                                 Expand, RetainExpansion,
2026                                                 NumExpansions))
2027       return 0;
2028 
2029     if (Expand) {
2030       for (unsigned I = 0; I != *NumExpansions; ++I) {
2031         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2032         LocalInstantiationScope Scope(SemaRef);
2033         TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2034         if (!Expansion)
2035           return 0;
2036         ExpandedParams.push_back(Expansion);
2037       }
2038 
2039       // Note that we have an expanded parameter pack. The "type" of this
2040       // expanded parameter pack is the original expansion type, but callers
2041       // will end up using the expanded parameter pack types for type-checking.
2042       IsExpandedParameterPack = true;
2043       InstParams = TempParams;
2044     } else {
2045       // We cannot fully expand the pack expansion now, so just substitute
2046       // into the pattern.
2047       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2048 
2049       LocalInstantiationScope Scope(SemaRef);
2050       InstParams = SubstTemplateParams(TempParams);
2051       if (!InstParams)
2052         return 0;
2053     }
2054   } else {
2055     // Perform the actual substitution of template parameters within a new,
2056     // local instantiation scope.
2057     LocalInstantiationScope Scope(SemaRef);
2058     InstParams = SubstTemplateParams(TempParams);
2059     if (!InstParams)
2060       return 0;
2061   }
2062 
2063   // Build the template template parameter.
2064   TemplateTemplateParmDecl *Param;
2065   if (IsExpandedParameterPack)
2066     Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2067                                              D->getLocation(),
2068                                    D->getDepth() - TemplateArgs.getNumLevels(),
2069                                              D->getPosition(),
2070                                              D->getIdentifier(), InstParams,
2071                                              ExpandedParams);
2072   else
2073     Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2074                                              D->getLocation(),
2075                                    D->getDepth() - TemplateArgs.getNumLevels(),
2076                                              D->getPosition(),
2077                                              D->isParameterPack(),
2078                                              D->getIdentifier(), InstParams);
2079   if (D->hasDefaultArgument()) {
2080     NestedNameSpecifierLoc QualifierLoc =
2081         D->getDefaultArgument().getTemplateQualifierLoc();
2082     QualifierLoc =
2083         SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2084     TemplateName TName = SemaRef.SubstTemplateName(
2085         QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2086         D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2087     if (!TName.isNull())
2088       Param->setDefaultArgument(
2089           TemplateArgumentLoc(TemplateArgument(TName),
2090                               D->getDefaultArgument().getTemplateQualifierLoc(),
2091                               D->getDefaultArgument().getTemplateNameLoc()),
2092           false);
2093   }
2094   Param->setAccess(AS_public);
2095 
2096   // Introduce this template parameter's instantiation into the instantiation
2097   // scope.
2098   SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2099 
2100   return Param;
2101 }
2102 
2103 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2104   // Using directives are never dependent (and never contain any types or
2105   // expressions), so they require no explicit instantiation work.
2106 
2107   UsingDirectiveDecl *Inst
2108     = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2109                                  D->getNamespaceKeyLocation(),
2110                                  D->getQualifierLoc(),
2111                                  D->getIdentLocation(),
2112                                  D->getNominatedNamespace(),
2113                                  D->getCommonAncestor());
2114 
2115   // Add the using directive to its declaration context
2116   // only if this is not a function or method.
2117   if (!Owner->isFunctionOrMethod())
2118     Owner->addDecl(Inst);
2119 
2120   return Inst;
2121 }
2122 
2123 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2124 
2125   // The nested name specifier may be dependent, for example
2126   //     template <typename T> struct t {
2127   //       struct s1 { T f1(); };
2128   //       struct s2 : s1 { using s1::f1; };
2129   //     };
2130   //     template struct t<int>;
2131   // Here, in using s1::f1, s1 refers to t<T>::s1;
2132   // we need to substitute for t<int>::s1.
2133   NestedNameSpecifierLoc QualifierLoc
2134     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2135                                           TemplateArgs);
2136   if (!QualifierLoc)
2137     return 0;
2138 
2139   // The name info is non-dependent, so no transformation
2140   // is required.
2141   DeclarationNameInfo NameInfo = D->getNameInfo();
2142 
2143   // We only need to do redeclaration lookups if we're in a class
2144   // scope (in fact, it's not really even possible in non-class
2145   // scopes).
2146   bool CheckRedeclaration = Owner->isRecord();
2147 
2148   LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2149                     Sema::ForRedeclaration);
2150 
2151   UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2152                                        D->getUsingLoc(),
2153                                        QualifierLoc,
2154                                        NameInfo,
2155                                        D->hasTypename());
2156 
2157   CXXScopeSpec SS;
2158   SS.Adopt(QualifierLoc);
2159   if (CheckRedeclaration) {
2160     Prev.setHideTags(false);
2161     SemaRef.LookupQualifiedName(Prev, Owner);
2162 
2163     // Check for invalid redeclarations.
2164     if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2165                                             D->hasTypename(), SS,
2166                                             D->getLocation(), Prev))
2167       NewUD->setInvalidDecl();
2168 
2169   }
2170 
2171   if (!NewUD->isInvalidDecl() &&
2172       SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
2173                                       D->getLocation()))
2174     NewUD->setInvalidDecl();
2175 
2176   SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2177   NewUD->setAccess(D->getAccess());
2178   Owner->addDecl(NewUD);
2179 
2180   // Don't process the shadow decls for an invalid decl.
2181   if (NewUD->isInvalidDecl())
2182     return NewUD;
2183 
2184   if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2185     if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2186       NewUD->setInvalidDecl();
2187     return NewUD;
2188   }
2189 
2190   bool isFunctionScope = Owner->isFunctionOrMethod();
2191 
2192   // Process the shadow decls.
2193   for (auto *Shadow : D->shadows()) {
2194     NamedDecl *InstTarget =
2195         cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2196             Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
2197     if (!InstTarget)
2198       return 0;
2199 
2200     UsingShadowDecl *PrevDecl = 0;
2201     if (CheckRedeclaration) {
2202       if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2203         continue;
2204     } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2205       PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2206           Shadow->getLocation(), OldPrev, TemplateArgs));
2207     }
2208 
2209     UsingShadowDecl *InstShadow =
2210         SemaRef.BuildUsingShadowDecl(/*Scope*/0, NewUD, InstTarget, PrevDecl);
2211     SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2212 
2213     if (isFunctionScope)
2214       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2215   }
2216 
2217   return NewUD;
2218 }
2219 
2220 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2221   // Ignore these;  we handle them in bulk when processing the UsingDecl.
2222   return 0;
2223 }
2224 
2225 Decl * TemplateDeclInstantiator
2226     ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2227   NestedNameSpecifierLoc QualifierLoc
2228     = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2229                                           TemplateArgs);
2230   if (!QualifierLoc)
2231     return 0;
2232 
2233   CXXScopeSpec SS;
2234   SS.Adopt(QualifierLoc);
2235 
2236   // Since NameInfo refers to a typename, it cannot be a C++ special name.
2237   // Hence, no transformation is required for it.
2238   DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2239   NamedDecl *UD =
2240     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2241                                   D->getUsingLoc(), SS, NameInfo, 0,
2242                                   /*instantiation*/ true,
2243                                   /*typename*/ true, D->getTypenameLoc());
2244   if (UD)
2245     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2246 
2247   return UD;
2248 }
2249 
2250 Decl * TemplateDeclInstantiator
2251     ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2252   NestedNameSpecifierLoc QualifierLoc
2253       = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2254   if (!QualifierLoc)
2255     return 0;
2256 
2257   CXXScopeSpec SS;
2258   SS.Adopt(QualifierLoc);
2259 
2260   DeclarationNameInfo NameInfo
2261     = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2262 
2263   NamedDecl *UD =
2264     SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
2265                                   D->getUsingLoc(), SS, NameInfo, 0,
2266                                   /*instantiation*/ true,
2267                                   /*typename*/ false, SourceLocation());
2268   if (UD)
2269     SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2270 
2271   return UD;
2272 }
2273 
2274 
2275 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2276                                      ClassScopeFunctionSpecializationDecl *Decl) {
2277   CXXMethodDecl *OldFD = Decl->getSpecialization();
2278   CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2279                                                                 0, true));
2280 
2281   LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2282                         Sema::ForRedeclaration);
2283 
2284   TemplateArgumentListInfo TemplateArgs;
2285   TemplateArgumentListInfo* TemplateArgsPtr = 0;
2286   if (Decl->hasExplicitTemplateArgs()) {
2287     TemplateArgs = Decl->templateArgs();
2288     TemplateArgsPtr = &TemplateArgs;
2289   }
2290 
2291   SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2292   if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2293                                                   Previous)) {
2294     NewFD->setInvalidDecl();
2295     return NewFD;
2296   }
2297 
2298   // Associate the specialization with the pattern.
2299   FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2300   assert(Specialization && "Class scope Specialization is null");
2301   SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2302 
2303   return NewFD;
2304 }
2305 
2306 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2307                                      OMPThreadPrivateDecl *D) {
2308   SmallVector<Expr *, 5> Vars;
2309   for (auto *I : D->varlists()) {
2310     Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).take();
2311     assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2312     Vars.push_back(Var);
2313   }
2314 
2315   OMPThreadPrivateDecl *TD =
2316     SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2317 
2318   TD->setAccess(AS_public);
2319   Owner->addDecl(TD);
2320 
2321   return TD;
2322 }
2323 
2324 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2325   return VisitFunctionDecl(D, 0);
2326 }
2327 
2328 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2329   return VisitCXXMethodDecl(D, 0);
2330 }
2331 
2332 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2333   llvm_unreachable("There are only CXXRecordDecls in C++");
2334 }
2335 
2336 Decl *
2337 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2338     ClassTemplateSpecializationDecl *D) {
2339   // As a MS extension, we permit class-scope explicit specialization
2340   // of member class templates.
2341   ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2342   assert(ClassTemplate->getDeclContext()->isRecord() &&
2343          D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2344          "can only instantiate an explicit specialization "
2345          "for a member class template");
2346 
2347   // Lookup the already-instantiated declaration in the instantiation
2348   // of the class template. FIXME: Diagnose or assert if this fails?
2349   DeclContext::lookup_result Found
2350     = Owner->lookup(ClassTemplate->getDeclName());
2351   if (Found.empty())
2352     return 0;
2353   ClassTemplateDecl *InstClassTemplate
2354     = dyn_cast<ClassTemplateDecl>(Found.front());
2355   if (!InstClassTemplate)
2356     return 0;
2357 
2358   // Substitute into the template arguments of the class template explicit
2359   // specialization.
2360   TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2361                                         castAs<TemplateSpecializationTypeLoc>();
2362   TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2363                                             Loc.getRAngleLoc());
2364   SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2365   for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2366     ArgLocs.push_back(Loc.getArgLoc(I));
2367   if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2368                     InstTemplateArgs, TemplateArgs))
2369     return 0;
2370 
2371   // Check that the template argument list is well-formed for this
2372   // class template.
2373   SmallVector<TemplateArgument, 4> Converted;
2374   if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2375                                         D->getLocation(),
2376                                         InstTemplateArgs,
2377                                         false,
2378                                         Converted))
2379     return 0;
2380 
2381   // Figure out where to insert this class template explicit specialization
2382   // in the member template's set of class template explicit specializations.
2383   void *InsertPos = 0;
2384   ClassTemplateSpecializationDecl *PrevDecl =
2385       InstClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2386                                             InsertPos);
2387 
2388   // Check whether we've already seen a conflicting instantiation of this
2389   // declaration (for instance, if there was a prior implicit instantiation).
2390   bool Ignored;
2391   if (PrevDecl &&
2392       SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2393                                                      D->getSpecializationKind(),
2394                                                      PrevDecl,
2395                                                      PrevDecl->getSpecializationKind(),
2396                                                      PrevDecl->getPointOfInstantiation(),
2397                                                      Ignored))
2398     return 0;
2399 
2400   // If PrevDecl was a definition and D is also a definition, diagnose.
2401   // This happens in cases like:
2402   //
2403   //   template<typename T, typename U>
2404   //   struct Outer {
2405   //     template<typename X> struct Inner;
2406   //     template<> struct Inner<T> {};
2407   //     template<> struct Inner<U> {};
2408   //   };
2409   //
2410   //   Outer<int, int> outer; // error: the explicit specializations of Inner
2411   //                          // have the same signature.
2412   if (PrevDecl && PrevDecl->getDefinition() &&
2413       D->isThisDeclarationADefinition()) {
2414     SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2415     SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2416                  diag::note_previous_definition);
2417     return 0;
2418   }
2419 
2420   // Create the class template partial specialization declaration.
2421   ClassTemplateSpecializationDecl *InstD
2422     = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2423                                               D->getTagKind(),
2424                                               Owner,
2425                                               D->getLocStart(),
2426                                               D->getLocation(),
2427                                               InstClassTemplate,
2428                                               Converted.data(),
2429                                               Converted.size(),
2430                                               PrevDecl);
2431 
2432   // Add this partial specialization to the set of class template partial
2433   // specializations.
2434   if (!PrevDecl)
2435     InstClassTemplate->AddSpecialization(InstD, InsertPos);
2436 
2437   // Substitute the nested name specifier, if any.
2438   if (SubstQualifier(D, InstD))
2439     return 0;
2440 
2441   // Build the canonical type that describes the converted template
2442   // arguments of the class template explicit specialization.
2443   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2444       TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2445       SemaRef.Context.getRecordType(InstD));
2446 
2447   // Build the fully-sugared type for this class template
2448   // specialization as the user wrote in the specialization
2449   // itself. This means that we'll pretty-print the type retrieved
2450   // from the specialization's declaration the way that the user
2451   // actually wrote the specialization, rather than formatting the
2452   // name based on the "canonical" representation used to store the
2453   // template arguments in the specialization.
2454   TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2455       TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2456       CanonType);
2457 
2458   InstD->setAccess(D->getAccess());
2459   InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2460   InstD->setSpecializationKind(D->getSpecializationKind());
2461   InstD->setTypeAsWritten(WrittenTy);
2462   InstD->setExternLoc(D->getExternLoc());
2463   InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2464 
2465   Owner->addDecl(InstD);
2466 
2467   // Instantiate the members of the class-scope explicit specialization eagerly.
2468   // We don't have support for lazy instantiation of an explicit specialization
2469   // yet, and MSVC eagerly instantiates in this case.
2470   if (D->isThisDeclarationADefinition() &&
2471       SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2472                                TSK_ImplicitInstantiation,
2473                                /*Complain=*/true))
2474     return 0;
2475 
2476   return InstD;
2477 }
2478 
2479 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2480     VarTemplateSpecializationDecl *D) {
2481 
2482   TemplateArgumentListInfo VarTemplateArgsInfo;
2483   VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2484   assert(VarTemplate &&
2485          "A template specialization without specialized template?");
2486 
2487   // Substitute the current template arguments.
2488   const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2489   VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2490   VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2491 
2492   if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2493                     TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2494     return 0;
2495 
2496   // Check that the template argument list is well-formed for this template.
2497   SmallVector<TemplateArgument, 4> Converted;
2498   if (SemaRef.CheckTemplateArgumentList(
2499           VarTemplate, VarTemplate->getLocStart(),
2500           const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2501           Converted))
2502     return 0;
2503 
2504   // Find the variable template specialization declaration that
2505   // corresponds to these arguments.
2506   void *InsertPos = 0;
2507   if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2508           Converted.data(), Converted.size(), InsertPos))
2509     // If we already have a variable template specialization, return it.
2510     return VarSpec;
2511 
2512   return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2513                                             VarTemplateArgsInfo, Converted);
2514 }
2515 
2516 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2517     VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2518     const TemplateArgumentListInfo &TemplateArgsInfo,
2519     llvm::ArrayRef<TemplateArgument> Converted) {
2520 
2521   // If this is the variable for an anonymous struct or union,
2522   // instantiate the anonymous struct/union type first.
2523   if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2524     if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2525       if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2526         return 0;
2527 
2528   // Do substitution on the type of the declaration
2529   TypeSourceInfo *DI =
2530       SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2531                         D->getTypeSpecStartLoc(), D->getDeclName());
2532   if (!DI)
2533     return 0;
2534 
2535   if (DI->getType()->isFunctionType()) {
2536     SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2537         << D->isStaticDataMember() << DI->getType();
2538     return 0;
2539   }
2540 
2541   // Build the instantiated declaration
2542   VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2543       SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2544       VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2545       Converted.size());
2546   Var->setTemplateArgsInfo(TemplateArgsInfo);
2547   if (InsertPos)
2548     VarTemplate->AddSpecialization(Var, InsertPos);
2549 
2550   // Substitute the nested name specifier, if any.
2551   if (SubstQualifier(D, Var))
2552     return 0;
2553 
2554   SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2555                                      Owner, StartingScope);
2556 
2557   return Var;
2558 }
2559 
2560 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2561   llvm_unreachable("@defs is not supported in Objective-C++");
2562 }
2563 
2564 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2565   // FIXME: We need to be able to instantiate FriendTemplateDecls.
2566   unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2567                                                DiagnosticsEngine::Error,
2568                                                "cannot instantiate %0 yet");
2569   SemaRef.Diag(D->getLocation(), DiagID)
2570     << D->getDeclKindName();
2571 
2572   return 0;
2573 }
2574 
2575 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2576   llvm_unreachable("Unexpected decl");
2577 }
2578 
2579 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2580                       const MultiLevelTemplateArgumentList &TemplateArgs) {
2581   TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2582   if (D->isInvalidDecl())
2583     return 0;
2584 
2585   return Instantiator.Visit(D);
2586 }
2587 
2588 /// \brief Instantiates a nested template parameter list in the current
2589 /// instantiation context.
2590 ///
2591 /// \param L The parameter list to instantiate
2592 ///
2593 /// \returns NULL if there was an error
2594 TemplateParameterList *
2595 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2596   // Get errors for all the parameters before bailing out.
2597   bool Invalid = false;
2598 
2599   unsigned N = L->size();
2600   typedef SmallVector<NamedDecl *, 8> ParamVector;
2601   ParamVector Params;
2602   Params.reserve(N);
2603   for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2604        PI != PE; ++PI) {
2605     NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2606     Params.push_back(D);
2607     Invalid = Invalid || !D || D->isInvalidDecl();
2608   }
2609 
2610   // Clean up if we had an error.
2611   if (Invalid)
2612     return NULL;
2613 
2614   TemplateParameterList *InstL
2615     = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2616                                     L->getLAngleLoc(), &Params.front(), N,
2617                                     L->getRAngleLoc());
2618   return InstL;
2619 }
2620 
2621 /// \brief Instantiate the declaration of a class template partial
2622 /// specialization.
2623 ///
2624 /// \param ClassTemplate the (instantiated) class template that is partially
2625 // specialized by the instantiation of \p PartialSpec.
2626 ///
2627 /// \param PartialSpec the (uninstantiated) class template partial
2628 /// specialization that we are instantiating.
2629 ///
2630 /// \returns The instantiated partial specialization, if successful; otherwise,
2631 /// NULL to indicate an error.
2632 ClassTemplatePartialSpecializationDecl *
2633 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2634                                             ClassTemplateDecl *ClassTemplate,
2635                           ClassTemplatePartialSpecializationDecl *PartialSpec) {
2636   // Create a local instantiation scope for this class template partial
2637   // specialization, which will contain the instantiations of the template
2638   // parameters.
2639   LocalInstantiationScope Scope(SemaRef);
2640 
2641   // Substitute into the template parameters of the class template partial
2642   // specialization.
2643   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2644   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2645   if (!InstParams)
2646     return 0;
2647 
2648   // Substitute into the template arguments of the class template partial
2649   // specialization.
2650   const ASTTemplateArgumentListInfo *TemplArgInfo
2651     = PartialSpec->getTemplateArgsAsWritten();
2652   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2653                                             TemplArgInfo->RAngleLoc);
2654   if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2655                     TemplArgInfo->NumTemplateArgs,
2656                     InstTemplateArgs, TemplateArgs))
2657     return 0;
2658 
2659   // Check that the template argument list is well-formed for this
2660   // class template.
2661   SmallVector<TemplateArgument, 4> Converted;
2662   if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2663                                         PartialSpec->getLocation(),
2664                                         InstTemplateArgs,
2665                                         false,
2666                                         Converted))
2667     return 0;
2668 
2669   // Figure out where to insert this class template partial specialization
2670   // in the member template's set of class template partial specializations.
2671   void *InsertPos = 0;
2672   ClassTemplateSpecializationDecl *PrevDecl
2673     = ClassTemplate->findPartialSpecialization(Converted.data(),
2674                                                Converted.size(), InsertPos);
2675 
2676   // Build the canonical type that describes the converted template
2677   // arguments of the class template partial specialization.
2678   QualType CanonType
2679     = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2680                                                     Converted.data(),
2681                                                     Converted.size());
2682 
2683   // Build the fully-sugared type for this class template
2684   // specialization as the user wrote in the specialization
2685   // itself. This means that we'll pretty-print the type retrieved
2686   // from the specialization's declaration the way that the user
2687   // actually wrote the specialization, rather than formatting the
2688   // name based on the "canonical" representation used to store the
2689   // template arguments in the specialization.
2690   TypeSourceInfo *WrittenTy
2691     = SemaRef.Context.getTemplateSpecializationTypeInfo(
2692                                                     TemplateName(ClassTemplate),
2693                                                     PartialSpec->getLocation(),
2694                                                     InstTemplateArgs,
2695                                                     CanonType);
2696 
2697   if (PrevDecl) {
2698     // We've already seen a partial specialization with the same template
2699     // parameters and template arguments. This can happen, for example, when
2700     // substituting the outer template arguments ends up causing two
2701     // class template partial specializations of a member class template
2702     // to have identical forms, e.g.,
2703     //
2704     //   template<typename T, typename U>
2705     //   struct Outer {
2706     //     template<typename X, typename Y> struct Inner;
2707     //     template<typename Y> struct Inner<T, Y>;
2708     //     template<typename Y> struct Inner<U, Y>;
2709     //   };
2710     //
2711     //   Outer<int, int> outer; // error: the partial specializations of Inner
2712     //                          // have the same signature.
2713     SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2714       << WrittenTy->getType();
2715     SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2716       << SemaRef.Context.getTypeDeclType(PrevDecl);
2717     return 0;
2718   }
2719 
2720 
2721   // Create the class template partial specialization declaration.
2722   ClassTemplatePartialSpecializationDecl *InstPartialSpec
2723     = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2724                                                      PartialSpec->getTagKind(),
2725                                                      Owner,
2726                                                      PartialSpec->getLocStart(),
2727                                                      PartialSpec->getLocation(),
2728                                                      InstParams,
2729                                                      ClassTemplate,
2730                                                      Converted.data(),
2731                                                      Converted.size(),
2732                                                      InstTemplateArgs,
2733                                                      CanonType,
2734                                                      0);
2735   // Substitute the nested name specifier, if any.
2736   if (SubstQualifier(PartialSpec, InstPartialSpec))
2737     return 0;
2738 
2739   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2740   InstPartialSpec->setTypeAsWritten(WrittenTy);
2741 
2742   // Add this partial specialization to the set of class template partial
2743   // specializations.
2744   ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2745   return InstPartialSpec;
2746 }
2747 
2748 /// \brief Instantiate the declaration of a variable template partial
2749 /// specialization.
2750 ///
2751 /// \param VarTemplate the (instantiated) variable template that is partially
2752 /// specialized by the instantiation of \p PartialSpec.
2753 ///
2754 /// \param PartialSpec the (uninstantiated) variable template partial
2755 /// specialization that we are instantiating.
2756 ///
2757 /// \returns The instantiated partial specialization, if successful; otherwise,
2758 /// NULL to indicate an error.
2759 VarTemplatePartialSpecializationDecl *
2760 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2761     VarTemplateDecl *VarTemplate,
2762     VarTemplatePartialSpecializationDecl *PartialSpec) {
2763   // Create a local instantiation scope for this variable template partial
2764   // specialization, which will contain the instantiations of the template
2765   // parameters.
2766   LocalInstantiationScope Scope(SemaRef);
2767 
2768   // Substitute into the template parameters of the variable template partial
2769   // specialization.
2770   TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2771   TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2772   if (!InstParams)
2773     return 0;
2774 
2775   // Substitute into the template arguments of the variable template partial
2776   // specialization.
2777   const ASTTemplateArgumentListInfo *TemplArgInfo
2778     = PartialSpec->getTemplateArgsAsWritten();
2779   TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2780                                             TemplArgInfo->RAngleLoc);
2781   if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2782                     TemplArgInfo->NumTemplateArgs,
2783                     InstTemplateArgs, TemplateArgs))
2784     return 0;
2785 
2786   // Check that the template argument list is well-formed for this
2787   // class template.
2788   SmallVector<TemplateArgument, 4> Converted;
2789   if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2790                                         InstTemplateArgs, false, Converted))
2791     return 0;
2792 
2793   // Figure out where to insert this variable template partial specialization
2794   // in the member template's set of variable template partial specializations.
2795   void *InsertPos = 0;
2796   VarTemplateSpecializationDecl *PrevDecl =
2797       VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2798                                              InsertPos);
2799 
2800   // Build the canonical type that describes the converted template
2801   // arguments of the variable template partial specialization.
2802   QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2803       TemplateName(VarTemplate), Converted.data(), Converted.size());
2804 
2805   // Build the fully-sugared type for this variable template
2806   // specialization as the user wrote in the specialization
2807   // itself. This means that we'll pretty-print the type retrieved
2808   // from the specialization's declaration the way that the user
2809   // actually wrote the specialization, rather than formatting the
2810   // name based on the "canonical" representation used to store the
2811   // template arguments in the specialization.
2812   TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2813       TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2814       CanonType);
2815 
2816   if (PrevDecl) {
2817     // We've already seen a partial specialization with the same template
2818     // parameters and template arguments. This can happen, for example, when
2819     // substituting the outer template arguments ends up causing two
2820     // variable template partial specializations of a member variable template
2821     // to have identical forms, e.g.,
2822     //
2823     //   template<typename T, typename U>
2824     //   struct Outer {
2825     //     template<typename X, typename Y> pair<X,Y> p;
2826     //     template<typename Y> pair<T, Y> p;
2827     //     template<typename Y> pair<U, Y> p;
2828     //   };
2829     //
2830     //   Outer<int, int> outer; // error: the partial specializations of Inner
2831     //                          // have the same signature.
2832     SemaRef.Diag(PartialSpec->getLocation(),
2833                  diag::err_var_partial_spec_redeclared)
2834         << WrittenTy->getType();
2835     SemaRef.Diag(PrevDecl->getLocation(),
2836                  diag::note_var_prev_partial_spec_here);
2837     return 0;
2838   }
2839 
2840   // Do substitution on the type of the declaration
2841   TypeSourceInfo *DI = SemaRef.SubstType(
2842       PartialSpec->getTypeSourceInfo(), TemplateArgs,
2843       PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2844   if (!DI)
2845     return 0;
2846 
2847   if (DI->getType()->isFunctionType()) {
2848     SemaRef.Diag(PartialSpec->getLocation(),
2849                  diag::err_variable_instantiates_to_function)
2850         << PartialSpec->isStaticDataMember() << DI->getType();
2851     return 0;
2852   }
2853 
2854   // Create the variable template partial specialization declaration.
2855   VarTemplatePartialSpecializationDecl *InstPartialSpec =
2856       VarTemplatePartialSpecializationDecl::Create(
2857           SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2858           PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2859           DI, PartialSpec->getStorageClass(), Converted.data(),
2860           Converted.size(), InstTemplateArgs);
2861 
2862   // Substitute the nested name specifier, if any.
2863   if (SubstQualifier(PartialSpec, InstPartialSpec))
2864     return 0;
2865 
2866   InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2867   InstPartialSpec->setTypeAsWritten(WrittenTy);
2868 
2869   // Add this partial specialization to the set of variable template partial
2870   // specializations. The instantiation of the initializer is not necessary.
2871   VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
2872 
2873   SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
2874                                      LateAttrs, Owner, StartingScope);
2875 
2876   return InstPartialSpec;
2877 }
2878 
2879 TypeSourceInfo*
2880 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2881                               SmallVectorImpl<ParmVarDecl *> &Params) {
2882   TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2883   assert(OldTInfo && "substituting function without type source info");
2884   assert(Params.empty() && "parameter vector is non-empty at start");
2885 
2886   CXXRecordDecl *ThisContext = 0;
2887   unsigned ThisTypeQuals = 0;
2888   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2889     ThisContext = cast<CXXRecordDecl>(Owner);
2890     ThisTypeQuals = Method->getTypeQualifiers();
2891   }
2892 
2893   TypeSourceInfo *NewTInfo
2894     = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2895                                     D->getTypeSpecStartLoc(),
2896                                     D->getDeclName(),
2897                                     ThisContext, ThisTypeQuals);
2898   if (!NewTInfo)
2899     return 0;
2900 
2901   TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2902   if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2903     if (NewTInfo != OldTInfo) {
2904       // Get parameters from the new type info.
2905       TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2906       FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
2907       unsigned NewIdx = 0;
2908       for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
2909            OldIdx != NumOldParams; ++OldIdx) {
2910         ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
2911         LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2912 
2913         Optional<unsigned> NumArgumentsInExpansion;
2914         if (OldParam->isParameterPack())
2915           NumArgumentsInExpansion =
2916               SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2917                                                  TemplateArgs);
2918         if (!NumArgumentsInExpansion) {
2919           // Simple case: normal parameter, or a parameter pack that's
2920           // instantiated to a (still-dependent) parameter pack.
2921           ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
2922           Params.push_back(NewParam);
2923           Scope->InstantiatedLocal(OldParam, NewParam);
2924         } else {
2925           // Parameter pack expansion: make the instantiation an argument pack.
2926           Scope->MakeInstantiatedLocalArgPack(OldParam);
2927           for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
2928             ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
2929             Params.push_back(NewParam);
2930             Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2931           }
2932         }
2933       }
2934     } else {
2935       // The function type itself was not dependent and therefore no
2936       // substitution occurred. However, we still need to instantiate
2937       // the function parameters themselves.
2938       const FunctionProtoType *OldProto =
2939           cast<FunctionProtoType>(OldProtoLoc.getType());
2940       for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
2941            ++i) {
2942         ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
2943         if (!OldParam) {
2944           Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2945               D, D->getLocation(), OldProto->getParamType(i)));
2946           continue;
2947         }
2948 
2949         ParmVarDecl *Parm =
2950             cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
2951         if (!Parm)
2952           return 0;
2953         Params.push_back(Parm);
2954       }
2955     }
2956   } else {
2957     // If the type of this function, after ignoring parentheses, is not
2958     // *directly* a function type, then we're instantiating a function that
2959     // was declared via a typedef or with attributes, e.g.,
2960     //
2961     //   typedef int functype(int, int);
2962     //   functype func;
2963     //   int __cdecl meth(int, int);
2964     //
2965     // In this case, we'll just go instantiate the ParmVarDecls that we
2966     // synthesized in the method declaration.
2967     SmallVector<QualType, 4> ParamTypes;
2968     if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2969                                D->getNumParams(), TemplateArgs, ParamTypes,
2970                                &Params))
2971       return 0;
2972   }
2973 
2974   return NewTInfo;
2975 }
2976 
2977 /// Introduce the instantiated function parameters into the local
2978 /// instantiation scope, and set the parameter names to those used
2979 /// in the template.
2980 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2981                                              const FunctionDecl *PatternDecl,
2982                                              LocalInstantiationScope &Scope,
2983                            const MultiLevelTemplateArgumentList &TemplateArgs) {
2984   unsigned FParamIdx = 0;
2985   for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2986     const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2987     if (!PatternParam->isParameterPack()) {
2988       // Simple case: not a parameter pack.
2989       assert(FParamIdx < Function->getNumParams());
2990       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2991       // If the parameter's type is not dependent, update it to match the type
2992       // in the pattern. They can differ in top-level cv-qualifiers, and we want
2993       // the pattern's type here. If the type is dependent, they can't differ,
2994       // per core issue 1668.
2995       // FIXME: Updating the type to work around this is at best fragile.
2996       if (!PatternDecl->getType()->isDependentType())
2997         FunctionParam->setType(PatternParam->getType());
2998 
2999       FunctionParam->setDeclName(PatternParam->getDeclName());
3000       Scope.InstantiatedLocal(PatternParam, FunctionParam);
3001       ++FParamIdx;
3002       continue;
3003     }
3004 
3005     // Expand the parameter pack.
3006     Scope.MakeInstantiatedLocalArgPack(PatternParam);
3007     Optional<unsigned> NumArgumentsInExpansion
3008       = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3009     assert(NumArgumentsInExpansion &&
3010            "should only be called when all template arguments are known");
3011     for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3012       ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3013       if (!PatternDecl->getType()->isDependentType())
3014         FunctionParam->setType(PatternParam->getType());
3015 
3016       FunctionParam->setDeclName(PatternParam->getDeclName());
3017       Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3018       ++FParamIdx;
3019     }
3020   }
3021 }
3022 
3023 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
3024                                      const FunctionProtoType *Proto,
3025                            const MultiLevelTemplateArgumentList &TemplateArgs) {
3026   assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
3027 
3028   // C++11 [expr.prim.general]p3:
3029   //   If a declaration declares a member function or member function
3030   //   template of a class X, the expression this is a prvalue of type
3031   //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3032   //   and the end of the function-definition, member-declarator, or
3033   //   declarator.
3034   CXXRecordDecl *ThisContext = 0;
3035   unsigned ThisTypeQuals = 0;
3036   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
3037     ThisContext = Method->getParent();
3038     ThisTypeQuals = Method->getTypeQualifiers();
3039   }
3040   Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
3041                                    SemaRef.getLangOpts().CPlusPlus11);
3042 
3043   // The function has an exception specification or a "noreturn"
3044   // attribute. Substitute into each of the exception types.
3045   SmallVector<QualType, 4> Exceptions;
3046   for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
3047     // FIXME: Poor location information!
3048     if (const PackExpansionType *PackExpansion
3049           = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
3050       // We have a pack expansion. Instantiate it.
3051       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3052       SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
3053                                               Unexpanded);
3054       assert(!Unexpanded.empty() &&
3055              "Pack expansion without parameter packs?");
3056 
3057       bool Expand = false;
3058       bool RetainExpansion = false;
3059       Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
3060       if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
3061                                                   SourceRange(),
3062                                                   Unexpanded,
3063                                                   TemplateArgs,
3064                                                   Expand,
3065                                                   RetainExpansion,
3066                                                   NumExpansions))
3067         break;
3068 
3069       if (!Expand) {
3070         // We can't expand this pack expansion into separate arguments yet;
3071         // just substitute into the pattern and create a new pack expansion
3072         // type.
3073         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3074         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3075                                        TemplateArgs,
3076                                      New->getLocation(), New->getDeclName());
3077         if (T.isNull())
3078           break;
3079 
3080         T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
3081         Exceptions.push_back(T);
3082         continue;
3083       }
3084 
3085       // Substitute into the pack expansion pattern for each template
3086       bool Invalid = false;
3087       for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
3088         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
3089 
3090         QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3091                                        TemplateArgs,
3092                                      New->getLocation(), New->getDeclName());
3093         if (T.isNull()) {
3094           Invalid = true;
3095           break;
3096         }
3097 
3098         Exceptions.push_back(T);
3099       }
3100 
3101       if (Invalid)
3102         break;
3103 
3104       continue;
3105     }
3106 
3107     QualType T
3108       = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
3109                           New->getLocation(), New->getDeclName());
3110     if (T.isNull() ||
3111         SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
3112       continue;
3113 
3114     Exceptions.push_back(T);
3115   }
3116   Expr *NoexceptExpr = 0;
3117   if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
3118     EnterExpressionEvaluationContext Unevaluated(SemaRef,
3119                                                  Sema::ConstantEvaluated);
3120     ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
3121     if (E.isUsable())
3122       E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
3123 
3124     if (E.isUsable()) {
3125       NoexceptExpr = E.take();
3126       if (!NoexceptExpr->isTypeDependent() &&
3127           !NoexceptExpr->isValueDependent())
3128         NoexceptExpr
3129           = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
3130               0, diag::err_noexcept_needs_constant_expression,
3131               /*AllowFold*/ false).take();
3132     }
3133   }
3134 
3135   FunctionProtoType::ExtProtoInfo EPI;
3136   EPI.ExceptionSpecType = Proto->getExceptionSpecType();
3137   EPI.NumExceptions = Exceptions.size();
3138   EPI.Exceptions = Exceptions.data();
3139   EPI.NoexceptExpr = NoexceptExpr;
3140 
3141   SemaRef.UpdateExceptionSpec(New, EPI);
3142 }
3143 
3144 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3145                                     FunctionDecl *Decl) {
3146   const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3147   if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3148     return;
3149 
3150   InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3151                              InstantiatingTemplate::ExceptionSpecification());
3152   if (Inst.isInvalid()) {
3153     // We hit the instantiation depth limit. Clear the exception specification
3154     // so that our callers don't have to cope with EST_Uninstantiated.
3155     FunctionProtoType::ExtProtoInfo EPI;
3156     EPI.ExceptionSpecType = EST_None;
3157     UpdateExceptionSpec(Decl, EPI);
3158     return;
3159   }
3160 
3161   // Enter the scope of this instantiation. We don't use
3162   // PushDeclContext because we don't have a scope.
3163   Sema::ContextRAII savedContext(*this, Decl);
3164   LocalInstantiationScope Scope(*this);
3165 
3166   MultiLevelTemplateArgumentList TemplateArgs =
3167     getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
3168 
3169   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3170   addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
3171 
3172   ::InstantiateExceptionSpec(*this, Decl,
3173                              Template->getType()->castAs<FunctionProtoType>(),
3174                              TemplateArgs);
3175 }
3176 
3177 /// \brief Initializes the common fields of an instantiation function
3178 /// declaration (New) from the corresponding fields of its template (Tmpl).
3179 ///
3180 /// \returns true if there was an error
3181 bool
3182 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3183                                                     FunctionDecl *Tmpl) {
3184   if (Tmpl->isDeleted())
3185     New->setDeletedAsWritten();
3186 
3187   // Forward the mangling number from the template to the instantiated decl.
3188   SemaRef.Context.setManglingNumber(New,
3189                                     SemaRef.Context.getManglingNumber(Tmpl));
3190 
3191   // If we are performing substituting explicitly-specified template arguments
3192   // or deduced template arguments into a function template and we reach this
3193   // point, we are now past the point where SFINAE applies and have committed
3194   // to keeping the new function template specialization. We therefore
3195   // convert the active template instantiation for the function template
3196   // into a template instantiation for this specific function template
3197   // specialization, which is not a SFINAE context, so that we diagnose any
3198   // further errors in the declaration itself.
3199   typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3200   ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3201   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3202       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3203     if (FunctionTemplateDecl *FunTmpl
3204           = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3205       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3206              "Deduction from the wrong function template?");
3207       (void) FunTmpl;
3208       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3209       ActiveInst.Entity = New;
3210     }
3211   }
3212 
3213   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3214   assert(Proto && "Function template without prototype?");
3215 
3216   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3217     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3218 
3219     // DR1330: In C++11, defer instantiation of a non-trivial
3220     // exception specification.
3221     if (SemaRef.getLangOpts().CPlusPlus11 &&
3222         EPI.ExceptionSpecType != EST_None &&
3223         EPI.ExceptionSpecType != EST_DynamicNone &&
3224         EPI.ExceptionSpecType != EST_BasicNoexcept) {
3225       FunctionDecl *ExceptionSpecTemplate = Tmpl;
3226       if (EPI.ExceptionSpecType == EST_Uninstantiated)
3227         ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
3228       ExceptionSpecificationType NewEST = EST_Uninstantiated;
3229       if (EPI.ExceptionSpecType == EST_Unevaluated)
3230         NewEST = EST_Unevaluated;
3231 
3232       // Mark the function has having an uninstantiated exception specification.
3233       const FunctionProtoType *NewProto
3234         = New->getType()->getAs<FunctionProtoType>();
3235       assert(NewProto && "Template instantiation without function prototype?");
3236       EPI = NewProto->getExtProtoInfo();
3237       EPI.ExceptionSpecType = NewEST;
3238       EPI.ExceptionSpecDecl = New;
3239       EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
3240       New->setType(SemaRef.Context.getFunctionType(
3241           NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3242     } else {
3243       ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3244     }
3245   }
3246 
3247   // Get the definition. Leaves the variable unchanged if undefined.
3248   const FunctionDecl *Definition = Tmpl;
3249   Tmpl->isDefined(Definition);
3250 
3251   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3252                            LateAttrs, StartingScope);
3253 
3254   return false;
3255 }
3256 
3257 /// \brief Initializes common fields of an instantiated method
3258 /// declaration (New) from the corresponding fields of its template
3259 /// (Tmpl).
3260 ///
3261 /// \returns true if there was an error
3262 bool
3263 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3264                                                   CXXMethodDecl *Tmpl) {
3265   if (InitFunctionInstantiation(New, Tmpl))
3266     return true;
3267 
3268   New->setAccess(Tmpl->getAccess());
3269   if (Tmpl->isVirtualAsWritten())
3270     New->setVirtualAsWritten(true);
3271 
3272   // FIXME: New needs a pointer to Tmpl
3273   return false;
3274 }
3275 
3276 /// \brief Instantiate the definition of the given function from its
3277 /// template.
3278 ///
3279 /// \param PointOfInstantiation the point at which the instantiation was
3280 /// required. Note that this is not precisely a "point of instantiation"
3281 /// for the function, but it's close.
3282 ///
3283 /// \param Function the already-instantiated declaration of a
3284 /// function template specialization or member function of a class template
3285 /// specialization.
3286 ///
3287 /// \param Recursive if true, recursively instantiates any functions that
3288 /// are required by this instantiation.
3289 ///
3290 /// \param DefinitionRequired if true, then we are performing an explicit
3291 /// instantiation where the body of the function is required. Complain if
3292 /// there is no such body.
3293 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3294                                          FunctionDecl *Function,
3295                                          bool Recursive,
3296                                          bool DefinitionRequired) {
3297   if (Function->isInvalidDecl() || Function->isDefined())
3298     return;
3299 
3300   // Never instantiate an explicit specialization except if it is a class scope
3301   // explicit specialization.
3302   if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3303       !Function->getClassScopeSpecializationPattern())
3304     return;
3305 
3306   // Find the function body that we'll be substituting.
3307   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3308   assert(PatternDecl && "instantiating a non-template");
3309 
3310   Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3311   assert(PatternDecl && "template definition is not a template");
3312   if (!Pattern) {
3313     // Try to find a defaulted definition
3314     PatternDecl->isDefined(PatternDecl);
3315   }
3316   assert(PatternDecl && "template definition is not a template");
3317 
3318   // Postpone late parsed template instantiations.
3319   if (PatternDecl->isLateTemplateParsed() &&
3320       !LateTemplateParser) {
3321     PendingInstantiations.push_back(
3322       std::make_pair(Function, PointOfInstantiation));
3323     return;
3324   }
3325 
3326   // Call the LateTemplateParser callback if there is a need to late parse
3327   // a templated function definition.
3328   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3329       LateTemplateParser) {
3330     // FIXME: Optimize to allow individual templates to be deserialized.
3331     if (PatternDecl->isFromASTFile())
3332       ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3333 
3334     LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3335     assert(LPT && "missing LateParsedTemplate");
3336     LateTemplateParser(OpaqueParser, *LPT);
3337     Pattern = PatternDecl->getBody(PatternDecl);
3338   }
3339 
3340   if (!Pattern && !PatternDecl->isDefaulted()) {
3341     if (DefinitionRequired) {
3342       if (Function->getPrimaryTemplate())
3343         Diag(PointOfInstantiation,
3344              diag::err_explicit_instantiation_undefined_func_template)
3345           << Function->getPrimaryTemplate();
3346       else
3347         Diag(PointOfInstantiation,
3348              diag::err_explicit_instantiation_undefined_member)
3349           << 1 << Function->getDeclName() << Function->getDeclContext();
3350 
3351       if (PatternDecl)
3352         Diag(PatternDecl->getLocation(),
3353              diag::note_explicit_instantiation_here);
3354       Function->setInvalidDecl();
3355     } else if (Function->getTemplateSpecializationKind()
3356                  == TSK_ExplicitInstantiationDefinition) {
3357       PendingInstantiations.push_back(
3358         std::make_pair(Function, PointOfInstantiation));
3359     }
3360 
3361     return;
3362   }
3363 
3364   // C++1y [temp.explicit]p10:
3365   //   Except for inline functions, declarations with types deduced from their
3366   //   initializer or return value, and class template specializations, other
3367   //   explicit instantiation declarations have the effect of suppressing the
3368   //   implicit instantiation of the entity to which they refer.
3369   if (Function->getTemplateSpecializationKind() ==
3370           TSK_ExplicitInstantiationDeclaration &&
3371       !PatternDecl->isInlined() &&
3372       !PatternDecl->getReturnType()->getContainedAutoType())
3373     return;
3374 
3375   if (PatternDecl->isInlined())
3376     Function->setImplicitlyInline();
3377 
3378   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3379   if (Inst.isInvalid())
3380     return;
3381 
3382   // Copy the inner loc start from the pattern.
3383   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3384 
3385   // If we're performing recursive template instantiation, create our own
3386   // queue of pending implicit instantiations that we will instantiate later,
3387   // while we're still within our own instantiation context.
3388   SmallVector<VTableUse, 16> SavedVTableUses;
3389   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3390   SavePendingLocalImplicitInstantiationsRAII
3391       SavedPendingLocalImplicitInstantiations(*this);
3392   if (Recursive) {
3393     VTableUses.swap(SavedVTableUses);
3394     PendingInstantiations.swap(SavedPendingInstantiations);
3395   }
3396 
3397   EnterExpressionEvaluationContext EvalContext(*this,
3398                                                Sema::PotentiallyEvaluated);
3399 
3400   // Introduce a new scope where local variable instantiations will be
3401   // recorded, unless we're actually a member function within a local
3402   // class, in which case we need to merge our results with the parent
3403   // scope (of the enclosing function).
3404   bool MergeWithParentScope = false;
3405   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3406     MergeWithParentScope = Rec->isLocalClass();
3407 
3408   LocalInstantiationScope Scope(*this, MergeWithParentScope);
3409 
3410   if (PatternDecl->isDefaulted())
3411     SetDeclDefaulted(Function, PatternDecl->getLocation());
3412   else {
3413     ActOnStartOfFunctionDef(0, Function);
3414 
3415     // Enter the scope of this instantiation. We don't use
3416     // PushDeclContext because we don't have a scope.
3417     Sema::ContextRAII savedContext(*this, Function);
3418 
3419     MultiLevelTemplateArgumentList TemplateArgs =
3420       getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3421 
3422     addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3423                                      TemplateArgs);
3424 
3425     // If this is a constructor, instantiate the member initializers.
3426     if (const CXXConstructorDecl *Ctor =
3427           dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3428       InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3429                                  TemplateArgs);
3430     }
3431 
3432     // Instantiate the function body.
3433     StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3434 
3435     if (Body.isInvalid())
3436       Function->setInvalidDecl();
3437 
3438     ActOnFinishFunctionBody(Function, Body.get(),
3439                             /*IsInstantiation=*/true);
3440 
3441     PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3442 
3443     if (auto *Listener = getASTMutationListener())
3444       Listener->FunctionDefinitionInstantiated(Function);
3445 
3446     savedContext.pop();
3447   }
3448 
3449   DeclGroupRef DG(Function);
3450   Consumer.HandleTopLevelDecl(DG);
3451 
3452   // This class may have local implicit instantiations that need to be
3453   // instantiation within this scope.
3454   PerformPendingInstantiations(/*LocalOnly=*/true);
3455   Scope.Exit();
3456 
3457   if (Recursive) {
3458     // Define any pending vtables.
3459     DefineUsedVTables();
3460 
3461     // Instantiate any pending implicit instantiations found during the
3462     // instantiation of this template.
3463     PerformPendingInstantiations();
3464 
3465     // Restore the set of pending vtables.
3466     assert(VTableUses.empty() &&
3467            "VTableUses should be empty before it is discarded.");
3468     VTableUses.swap(SavedVTableUses);
3469 
3470     // Restore the set of pending implicit instantiations.
3471     assert(PendingInstantiations.empty() &&
3472            "PendingInstantiations should be empty before it is discarded.");
3473     PendingInstantiations.swap(SavedPendingInstantiations);
3474   }
3475 }
3476 
3477 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3478     VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3479     const TemplateArgumentList &TemplateArgList,
3480     const TemplateArgumentListInfo &TemplateArgsInfo,
3481     SmallVectorImpl<TemplateArgument> &Converted,
3482     SourceLocation PointOfInstantiation, void *InsertPos,
3483     LateInstantiatedAttrVec *LateAttrs,
3484     LocalInstantiationScope *StartingScope) {
3485   if (FromVar->isInvalidDecl())
3486     return 0;
3487 
3488   InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3489   if (Inst.isInvalid())
3490     return 0;
3491 
3492   MultiLevelTemplateArgumentList TemplateArgLists;
3493   TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3494 
3495   // Instantiate the first declaration of the variable template: for a partial
3496   // specialization of a static data member template, the first declaration may
3497   // or may not be the declaration in the class; if it's in the class, we want
3498   // to instantiate a member in the class (a declaration), and if it's outside,
3499   // we want to instantiate a definition.
3500   //
3501   // If we're instantiating an explicitly-specialized member template or member
3502   // partial specialization, don't do this. The member specialization completely
3503   // replaces the original declaration in this case.
3504   bool IsMemberSpec = false;
3505   if (VarTemplatePartialSpecializationDecl *PartialSpec =
3506           dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3507     IsMemberSpec = PartialSpec->isMemberSpecialization();
3508   else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3509     IsMemberSpec = FromTemplate->isMemberSpecialization();
3510   if (!IsMemberSpec)
3511     FromVar = FromVar->getFirstDecl();
3512 
3513   MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3514   TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3515                                         MultiLevelList);
3516 
3517   // TODO: Set LateAttrs and StartingScope ...
3518 
3519   return cast_or_null<VarTemplateSpecializationDecl>(
3520       Instantiator.VisitVarTemplateSpecializationDecl(
3521           VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3522 }
3523 
3524 /// \brief Instantiates a variable template specialization by completing it
3525 /// with appropriate type information and initializer.
3526 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3527     VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3528     const MultiLevelTemplateArgumentList &TemplateArgs) {
3529 
3530   // Do substitution on the type of the declaration
3531   TypeSourceInfo *DI =
3532       SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3533                 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3534   if (!DI)
3535     return 0;
3536 
3537   // Update the type of this variable template specialization.
3538   VarSpec->setType(DI->getType());
3539 
3540   // Instantiate the initializer.
3541   InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3542 
3543   return VarSpec;
3544 }
3545 
3546 /// BuildVariableInstantiation - Used after a new variable has been created.
3547 /// Sets basic variable data and decides whether to postpone the
3548 /// variable instantiation.
3549 void Sema::BuildVariableInstantiation(
3550     VarDecl *NewVar, VarDecl *OldVar,
3551     const MultiLevelTemplateArgumentList &TemplateArgs,
3552     LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3553     LocalInstantiationScope *StartingScope,
3554     bool InstantiatingVarTemplate) {
3555 
3556   // If we are instantiating a local extern declaration, the
3557   // instantiation belongs lexically to the containing function.
3558   // If we are instantiating a static data member defined
3559   // out-of-line, the instantiation will have the same lexical
3560   // context (which will be a namespace scope) as the template.
3561   if (OldVar->isLocalExternDecl()) {
3562     NewVar->setLocalExternDecl();
3563     NewVar->setLexicalDeclContext(Owner);
3564   } else if (OldVar->isOutOfLine())
3565     NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3566   NewVar->setTSCSpec(OldVar->getTSCSpec());
3567   NewVar->setInitStyle(OldVar->getInitStyle());
3568   NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3569   NewVar->setConstexpr(OldVar->isConstexpr());
3570   NewVar->setInitCapture(OldVar->isInitCapture());
3571   NewVar->setPreviousDeclInSameBlockScope(
3572       OldVar->isPreviousDeclInSameBlockScope());
3573   NewVar->setAccess(OldVar->getAccess());
3574 
3575   if (!OldVar->isStaticDataMember()) {
3576     if (OldVar->isUsed(false))
3577       NewVar->setIsUsed();
3578     NewVar->setReferenced(OldVar->isReferenced());
3579   }
3580 
3581   // See if the old variable had a type-specifier that defined an anonymous tag.
3582   // If it did, mark the new variable as being the declarator for the new
3583   // anonymous tag.
3584   if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3585     TagDecl *OldTag = OldTagType->getDecl();
3586     if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3587       TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3588       assert(!NewTag->hasNameForLinkage() &&
3589              !NewTag->hasDeclaratorForAnonDecl());
3590       NewTag->setDeclaratorForAnonDecl(NewVar);
3591     }
3592   }
3593 
3594   InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3595 
3596   LookupResult Previous(
3597       *this, NewVar->getDeclName(), NewVar->getLocation(),
3598       NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3599                                   : Sema::LookupOrdinaryName,
3600       Sema::ForRedeclaration);
3601 
3602   if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3603       (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3604        OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
3605     // We have a previous declaration. Use that one, so we merge with the
3606     // right type.
3607     if (NamedDecl *NewPrev = FindInstantiatedDecl(
3608             NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3609       Previous.addDecl(NewPrev);
3610   } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3611              OldVar->hasLinkage())
3612     LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3613   CheckVariableDeclaration(NewVar, Previous);
3614 
3615   if (!InstantiatingVarTemplate) {
3616     NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3617     if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3618       NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3619   }
3620 
3621   if (!OldVar->isOutOfLine()) {
3622     if (NewVar->getDeclContext()->isFunctionOrMethod())
3623       CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3624   }
3625 
3626   // Link instantiations of static data members back to the template from
3627   // which they were instantiated.
3628   if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3629     NewVar->setInstantiationOfStaticDataMember(OldVar,
3630                                                TSK_ImplicitInstantiation);
3631 
3632   // Forward the mangling number from the template to the instantiated decl.
3633   Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
3634   Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
3635 
3636   // Delay instantiation of the initializer for variable templates until a
3637   // definition of the variable is needed. We need it right away if the type
3638   // contains 'auto'.
3639   if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3640        !InstantiatingVarTemplate) ||
3641       NewVar->getType()->isUndeducedType())
3642     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3643 
3644   // Diagnose unused local variables with dependent types, where the diagnostic
3645   // will have been deferred.
3646   if (!NewVar->isInvalidDecl() &&
3647       NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3648       OldVar->getType()->isDependentType())
3649     DiagnoseUnusedDecl(NewVar);
3650 }
3651 
3652 /// \brief Instantiate the initializer of a variable.
3653 void Sema::InstantiateVariableInitializer(
3654     VarDecl *Var, VarDecl *OldVar,
3655     const MultiLevelTemplateArgumentList &TemplateArgs) {
3656 
3657   if (Var->getAnyInitializer())
3658     // We already have an initializer in the class.
3659     return;
3660 
3661   if (OldVar->getInit()) {
3662     if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3663       PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3664     else
3665       PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3666 
3667     // Instantiate the initializer.
3668     ExprResult Init =
3669         SubstInitializer(OldVar->getInit(), TemplateArgs,
3670                          OldVar->getInitStyle() == VarDecl::CallInit);
3671     if (!Init.isInvalid()) {
3672       bool TypeMayContainAuto = true;
3673       if (Init.get()) {
3674         bool DirectInit = OldVar->isDirectInit();
3675         AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3676       } else
3677         ActOnUninitializedDecl(Var, TypeMayContainAuto);
3678     } else {
3679       // FIXME: Not too happy about invalidating the declaration
3680       // because of a bogus initializer.
3681       Var->setInvalidDecl();
3682     }
3683 
3684     PopExpressionEvaluationContext();
3685   } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3686              !Var->isCXXForRangeDecl())
3687     ActOnUninitializedDecl(Var, false);
3688 }
3689 
3690 /// \brief Instantiate the definition of the given variable from its
3691 /// template.
3692 ///
3693 /// \param PointOfInstantiation the point at which the instantiation was
3694 /// required. Note that this is not precisely a "point of instantiation"
3695 /// for the function, but it's close.
3696 ///
3697 /// \param Var the already-instantiated declaration of a static member
3698 /// variable of a class template specialization.
3699 ///
3700 /// \param Recursive if true, recursively instantiates any functions that
3701 /// are required by this instantiation.
3702 ///
3703 /// \param DefinitionRequired if true, then we are performing an explicit
3704 /// instantiation where an out-of-line definition of the member variable
3705 /// is required. Complain if there is no such definition.
3706 void Sema::InstantiateStaticDataMemberDefinition(
3707                                           SourceLocation PointOfInstantiation,
3708                                                  VarDecl *Var,
3709                                                  bool Recursive,
3710                                                  bool DefinitionRequired) {
3711   InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3712                                 DefinitionRequired);
3713 }
3714 
3715 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3716                                          VarDecl *Var, bool Recursive,
3717                                          bool DefinitionRequired) {
3718   if (Var->isInvalidDecl())
3719     return;
3720 
3721   VarTemplateSpecializationDecl *VarSpec =
3722       dyn_cast<VarTemplateSpecializationDecl>(Var);
3723   VarDecl *PatternDecl = 0, *Def = 0;
3724   MultiLevelTemplateArgumentList TemplateArgs =
3725       getTemplateInstantiationArgs(Var);
3726 
3727   if (VarSpec) {
3728     // If this is a variable template specialization, make sure that it is
3729     // non-dependent, then find its instantiation pattern.
3730     bool InstantiationDependent = false;
3731     assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3732                VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3733            "Only instantiate variable template specializations that are "
3734            "not type-dependent");
3735     (void)InstantiationDependent;
3736 
3737     // Find the variable initialization that we'll be substituting. If the
3738     // pattern was instantiated from a member template, look back further to
3739     // find the real pattern.
3740     assert(VarSpec->getSpecializedTemplate() &&
3741            "Specialization without specialized template?");
3742     llvm::PointerUnion<VarTemplateDecl *,
3743                        VarTemplatePartialSpecializationDecl *> PatternPtr =
3744         VarSpec->getSpecializedTemplateOrPartial();
3745     if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
3746       VarTemplatePartialSpecializationDecl *Tmpl =
3747           PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3748       while (VarTemplatePartialSpecializationDecl *From =
3749                  Tmpl->getInstantiatedFromMember()) {
3750         if (Tmpl->isMemberSpecialization())
3751           break;
3752 
3753         Tmpl = From;
3754       }
3755       PatternDecl = Tmpl;
3756     } else {
3757       VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3758       while (VarTemplateDecl *From =
3759                  Tmpl->getInstantiatedFromMemberTemplate()) {
3760         if (Tmpl->isMemberSpecialization())
3761           break;
3762 
3763         Tmpl = From;
3764       }
3765       PatternDecl = Tmpl->getTemplatedDecl();
3766     }
3767 
3768     // If this is a static data member template, there might be an
3769     // uninstantiated initializer on the declaration. If so, instantiate
3770     // it now.
3771     if (PatternDecl->isStaticDataMember() &&
3772         (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
3773         !Var->hasInit()) {
3774       // FIXME: Factor out the duplicated instantiation context setup/tear down
3775       // code here.
3776       InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3777       if (Inst.isInvalid())
3778         return;
3779 
3780       // If we're performing recursive template instantiation, create our own
3781       // queue of pending implicit instantiations that we will instantiate
3782       // later, while we're still within our own instantiation context.
3783       SmallVector<VTableUse, 16> SavedVTableUses;
3784       std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3785       if (Recursive) {
3786         VTableUses.swap(SavedVTableUses);
3787         PendingInstantiations.swap(SavedPendingInstantiations);
3788       }
3789 
3790       LocalInstantiationScope Local(*this);
3791 
3792       // Enter the scope of this instantiation. We don't use
3793       // PushDeclContext because we don't have a scope.
3794       ContextRAII PreviousContext(*this, Var->getDeclContext());
3795       InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3796       PreviousContext.pop();
3797 
3798       // FIXME: Need to inform the ASTConsumer that we instantiated the
3799       // initializer?
3800 
3801       // This variable may have local implicit instantiations that need to be
3802       // instantiated within this scope.
3803       PerformPendingInstantiations(/*LocalOnly=*/true);
3804 
3805       Local.Exit();
3806 
3807       if (Recursive) {
3808         // Define any newly required vtables.
3809         DefineUsedVTables();
3810 
3811         // Instantiate any pending implicit instantiations found during the
3812         // instantiation of this template.
3813         PerformPendingInstantiations();
3814 
3815         // Restore the set of pending vtables.
3816         assert(VTableUses.empty() &&
3817                "VTableUses should be empty before it is discarded.");
3818         VTableUses.swap(SavedVTableUses);
3819 
3820         // Restore the set of pending implicit instantiations.
3821         assert(PendingInstantiations.empty() &&
3822                "PendingInstantiations should be empty before it is discarded.");
3823         PendingInstantiations.swap(SavedPendingInstantiations);
3824       }
3825     }
3826 
3827     // Find actual definition
3828     Def = PatternDecl->getDefinition(getASTContext());
3829   } else {
3830     // If this is a static data member, find its out-of-line definition.
3831     assert(Var->isStaticDataMember() && "not a static data member?");
3832     PatternDecl = Var->getInstantiatedFromStaticDataMember();
3833 
3834     assert(PatternDecl && "data member was not instantiated from a template?");
3835     assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3836     Def = PatternDecl->getOutOfLineDefinition();
3837   }
3838 
3839   // If we don't have a definition of the variable template, we won't perform
3840   // any instantiation. Rather, we rely on the user to instantiate this
3841   // definition (or provide a specialization for it) in another translation
3842   // unit.
3843   if (!Def) {
3844     if (DefinitionRequired) {
3845       if (VarSpec)
3846         Diag(PointOfInstantiation,
3847              diag::err_explicit_instantiation_undefined_var_template) << Var;
3848       else
3849         Diag(PointOfInstantiation,
3850              diag::err_explicit_instantiation_undefined_member)
3851             << 2 << Var->getDeclName() << Var->getDeclContext();
3852       Diag(PatternDecl->getLocation(),
3853            diag::note_explicit_instantiation_here);
3854       if (VarSpec)
3855         Var->setInvalidDecl();
3856     } else if (Var->getTemplateSpecializationKind()
3857                  == TSK_ExplicitInstantiationDefinition) {
3858       PendingInstantiations.push_back(
3859         std::make_pair(Var, PointOfInstantiation));
3860     }
3861 
3862     return;
3863   }
3864 
3865   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3866 
3867   // Never instantiate an explicit specialization.
3868   if (TSK == TSK_ExplicitSpecialization)
3869     return;
3870 
3871   // C++11 [temp.explicit]p10:
3872   //   Except for inline functions, [...] explicit instantiation declarations
3873   //   have the effect of suppressing the implicit instantiation of the entity
3874   //   to which they refer.
3875   if (TSK == TSK_ExplicitInstantiationDeclaration)
3876     return;
3877 
3878   // Make sure to pass the instantiated variable to the consumer at the end.
3879   struct PassToConsumerRAII {
3880     ASTConsumer &Consumer;
3881     VarDecl *Var;
3882 
3883     PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3884       : Consumer(Consumer), Var(Var) { }
3885 
3886     ~PassToConsumerRAII() {
3887       Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3888     }
3889   } PassToConsumerRAII(Consumer, Var);
3890 
3891   // If we already have a definition, we're done.
3892   if (VarDecl *Def = Var->getDefinition()) {
3893     // We may be explicitly instantiating something we've already implicitly
3894     // instantiated.
3895     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3896                                        PointOfInstantiation);
3897     return;
3898   }
3899 
3900   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3901   if (Inst.isInvalid())
3902     return;
3903 
3904   // If we're performing recursive template instantiation, create our own
3905   // queue of pending implicit instantiations that we will instantiate later,
3906   // while we're still within our own instantiation context.
3907   SmallVector<VTableUse, 16> SavedVTableUses;
3908   std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3909   SavePendingLocalImplicitInstantiationsRAII
3910       SavedPendingLocalImplicitInstantiations(*this);
3911   if (Recursive) {
3912     VTableUses.swap(SavedVTableUses);
3913     PendingInstantiations.swap(SavedPendingInstantiations);
3914   }
3915 
3916   // Enter the scope of this instantiation. We don't use
3917   // PushDeclContext because we don't have a scope.
3918   ContextRAII PreviousContext(*this, Var->getDeclContext());
3919   LocalInstantiationScope Local(*this);
3920 
3921   VarDecl *OldVar = Var;
3922   if (!VarSpec)
3923     Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3924                                           TemplateArgs));
3925   else if (Var->isStaticDataMember() &&
3926            Var->getLexicalDeclContext()->isRecord()) {
3927     // We need to instantiate the definition of a static data member template,
3928     // and all we have is the in-class declaration of it. Instantiate a separate
3929     // declaration of the definition.
3930     TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3931                                           TemplateArgs);
3932     Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3933         VarSpec->getSpecializedTemplate(), Def, 0,
3934         VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3935     if (Var) {
3936       llvm::PointerUnion<VarTemplateDecl *,
3937                          VarTemplatePartialSpecializationDecl *> PatternPtr =
3938           VarSpec->getSpecializedTemplateOrPartial();
3939       if (VarTemplatePartialSpecializationDecl *Partial =
3940           PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3941         cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3942             Partial, &VarSpec->getTemplateInstantiationArgs());
3943 
3944       // Merge the definition with the declaration.
3945       LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3946                      LookupOrdinaryName, ForRedeclaration);
3947       R.addDecl(OldVar);
3948       MergeVarDecl(Var, R);
3949 
3950       // Attach the initializer.
3951       InstantiateVariableInitializer(Var, Def, TemplateArgs);
3952     }
3953   } else
3954     // Complete the existing variable's definition with an appropriately
3955     // substituted type and initializer.
3956     Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
3957 
3958   PreviousContext.pop();
3959 
3960   if (Var) {
3961     PassToConsumerRAII.Var = Var;
3962     Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3963                                        OldVar->getPointOfInstantiation());
3964   }
3965 
3966   // This variable may have local implicit instantiations that need to be
3967   // instantiated within this scope.
3968   PerformPendingInstantiations(/*LocalOnly=*/true);
3969 
3970   Local.Exit();
3971 
3972   if (Recursive) {
3973     // Define any newly required vtables.
3974     DefineUsedVTables();
3975 
3976     // Instantiate any pending implicit instantiations found during the
3977     // instantiation of this template.
3978     PerformPendingInstantiations();
3979 
3980     // Restore the set of pending vtables.
3981     assert(VTableUses.empty() &&
3982            "VTableUses should be empty before it is discarded.");
3983     VTableUses.swap(SavedVTableUses);
3984 
3985     // Restore the set of pending implicit instantiations.
3986     assert(PendingInstantiations.empty() &&
3987            "PendingInstantiations should be empty before it is discarded.");
3988     PendingInstantiations.swap(SavedPendingInstantiations);
3989   }
3990 }
3991 
3992 void
3993 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3994                                  const CXXConstructorDecl *Tmpl,
3995                            const MultiLevelTemplateArgumentList &TemplateArgs) {
3996 
3997   SmallVector<CXXCtorInitializer*, 4> NewInits;
3998   bool AnyErrors = Tmpl->isInvalidDecl();
3999 
4000   // Instantiate all the initializers.
4001   for (const auto *Init : Tmpl->inits()) {
4002     // Only instantiate written initializers, let Sema re-construct implicit
4003     // ones.
4004     if (!Init->isWritten())
4005       continue;
4006 
4007     SourceLocation EllipsisLoc;
4008 
4009     if (Init->isPackExpansion()) {
4010       // This is a pack expansion. We should expand it now.
4011       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4012       SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4013       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4014       collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4015       bool ShouldExpand = false;
4016       bool RetainExpansion = false;
4017       Optional<unsigned> NumExpansions;
4018       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4019                                           BaseTL.getSourceRange(),
4020                                           Unexpanded,
4021                                           TemplateArgs, ShouldExpand,
4022                                           RetainExpansion,
4023                                           NumExpansions)) {
4024         AnyErrors = true;
4025         New->setInvalidDecl();
4026         continue;
4027       }
4028       assert(ShouldExpand && "Partial instantiation of base initializer?");
4029 
4030       // Loop over all of the arguments in the argument pack(s),
4031       for (unsigned I = 0; I != *NumExpansions; ++I) {
4032         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4033 
4034         // Instantiate the initializer.
4035         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4036                                                /*CXXDirectInit=*/true);
4037         if (TempInit.isInvalid()) {
4038           AnyErrors = true;
4039           break;
4040         }
4041 
4042         // Instantiate the base type.
4043         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4044                                               TemplateArgs,
4045                                               Init->getSourceLocation(),
4046                                               New->getDeclName());
4047         if (!BaseTInfo) {
4048           AnyErrors = true;
4049           break;
4050         }
4051 
4052         // Build the initializer.
4053         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4054                                                      BaseTInfo, TempInit.take(),
4055                                                      New->getParent(),
4056                                                      SourceLocation());
4057         if (NewInit.isInvalid()) {
4058           AnyErrors = true;
4059           break;
4060         }
4061 
4062         NewInits.push_back(NewInit.get());
4063       }
4064 
4065       continue;
4066     }
4067 
4068     // Instantiate the initializer.
4069     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4070                                            /*CXXDirectInit=*/true);
4071     if (TempInit.isInvalid()) {
4072       AnyErrors = true;
4073       continue;
4074     }
4075 
4076     MemInitResult NewInit;
4077     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4078       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4079                                         TemplateArgs,
4080                                         Init->getSourceLocation(),
4081                                         New->getDeclName());
4082       if (!TInfo) {
4083         AnyErrors = true;
4084         New->setInvalidDecl();
4085         continue;
4086       }
4087 
4088       if (Init->isBaseInitializer())
4089         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
4090                                        New->getParent(), EllipsisLoc);
4091       else
4092         NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
4093                                   cast<CXXRecordDecl>(CurContext->getParent()));
4094     } else if (Init->isMemberInitializer()) {
4095       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4096                                                      Init->getMemberLocation(),
4097                                                      Init->getMember(),
4098                                                      TemplateArgs));
4099       if (!Member) {
4100         AnyErrors = true;
4101         New->setInvalidDecl();
4102         continue;
4103       }
4104 
4105       NewInit = BuildMemberInitializer(Member, TempInit.take(),
4106                                        Init->getSourceLocation());
4107     } else if (Init->isIndirectMemberInitializer()) {
4108       IndirectFieldDecl *IndirectMember =
4109          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4110                                  Init->getMemberLocation(),
4111                                  Init->getIndirectMember(), TemplateArgs));
4112 
4113       if (!IndirectMember) {
4114         AnyErrors = true;
4115         New->setInvalidDecl();
4116         continue;
4117       }
4118 
4119       NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
4120                                        Init->getSourceLocation());
4121     }
4122 
4123     if (NewInit.isInvalid()) {
4124       AnyErrors = true;
4125       New->setInvalidDecl();
4126     } else {
4127       NewInits.push_back(NewInit.get());
4128     }
4129   }
4130 
4131   // Assign all the initializers to the new constructor.
4132   ActOnMemInitializers(New,
4133                        /*FIXME: ColonLoc */
4134                        SourceLocation(),
4135                        NewInits,
4136                        AnyErrors);
4137 }
4138 
4139 // TODO: this could be templated if the various decl types used the
4140 // same method name.
4141 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4142                               ClassTemplateDecl *Instance) {
4143   Pattern = Pattern->getCanonicalDecl();
4144 
4145   do {
4146     Instance = Instance->getCanonicalDecl();
4147     if (Pattern == Instance) return true;
4148     Instance = Instance->getInstantiatedFromMemberTemplate();
4149   } while (Instance);
4150 
4151   return false;
4152 }
4153 
4154 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4155                               FunctionTemplateDecl *Instance) {
4156   Pattern = Pattern->getCanonicalDecl();
4157 
4158   do {
4159     Instance = Instance->getCanonicalDecl();
4160     if (Pattern == Instance) return true;
4161     Instance = Instance->getInstantiatedFromMemberTemplate();
4162   } while (Instance);
4163 
4164   return false;
4165 }
4166 
4167 static bool
4168 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4169                   ClassTemplatePartialSpecializationDecl *Instance) {
4170   Pattern
4171     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4172   do {
4173     Instance = cast<ClassTemplatePartialSpecializationDecl>(
4174                                                 Instance->getCanonicalDecl());
4175     if (Pattern == Instance)
4176       return true;
4177     Instance = Instance->getInstantiatedFromMember();
4178   } while (Instance);
4179 
4180   return false;
4181 }
4182 
4183 static bool isInstantiationOf(CXXRecordDecl *Pattern,
4184                               CXXRecordDecl *Instance) {
4185   Pattern = Pattern->getCanonicalDecl();
4186 
4187   do {
4188     Instance = Instance->getCanonicalDecl();
4189     if (Pattern == Instance) return true;
4190     Instance = Instance->getInstantiatedFromMemberClass();
4191   } while (Instance);
4192 
4193   return false;
4194 }
4195 
4196 static bool isInstantiationOf(FunctionDecl *Pattern,
4197                               FunctionDecl *Instance) {
4198   Pattern = Pattern->getCanonicalDecl();
4199 
4200   do {
4201     Instance = Instance->getCanonicalDecl();
4202     if (Pattern == Instance) return true;
4203     Instance = Instance->getInstantiatedFromMemberFunction();
4204   } while (Instance);
4205 
4206   return false;
4207 }
4208 
4209 static bool isInstantiationOf(EnumDecl *Pattern,
4210                               EnumDecl *Instance) {
4211   Pattern = Pattern->getCanonicalDecl();
4212 
4213   do {
4214     Instance = Instance->getCanonicalDecl();
4215     if (Pattern == Instance) return true;
4216     Instance = Instance->getInstantiatedFromMemberEnum();
4217   } while (Instance);
4218 
4219   return false;
4220 }
4221 
4222 static bool isInstantiationOf(UsingShadowDecl *Pattern,
4223                               UsingShadowDecl *Instance,
4224                               ASTContext &C) {
4225   return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4226 }
4227 
4228 static bool isInstantiationOf(UsingDecl *Pattern,
4229                               UsingDecl *Instance,
4230                               ASTContext &C) {
4231   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4232 }
4233 
4234 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4235                               UsingDecl *Instance,
4236                               ASTContext &C) {
4237   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4238 }
4239 
4240 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
4241                               UsingDecl *Instance,
4242                               ASTContext &C) {
4243   return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4244 }
4245 
4246 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4247                                               VarDecl *Instance) {
4248   assert(Instance->isStaticDataMember());
4249 
4250   Pattern = Pattern->getCanonicalDecl();
4251 
4252   do {
4253     Instance = Instance->getCanonicalDecl();
4254     if (Pattern == Instance) return true;
4255     Instance = Instance->getInstantiatedFromStaticDataMember();
4256   } while (Instance);
4257 
4258   return false;
4259 }
4260 
4261 // Other is the prospective instantiation
4262 // D is the prospective pattern
4263 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4264   if (D->getKind() != Other->getKind()) {
4265     if (UnresolvedUsingTypenameDecl *UUD
4266           = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4267       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4268         return isInstantiationOf(UUD, UD, Ctx);
4269       }
4270     }
4271 
4272     if (UnresolvedUsingValueDecl *UUD
4273           = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4274       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4275         return isInstantiationOf(UUD, UD, Ctx);
4276       }
4277     }
4278 
4279     return false;
4280   }
4281 
4282   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4283     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4284 
4285   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4286     return isInstantiationOf(cast<FunctionDecl>(D), Function);
4287 
4288   if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4289     return isInstantiationOf(cast<EnumDecl>(D), Enum);
4290 
4291   if (VarDecl *Var = dyn_cast<VarDecl>(Other))
4292     if (Var->isStaticDataMember())
4293       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4294 
4295   if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4296     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4297 
4298   if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4299     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4300 
4301   if (ClassTemplatePartialSpecializationDecl *PartialSpec
4302         = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4303     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4304                              PartialSpec);
4305 
4306   if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4307     if (!Field->getDeclName()) {
4308       // This is an unnamed field.
4309       return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
4310         cast<FieldDecl>(D);
4311     }
4312   }
4313 
4314   if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4315     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4316 
4317   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4318     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4319 
4320   return D->getDeclName() && isa<NamedDecl>(Other) &&
4321     D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4322 }
4323 
4324 template<typename ForwardIterator>
4325 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4326                                       NamedDecl *D,
4327                                       ForwardIterator first,
4328                                       ForwardIterator last) {
4329   for (; first != last; ++first)
4330     if (isInstantiationOf(Ctx, D, *first))
4331       return cast<NamedDecl>(*first);
4332 
4333   return 0;
4334 }
4335 
4336 /// \brief Finds the instantiation of the given declaration context
4337 /// within the current instantiation.
4338 ///
4339 /// \returns NULL if there was an error
4340 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4341                           const MultiLevelTemplateArgumentList &TemplateArgs) {
4342   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4343     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4344     return cast_or_null<DeclContext>(ID);
4345   } else return DC;
4346 }
4347 
4348 /// \brief Find the instantiation of the given declaration within the
4349 /// current instantiation.
4350 ///
4351 /// This routine is intended to be used when \p D is a declaration
4352 /// referenced from within a template, that needs to mapped into the
4353 /// corresponding declaration within an instantiation. For example,
4354 /// given:
4355 ///
4356 /// \code
4357 /// template<typename T>
4358 /// struct X {
4359 ///   enum Kind {
4360 ///     KnownValue = sizeof(T)
4361 ///   };
4362 ///
4363 ///   bool getKind() const { return KnownValue; }
4364 /// };
4365 ///
4366 /// template struct X<int>;
4367 /// \endcode
4368 ///
4369 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4370 /// \p EnumConstantDecl for \p KnownValue (which refers to
4371 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4372 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4373 /// this mapping from within the instantiation of <tt>X<int></tt>.
4374 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4375                           const MultiLevelTemplateArgumentList &TemplateArgs) {
4376   DeclContext *ParentDC = D->getDeclContext();
4377   // FIXME: Parmeters of pointer to functions (y below) that are themselves
4378   // parameters (p below) can have their ParentDC set to the translation-unit
4379   // - thus we can not consistently check if the ParentDC of such a parameter
4380   // is Dependent or/and a FunctionOrMethod.
4381   // For e.g. this code, during Template argument deduction tries to
4382   // find an instantiated decl for (T y) when the ParentDC for y is
4383   // the translation unit.
4384   //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4385   //   float baz(float(*)()) { return 0.0; }
4386   //   Foo(baz);
4387   // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4388   // it gets here, always has a FunctionOrMethod as its ParentDC??
4389   // For now:
4390   //  - as long as we have a ParmVarDecl whose parent is non-dependent and
4391   //    whose type is not instantiation dependent, do nothing to the decl
4392   //  - otherwise find its instantiated decl.
4393   if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4394       !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4395     return D;
4396   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4397       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4398       (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4399       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4400     // D is a local of some kind. Look into the map of local
4401     // declarations to their instantiations.
4402     typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4403     llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4404       = CurrentInstantiationScope->findInstantiationOf(D);
4405 
4406     if (Found) {
4407       if (Decl *FD = Found->dyn_cast<Decl *>())
4408         return cast<NamedDecl>(FD);
4409 
4410       int PackIdx = ArgumentPackSubstitutionIndex;
4411       assert(PackIdx != -1 && "found declaration pack but not pack expanding");
4412       return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4413     }
4414 
4415     // If we're performing a partial substitution during template argument
4416     // deduction, we may not have values for template parameters yet. They
4417     // just map to themselves.
4418     if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4419         isa<TemplateTemplateParmDecl>(D))
4420       return D;
4421 
4422     if (D->isInvalidDecl())
4423       return 0;
4424 
4425     // If we didn't find the decl, then we must have a label decl that hasn't
4426     // been found yet.  Lazily instantiate it and return it now.
4427     assert(isa<LabelDecl>(D));
4428 
4429     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4430     assert(Inst && "Failed to instantiate label??");
4431 
4432     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4433     return cast<LabelDecl>(Inst);
4434   }
4435 
4436   // For variable template specializations, update those that are still
4437   // type-dependent.
4438   if (VarTemplateSpecializationDecl *VarSpec =
4439           dyn_cast<VarTemplateSpecializationDecl>(D)) {
4440     bool InstantiationDependent = false;
4441     const TemplateArgumentListInfo &VarTemplateArgs =
4442         VarSpec->getTemplateArgsInfo();
4443     if (TemplateSpecializationType::anyDependentTemplateArguments(
4444             VarTemplateArgs, InstantiationDependent))
4445       D = cast<NamedDecl>(
4446           SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4447     return D;
4448   }
4449 
4450   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4451     if (!Record->isDependentContext())
4452       return D;
4453 
4454     // Determine whether this record is the "templated" declaration describing
4455     // a class template or class template partial specialization.
4456     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4457     if (ClassTemplate)
4458       ClassTemplate = ClassTemplate->getCanonicalDecl();
4459     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4460                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4461       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4462 
4463     // Walk the current context to find either the record or an instantiation of
4464     // it.
4465     DeclContext *DC = CurContext;
4466     while (!DC->isFileContext()) {
4467       // If we're performing substitution while we're inside the template
4468       // definition, we'll find our own context. We're done.
4469       if (DC->Equals(Record))
4470         return Record;
4471 
4472       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4473         // Check whether we're in the process of instantiating a class template
4474         // specialization of the template we're mapping.
4475         if (ClassTemplateSpecializationDecl *InstSpec
4476                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4477           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4478           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4479             return InstRecord;
4480         }
4481 
4482         // Check whether we're in the process of instantiating a member class.
4483         if (isInstantiationOf(Record, InstRecord))
4484           return InstRecord;
4485       }
4486 
4487       // Move to the outer template scope.
4488       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4489         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4490           DC = FD->getLexicalDeclContext();
4491           continue;
4492         }
4493       }
4494 
4495       DC = DC->getParent();
4496     }
4497 
4498     // Fall through to deal with other dependent record types (e.g.,
4499     // anonymous unions in class templates).
4500   }
4501 
4502   if (!ParentDC->isDependentContext())
4503     return D;
4504 
4505   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4506   if (!ParentDC)
4507     return 0;
4508 
4509   if (ParentDC != D->getDeclContext()) {
4510     // We performed some kind of instantiation in the parent context,
4511     // so now we need to look into the instantiated parent context to
4512     // find the instantiation of the declaration D.
4513 
4514     // If our context used to be dependent, we may need to instantiate
4515     // it before performing lookup into that context.
4516     bool IsBeingInstantiated = false;
4517     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4518       if (!Spec->isDependentContext()) {
4519         QualType T = Context.getTypeDeclType(Spec);
4520         const RecordType *Tag = T->getAs<RecordType>();
4521         assert(Tag && "type of non-dependent record is not a RecordType");
4522         if (Tag->isBeingDefined())
4523           IsBeingInstantiated = true;
4524         if (!Tag->isBeingDefined() &&
4525             RequireCompleteType(Loc, T, diag::err_incomplete_type))
4526           return 0;
4527 
4528         ParentDC = Tag->getDecl();
4529       }
4530     }
4531 
4532     NamedDecl *Result = 0;
4533     if (D->getDeclName()) {
4534       DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4535       Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4536     } else {
4537       // Since we don't have a name for the entity we're looking for,
4538       // our only option is to walk through all of the declarations to
4539       // find that name. This will occur in a few cases:
4540       //
4541       //   - anonymous struct/union within a template
4542       //   - unnamed class/struct/union/enum within a template
4543       //
4544       // FIXME: Find a better way to find these instantiations!
4545       Result = findInstantiationOf(Context, D,
4546                                    ParentDC->decls_begin(),
4547                                    ParentDC->decls_end());
4548     }
4549 
4550     if (!Result) {
4551       if (isa<UsingShadowDecl>(D)) {
4552         // UsingShadowDecls can instantiate to nothing because of using hiding.
4553       } else if (Diags.hasErrorOccurred()) {
4554         // We've already complained about something, so most likely this
4555         // declaration failed to instantiate. There's no point in complaining
4556         // further, since this is normal in invalid code.
4557       } else if (IsBeingInstantiated) {
4558         // The class in which this member exists is currently being
4559         // instantiated, and we haven't gotten around to instantiating this
4560         // member yet. This can happen when the code uses forward declarations
4561         // of member classes, and introduces ordering dependencies via
4562         // template instantiation.
4563         Diag(Loc, diag::err_member_not_yet_instantiated)
4564           << D->getDeclName()
4565           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4566         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4567       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4568         // This enumeration constant was found when the template was defined,
4569         // but can't be found in the instantiation. This can happen if an
4570         // unscoped enumeration member is explicitly specialized.
4571         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4572         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4573                                                              TemplateArgs));
4574         assert(Spec->getTemplateSpecializationKind() ==
4575                  TSK_ExplicitSpecialization);
4576         Diag(Loc, diag::err_enumerator_does_not_exist)
4577           << D->getDeclName()
4578           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4579         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4580           << Context.getTypeDeclType(Spec);
4581       } else {
4582         // We should have found something, but didn't.
4583         llvm_unreachable("Unable to find instantiation of declaration!");
4584       }
4585     }
4586 
4587     D = Result;
4588   }
4589 
4590   return D;
4591 }
4592 
4593 /// \brief Performs template instantiation for all implicit template
4594 /// instantiations we have seen until this point.
4595 void Sema::PerformPendingInstantiations(bool LocalOnly) {
4596   while (!PendingLocalImplicitInstantiations.empty() ||
4597          (!LocalOnly && !PendingInstantiations.empty())) {
4598     PendingImplicitInstantiation Inst;
4599 
4600     if (PendingLocalImplicitInstantiations.empty()) {
4601       Inst = PendingInstantiations.front();
4602       PendingInstantiations.pop_front();
4603     } else {
4604       Inst = PendingLocalImplicitInstantiations.front();
4605       PendingLocalImplicitInstantiations.pop_front();
4606     }
4607 
4608     // Instantiate function definitions
4609     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
4610       PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4611                                           "instantiating function definition");
4612       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4613                                 TSK_ExplicitInstantiationDefinition;
4614       InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4615                                     DefinitionRequired);
4616       continue;
4617     }
4618 
4619     // Instantiate variable definitions
4620     VarDecl *Var = cast<VarDecl>(Inst.first);
4621 
4622     assert((Var->isStaticDataMember() ||
4623             isa<VarTemplateSpecializationDecl>(Var)) &&
4624            "Not a static data member, nor a variable template"
4625            " specialization?");
4626 
4627     // Don't try to instantiate declarations if the most recent redeclaration
4628     // is invalid.
4629     if (Var->getMostRecentDecl()->isInvalidDecl())
4630       continue;
4631 
4632     // Check if the most recent declaration has changed the specialization kind
4633     // and removed the need for implicit instantiation.
4634     switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
4635     case TSK_Undeclared:
4636       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4637     case TSK_ExplicitInstantiationDeclaration:
4638     case TSK_ExplicitSpecialization:
4639       continue;  // No longer need to instantiate this type.
4640     case TSK_ExplicitInstantiationDefinition:
4641       // We only need an instantiation if the pending instantiation *is* the
4642       // explicit instantiation.
4643       if (Var != Var->getMostRecentDecl()) continue;
4644     case TSK_ImplicitInstantiation:
4645       break;
4646     }
4647 
4648     PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4649                                         "instantiating variable definition");
4650     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4651                               TSK_ExplicitInstantiationDefinition;
4652 
4653     // Instantiate static data member definitions or variable template
4654     // specializations.
4655     InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4656                                   DefinitionRequired);
4657   }
4658 }
4659 
4660 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4661                        const MultiLevelTemplateArgumentList &TemplateArgs) {
4662   for (auto DD : Pattern->ddiags()) {
4663     switch (DD->getKind()) {
4664     case DependentDiagnostic::Access:
4665       HandleDependentAccessCheck(*DD, TemplateArgs);
4666       break;
4667     }
4668   }
4669 }
4670