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