]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Merge ^/head r309519 through r309757.
[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   if (Inst.isAlreadyInstantiating()) {
3364     // This exception specification indirectly depends on itself. Reject.
3365     // FIXME: Corresponding rule in the standard?
3366     Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3367     UpdateExceptionSpec(Decl, EST_None);
3368     return;
3369   }
3370
3371   // Enter the scope of this instantiation. We don't use
3372   // PushDeclContext because we don't have a scope.
3373   Sema::ContextRAII savedContext(*this, Decl);
3374   LocalInstantiationScope Scope(*this);
3375
3376   MultiLevelTemplateArgumentList TemplateArgs =
3377     getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3378
3379   FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3380   if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3381                                        TemplateArgs)) {
3382     UpdateExceptionSpec(Decl, EST_None);
3383     return;
3384   }
3385
3386   SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3387                      TemplateArgs);
3388 }
3389
3390 /// \brief Initializes the common fields of an instantiation function
3391 /// declaration (New) from the corresponding fields of its template (Tmpl).
3392 ///
3393 /// \returns true if there was an error
3394 bool
3395 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3396                                                     FunctionDecl *Tmpl) {
3397   if (Tmpl->isDeleted())
3398     New->setDeletedAsWritten();
3399
3400   // Forward the mangling number from the template to the instantiated decl.
3401   SemaRef.Context.setManglingNumber(New,
3402                                     SemaRef.Context.getManglingNumber(Tmpl));
3403
3404   // If we are performing substituting explicitly-specified template arguments
3405   // or deduced template arguments into a function template and we reach this
3406   // point, we are now past the point where SFINAE applies and have committed
3407   // to keeping the new function template specialization. We therefore
3408   // convert the active template instantiation for the function template
3409   // into a template instantiation for this specific function template
3410   // specialization, which is not a SFINAE context, so that we diagnose any
3411   // further errors in the declaration itself.
3412   typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3413   ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3414   if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3415       ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3416     if (FunctionTemplateDecl *FunTmpl
3417           = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3418       assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3419              "Deduction from the wrong function template?");
3420       (void) FunTmpl;
3421       ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3422       ActiveInst.Entity = New;
3423     }
3424   }
3425
3426   const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3427   assert(Proto && "Function template without prototype?");
3428
3429   if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3430     FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3431
3432     // DR1330: In C++11, defer instantiation of a non-trivial
3433     // exception specification.
3434     // DR1484: Local classes and their members are instantiated along with the
3435     // containing function.
3436     if (SemaRef.getLangOpts().CPlusPlus11 &&
3437         EPI.ExceptionSpec.Type != EST_None &&
3438         EPI.ExceptionSpec.Type != EST_DynamicNone &&
3439         EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
3440         !Tmpl->isLexicallyWithinFunctionOrMethod()) {
3441       FunctionDecl *ExceptionSpecTemplate = Tmpl;
3442       if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3443         ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3444       ExceptionSpecificationType NewEST = EST_Uninstantiated;
3445       if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3446         NewEST = EST_Unevaluated;
3447
3448       // Mark the function has having an uninstantiated exception specification.
3449       const FunctionProtoType *NewProto
3450         = New->getType()->getAs<FunctionProtoType>();
3451       assert(NewProto && "Template instantiation without function prototype?");
3452       EPI = NewProto->getExtProtoInfo();
3453       EPI.ExceptionSpec.Type = NewEST;
3454       EPI.ExceptionSpec.SourceDecl = New;
3455       EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
3456       New->setType(SemaRef.Context.getFunctionType(
3457           NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3458     } else {
3459       SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
3460     }
3461   }
3462
3463   // Get the definition. Leaves the variable unchanged if undefined.
3464   const FunctionDecl *Definition = Tmpl;
3465   Tmpl->isDefined(Definition);
3466
3467   SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3468                            LateAttrs, StartingScope);
3469
3470   return false;
3471 }
3472
3473 /// \brief Initializes common fields of an instantiated method
3474 /// declaration (New) from the corresponding fields of its template
3475 /// (Tmpl).
3476 ///
3477 /// \returns true if there was an error
3478 bool
3479 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3480                                                   CXXMethodDecl *Tmpl) {
3481   if (InitFunctionInstantiation(New, Tmpl))
3482     return true;
3483
3484   New->setAccess(Tmpl->getAccess());
3485   if (Tmpl->isVirtualAsWritten())
3486     New->setVirtualAsWritten(true);
3487
3488   // FIXME: New needs a pointer to Tmpl
3489   return false;
3490 }
3491
3492 /// \brief Instantiate the definition of the given function from its
3493 /// template.
3494 ///
3495 /// \param PointOfInstantiation the point at which the instantiation was
3496 /// required. Note that this is not precisely a "point of instantiation"
3497 /// for the function, but it's close.
3498 ///
3499 /// \param Function the already-instantiated declaration of a
3500 /// function template specialization or member function of a class template
3501 /// specialization.
3502 ///
3503 /// \param Recursive if true, recursively instantiates any functions that
3504 /// are required by this instantiation.
3505 ///
3506 /// \param DefinitionRequired if true, then we are performing an explicit
3507 /// instantiation where the body of the function is required. Complain if
3508 /// there is no such body.
3509 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3510                                          FunctionDecl *Function,
3511                                          bool Recursive,
3512                                          bool DefinitionRequired,
3513                                          bool AtEndOfTU) {
3514   if (Function->isInvalidDecl() || Function->isDefined())
3515     return;
3516
3517   // Never instantiate an explicit specialization except if it is a class scope
3518   // explicit specialization.
3519   if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3520       !Function->getClassScopeSpecializationPattern())
3521     return;
3522
3523   // Find the function body that we'll be substituting.
3524   const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3525   assert(PatternDecl && "instantiating a non-template");
3526
3527   Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3528   assert(PatternDecl && "template definition is not a template");
3529   if (!Pattern) {
3530     // Try to find a defaulted definition
3531     PatternDecl->isDefined(PatternDecl);
3532   }
3533   assert(PatternDecl && "template definition is not a template");
3534
3535   // Postpone late parsed template instantiations.
3536   if (PatternDecl->isLateTemplateParsed() &&
3537       !LateTemplateParser) {
3538     PendingInstantiations.push_back(
3539       std::make_pair(Function, PointOfInstantiation));
3540     return;
3541   }
3542
3543   // If we're performing recursive template instantiation, create our own
3544   // queue of pending implicit instantiations that we will instantiate later,
3545   // while we're still within our own instantiation context.
3546   // This has to happen before LateTemplateParser below is called, so that
3547   // it marks vtables used in late parsed templates as used.
3548   SavePendingLocalImplicitInstantiationsRAII
3549       SavedPendingLocalImplicitInstantiations(*this);
3550   SavePendingInstantiationsAndVTableUsesRAII
3551       SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
3552
3553   // Call the LateTemplateParser callback if there is a need to late parse
3554   // a templated function definition.
3555   if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3556       LateTemplateParser) {
3557     // FIXME: Optimize to allow individual templates to be deserialized.
3558     if (PatternDecl->isFromASTFile())
3559       ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3560
3561     LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3562     assert(LPT && "missing LateParsedTemplate");
3563     LateTemplateParser(OpaqueParser, *LPT);
3564     Pattern = PatternDecl->getBody(PatternDecl);
3565   }
3566
3567   // FIXME: Check that the definition is visible before trying to instantiate
3568   // it. This requires us to track the instantiation stack in order to know
3569   // which definitions should be visible.
3570
3571   if (!Pattern && !PatternDecl->isDefaulted()) {
3572     if (DefinitionRequired) {
3573       if (Function->getPrimaryTemplate())
3574         Diag(PointOfInstantiation,
3575              diag::err_explicit_instantiation_undefined_func_template)
3576           << Function->getPrimaryTemplate();
3577       else
3578         Diag(PointOfInstantiation,
3579              diag::err_explicit_instantiation_undefined_member)
3580           << 1 << Function->getDeclName() << Function->getDeclContext();
3581
3582       if (PatternDecl)
3583         Diag(PatternDecl->getLocation(),
3584              diag::note_explicit_instantiation_here);
3585       Function->setInvalidDecl();
3586     } else if (Function->getTemplateSpecializationKind()
3587                  == TSK_ExplicitInstantiationDefinition) {
3588       assert(!Recursive);
3589       PendingInstantiations.push_back(
3590         std::make_pair(Function, PointOfInstantiation));
3591     } else if (Function->getTemplateSpecializationKind()
3592                  == TSK_ImplicitInstantiation) {
3593       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
3594         Diag(PointOfInstantiation, diag::warn_func_template_missing)
3595           << Function;
3596         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
3597         if (getLangOpts().CPlusPlus11)
3598           Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
3599             << Function;
3600       }
3601     }
3602
3603     return;
3604   }
3605
3606   // C++1y [temp.explicit]p10:
3607   //   Except for inline functions, declarations with types deduced from their
3608   //   initializer or return value, and class template specializations, other
3609   //   explicit instantiation declarations have the effect of suppressing the
3610   //   implicit instantiation of the entity to which they refer.
3611   if (Function->getTemplateSpecializationKind() ==
3612           TSK_ExplicitInstantiationDeclaration &&
3613       !PatternDecl->isInlined() &&
3614       !PatternDecl->getReturnType()->getContainedAutoType())
3615     return;
3616
3617   if (PatternDecl->isInlined()) {
3618     // Function, and all later redeclarations of it (from imported modules,
3619     // for instance), are now implicitly inline.
3620     for (auto *D = Function->getMostRecentDecl(); /**/;
3621          D = D->getPreviousDecl()) {
3622       D->setImplicitlyInline();
3623       if (D == Function)
3624         break;
3625     }
3626   }
3627
3628   InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3629   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
3630     return;
3631   PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3632                                       "instantiating function definition");
3633
3634   // Copy the inner loc start from the pattern.
3635   Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3636
3637   EnterExpressionEvaluationContext EvalContext(*this,
3638                                                Sema::PotentiallyEvaluated);
3639
3640   // Introduce a new scope where local variable instantiations will be
3641   // recorded, unless we're actually a member function within a local
3642   // class, in which case we need to merge our results with the parent
3643   // scope (of the enclosing function).
3644   bool MergeWithParentScope = false;
3645   if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3646     MergeWithParentScope = Rec->isLocalClass();
3647
3648   LocalInstantiationScope Scope(*this, MergeWithParentScope);
3649
3650   if (PatternDecl->isDefaulted())
3651     SetDeclDefaulted(Function, PatternDecl->getLocation());
3652   else {
3653     MultiLevelTemplateArgumentList TemplateArgs =
3654       getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3655
3656     // Substitute into the qualifier; we can get a substitution failure here
3657     // through evil use of alias templates.
3658     // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3659     // of the) lexical context of the pattern?
3660     SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3661
3662     ActOnStartOfFunctionDef(nullptr, Function);
3663
3664     // Enter the scope of this instantiation. We don't use
3665     // PushDeclContext because we don't have a scope.
3666     Sema::ContextRAII savedContext(*this, Function);
3667
3668     if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3669                                          TemplateArgs))
3670       return;
3671
3672     // If this is a constructor, instantiate the member initializers.
3673     if (const CXXConstructorDecl *Ctor =
3674           dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3675       InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3676                                  TemplateArgs);
3677     }
3678
3679     // Instantiate the function body.
3680     StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3681
3682     if (Body.isInvalid())
3683       Function->setInvalidDecl();
3684
3685     ActOnFinishFunctionBody(Function, Body.get(),
3686                             /*IsInstantiation=*/true);
3687
3688     PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3689
3690     if (auto *Listener = getASTMutationListener())
3691       Listener->FunctionDefinitionInstantiated(Function);
3692
3693     savedContext.pop();
3694   }
3695
3696   DeclGroupRef DG(Function);
3697   Consumer.HandleTopLevelDecl(DG);
3698
3699   // This class may have local implicit instantiations that need to be
3700   // instantiation within this scope.
3701   PerformPendingInstantiations(/*LocalOnly=*/true);
3702   Scope.Exit();
3703
3704   if (Recursive) {
3705     // Define any pending vtables.
3706     DefineUsedVTables();
3707
3708     // Instantiate any pending implicit instantiations found during the
3709     // instantiation of this template.
3710     PerformPendingInstantiations();
3711
3712     // PendingInstantiations and VTableUses are restored through
3713     // SavePendingInstantiationsAndVTableUses's destructor.
3714   }
3715 }
3716
3717 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3718     VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3719     const TemplateArgumentList &TemplateArgList,
3720     const TemplateArgumentListInfo &TemplateArgsInfo,
3721     SmallVectorImpl<TemplateArgument> &Converted,
3722     SourceLocation PointOfInstantiation, void *InsertPos,
3723     LateInstantiatedAttrVec *LateAttrs,
3724     LocalInstantiationScope *StartingScope) {
3725   if (FromVar->isInvalidDecl())
3726     return nullptr;
3727
3728   InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3729   if (Inst.isInvalid())
3730     return nullptr;
3731
3732   MultiLevelTemplateArgumentList TemplateArgLists;
3733   TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3734
3735   // Instantiate the first declaration of the variable template: for a partial
3736   // specialization of a static data member template, the first declaration may
3737   // or may not be the declaration in the class; if it's in the class, we want
3738   // to instantiate a member in the class (a declaration), and if it's outside,
3739   // we want to instantiate a definition.
3740   //
3741   // If we're instantiating an explicitly-specialized member template or member
3742   // partial specialization, don't do this. The member specialization completely
3743   // replaces the original declaration in this case.
3744   bool IsMemberSpec = false;
3745   if (VarTemplatePartialSpecializationDecl *PartialSpec =
3746           dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3747     IsMemberSpec = PartialSpec->isMemberSpecialization();
3748   else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3749     IsMemberSpec = FromTemplate->isMemberSpecialization();
3750   if (!IsMemberSpec)
3751     FromVar = FromVar->getFirstDecl();
3752
3753   MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3754   TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3755                                         MultiLevelList);
3756
3757   // TODO: Set LateAttrs and StartingScope ...
3758
3759   return cast_or_null<VarTemplateSpecializationDecl>(
3760       Instantiator.VisitVarTemplateSpecializationDecl(
3761           VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3762 }
3763
3764 /// \brief Instantiates a variable template specialization by completing it
3765 /// with appropriate type information and initializer.
3766 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3767     VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3768     const MultiLevelTemplateArgumentList &TemplateArgs) {
3769
3770   // Do substitution on the type of the declaration
3771   TypeSourceInfo *DI =
3772       SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3773                 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3774   if (!DI)
3775     return nullptr;
3776
3777   // Update the type of this variable template specialization.
3778   VarSpec->setType(DI->getType());
3779
3780   // Instantiate the initializer.
3781   InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3782
3783   return VarSpec;
3784 }
3785
3786 /// BuildVariableInstantiation - Used after a new variable has been created.
3787 /// Sets basic variable data and decides whether to postpone the
3788 /// variable instantiation.
3789 void Sema::BuildVariableInstantiation(
3790     VarDecl *NewVar, VarDecl *OldVar,
3791     const MultiLevelTemplateArgumentList &TemplateArgs,
3792     LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3793     LocalInstantiationScope *StartingScope,
3794     bool InstantiatingVarTemplate) {
3795
3796   // If we are instantiating a local extern declaration, the
3797   // instantiation belongs lexically to the containing function.
3798   // If we are instantiating a static data member defined
3799   // out-of-line, the instantiation will have the same lexical
3800   // context (which will be a namespace scope) as the template.
3801   if (OldVar->isLocalExternDecl()) {
3802     NewVar->setLocalExternDecl();
3803     NewVar->setLexicalDeclContext(Owner);
3804   } else if (OldVar->isOutOfLine())
3805     NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3806   NewVar->setTSCSpec(OldVar->getTSCSpec());
3807   NewVar->setInitStyle(OldVar->getInitStyle());
3808   NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3809   NewVar->setConstexpr(OldVar->isConstexpr());
3810   NewVar->setInitCapture(OldVar->isInitCapture());
3811   NewVar->setPreviousDeclInSameBlockScope(
3812       OldVar->isPreviousDeclInSameBlockScope());
3813   NewVar->setAccess(OldVar->getAccess());
3814
3815   if (!OldVar->isStaticDataMember()) {
3816     if (OldVar->isUsed(false))
3817       NewVar->setIsUsed();
3818     NewVar->setReferenced(OldVar->isReferenced());
3819   }
3820
3821   InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3822
3823   LookupResult Previous(
3824       *this, NewVar->getDeclName(), NewVar->getLocation(),
3825       NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3826                                   : Sema::LookupOrdinaryName,
3827       Sema::ForRedeclaration);
3828
3829   if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3830       (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3831        OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
3832     // We have a previous declaration. Use that one, so we merge with the
3833     // right type.
3834     if (NamedDecl *NewPrev = FindInstantiatedDecl(
3835             NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3836       Previous.addDecl(NewPrev);
3837   } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3838              OldVar->hasLinkage())
3839     LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3840   CheckVariableDeclaration(NewVar, Previous);
3841
3842   if (!InstantiatingVarTemplate) {
3843     NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3844     if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3845       NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3846   }
3847
3848   if (!OldVar->isOutOfLine()) {
3849     if (NewVar->getDeclContext()->isFunctionOrMethod())
3850       CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3851   }
3852
3853   // Link instantiations of static data members back to the template from
3854   // which they were instantiated.
3855   if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3856     NewVar->setInstantiationOfStaticDataMember(OldVar,
3857                                                TSK_ImplicitInstantiation);
3858
3859   // Forward the mangling number from the template to the instantiated decl.
3860   Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
3861   Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
3862
3863   // Delay instantiation of the initializer for variable templates or inline
3864   // static data members until a definition of the variable is needed. We need
3865   // it right away if the type contains 'auto'.
3866   if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3867        !InstantiatingVarTemplate &&
3868        !(OldVar->isInline() && OldVar->isThisDeclarationADefinition())) ||
3869       NewVar->getType()->isUndeducedType())
3870     InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3871
3872   // Diagnose unused local variables with dependent types, where the diagnostic
3873   // will have been deferred.
3874   if (!NewVar->isInvalidDecl() &&
3875       NewVar->getDeclContext()->isFunctionOrMethod() &&
3876       OldVar->getType()->isDependentType())
3877     DiagnoseUnusedDecl(NewVar);
3878 }
3879
3880 /// \brief Instantiate the initializer of a variable.
3881 void Sema::InstantiateVariableInitializer(
3882     VarDecl *Var, VarDecl *OldVar,
3883     const MultiLevelTemplateArgumentList &TemplateArgs) {
3884   // We propagate the 'inline' flag with the initializer, because it
3885   // would otherwise imply that the variable is a definition for a
3886   // non-static data member.
3887   if (OldVar->isInlineSpecified())
3888     Var->setInlineSpecified();
3889   else if (OldVar->isInline())
3890     Var->setImplicitlyInline();
3891
3892   if (OldVar->getInit()) {
3893     if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3894       PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3895     else
3896       PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3897
3898     // Instantiate the initializer.
3899     ExprResult Init;
3900
3901     {
3902       ContextRAII SwitchContext(*this, Var->getDeclContext());
3903       Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
3904                               OldVar->getInitStyle() == VarDecl::CallInit);
3905     }
3906
3907     if (!Init.isInvalid()) {
3908       bool TypeMayContainAuto = true;
3909       Expr *InitExpr = Init.get();
3910
3911       if (Var->hasAttr<DLLImportAttr>() &&
3912           (!InitExpr ||
3913            !InitExpr->isConstantInitializer(getASTContext(), false))) {
3914         // Do not dynamically initialize dllimport variables.
3915       } else if (InitExpr) {
3916         bool DirectInit = OldVar->isDirectInit();
3917         AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
3918       } else
3919         ActOnUninitializedDecl(Var, TypeMayContainAuto);
3920     } else {
3921       // FIXME: Not too happy about invalidating the declaration
3922       // because of a bogus initializer.
3923       Var->setInvalidDecl();
3924     }
3925
3926     PopExpressionEvaluationContext();
3927   } else {
3928     if (Var->isStaticDataMember()) {
3929       if (!Var->isOutOfLine())
3930         return;
3931
3932       // If the declaration inside the class had an initializer, don't add
3933       // another one to the out-of-line definition.
3934       if (OldVar->getFirstDecl()->hasInit())
3935         return;
3936     }
3937
3938     // We'll add an initializer to a for-range declaration later.
3939     if (Var->isCXXForRangeDecl())
3940       return;
3941
3942     ActOnUninitializedDecl(Var, false);
3943   }
3944 }
3945
3946 /// \brief Instantiate the definition of the given variable from its
3947 /// template.
3948 ///
3949 /// \param PointOfInstantiation the point at which the instantiation was
3950 /// required. Note that this is not precisely a "point of instantiation"
3951 /// for the function, but it's close.
3952 ///
3953 /// \param Var the already-instantiated declaration of a static member
3954 /// variable of a class template specialization.
3955 ///
3956 /// \param Recursive if true, recursively instantiates any functions that
3957 /// are required by this instantiation.
3958 ///
3959 /// \param DefinitionRequired if true, then we are performing an explicit
3960 /// instantiation where an out-of-line definition of the member variable
3961 /// is required. Complain if there is no such definition.
3962 void Sema::InstantiateStaticDataMemberDefinition(
3963                                           SourceLocation PointOfInstantiation,
3964                                                  VarDecl *Var,
3965                                                  bool Recursive,
3966                                                  bool DefinitionRequired) {
3967   InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3968                                 DefinitionRequired);
3969 }
3970
3971 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3972                                          VarDecl *Var, bool Recursive,
3973                                       bool DefinitionRequired, bool AtEndOfTU) {
3974   if (Var->isInvalidDecl())
3975     return;
3976
3977   VarTemplateSpecializationDecl *VarSpec =
3978       dyn_cast<VarTemplateSpecializationDecl>(Var);
3979   VarDecl *PatternDecl = nullptr, *Def = nullptr;
3980   MultiLevelTemplateArgumentList TemplateArgs =
3981       getTemplateInstantiationArgs(Var);
3982
3983   if (VarSpec) {
3984     // If this is a variable template specialization, make sure that it is
3985     // non-dependent, then find its instantiation pattern.
3986     bool InstantiationDependent = false;
3987     assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3988                VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3989            "Only instantiate variable template specializations that are "
3990            "not type-dependent");
3991     (void)InstantiationDependent;
3992
3993     // Find the variable initialization that we'll be substituting. If the
3994     // pattern was instantiated from a member template, look back further to
3995     // find the real pattern.
3996     assert(VarSpec->getSpecializedTemplate() &&
3997            "Specialization without specialized template?");
3998     llvm::PointerUnion<VarTemplateDecl *,
3999                        VarTemplatePartialSpecializationDecl *> PatternPtr =
4000         VarSpec->getSpecializedTemplateOrPartial();
4001     if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
4002       VarTemplatePartialSpecializationDecl *Tmpl =
4003           PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
4004       while (VarTemplatePartialSpecializationDecl *From =
4005                  Tmpl->getInstantiatedFromMember()) {
4006         if (Tmpl->isMemberSpecialization())
4007           break;
4008
4009         Tmpl = From;
4010       }
4011       PatternDecl = Tmpl;
4012     } else {
4013       VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
4014       while (VarTemplateDecl *From =
4015                  Tmpl->getInstantiatedFromMemberTemplate()) {
4016         if (Tmpl->isMemberSpecialization())
4017           break;
4018
4019         Tmpl = From;
4020       }
4021       PatternDecl = Tmpl->getTemplatedDecl();
4022     }
4023
4024     // If this is a static data member template, there might be an
4025     // uninstantiated initializer on the declaration. If so, instantiate
4026     // it now.
4027     if (PatternDecl->isStaticDataMember() &&
4028         (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
4029         !Var->hasInit()) {
4030       // FIXME: Factor out the duplicated instantiation context setup/tear down
4031       // code here.
4032       InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4033       if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4034         return;
4035       PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4036                                           "instantiating variable initializer");
4037
4038       // If we're performing recursive template instantiation, create our own
4039       // queue of pending implicit instantiations that we will instantiate
4040       // later, while we're still within our own instantiation context.
4041       SavePendingInstantiationsAndVTableUsesRAII
4042           SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
4043
4044       LocalInstantiationScope Local(*this);
4045
4046       // Enter the scope of this instantiation. We don't use
4047       // PushDeclContext because we don't have a scope.
4048       ContextRAII PreviousContext(*this, Var->getDeclContext());
4049       InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4050       PreviousContext.pop();
4051
4052       // FIXME: Need to inform the ASTConsumer that we instantiated the
4053       // initializer?
4054
4055       // This variable may have local implicit instantiations that need to be
4056       // instantiated within this scope.
4057       PerformPendingInstantiations(/*LocalOnly=*/true);
4058
4059       Local.Exit();
4060
4061       if (Recursive) {
4062         // Define any newly required vtables.
4063         DefineUsedVTables();
4064
4065         // Instantiate any pending implicit instantiations found during the
4066         // instantiation of this template.
4067         PerformPendingInstantiations();
4068
4069         // PendingInstantiations and VTableUses are restored through
4070         // SavePendingInstantiationsAndVTableUses's destructor.
4071       }
4072     }
4073
4074     // Find actual definition
4075     Def = PatternDecl->getDefinition(getASTContext());
4076   } else {
4077     // If this is a static data member, find its out-of-line definition.
4078     assert(Var->isStaticDataMember() && "not a static data member?");
4079     PatternDecl = Var->getInstantiatedFromStaticDataMember();
4080
4081     assert(PatternDecl && "data member was not instantiated from a template?");
4082     assert(PatternDecl->isStaticDataMember() && "not a static data member?");
4083     Def = PatternDecl->getDefinition();
4084   }
4085
4086   // FIXME: Check that the definition is visible before trying to instantiate
4087   // it. This requires us to track the instantiation stack in order to know
4088   // which definitions should be visible.
4089
4090   // If we don't have a definition of the variable template, we won't perform
4091   // any instantiation. Rather, we rely on the user to instantiate this
4092   // definition (or provide a specialization for it) in another translation
4093   // unit.
4094   if (!Def) {
4095     if (DefinitionRequired) {
4096       if (VarSpec)
4097         Diag(PointOfInstantiation,
4098              diag::err_explicit_instantiation_undefined_var_template) << Var;
4099       else
4100         Diag(PointOfInstantiation,
4101              diag::err_explicit_instantiation_undefined_member)
4102             << 2 << Var->getDeclName() << Var->getDeclContext();
4103       Diag(PatternDecl->getLocation(),
4104            diag::note_explicit_instantiation_here);
4105       if (VarSpec)
4106         Var->setInvalidDecl();
4107     } else if (Var->getTemplateSpecializationKind()
4108                  == TSK_ExplicitInstantiationDefinition) {
4109       PendingInstantiations.push_back(
4110         std::make_pair(Var, PointOfInstantiation));
4111     } else if (Var->getTemplateSpecializationKind()
4112                  == TSK_ImplicitInstantiation) {
4113       // Warn about missing definition at the end of translation unit.
4114       if (AtEndOfTU && !getDiagnostics().hasErrorOccurred()) {
4115         Diag(PointOfInstantiation, diag::warn_var_template_missing)
4116           << Var;
4117         Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4118         if (getLangOpts().CPlusPlus11)
4119           Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4120       }
4121     }
4122
4123     return;
4124   }
4125
4126   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
4127
4128   // Never instantiate an explicit specialization.
4129   if (TSK == TSK_ExplicitSpecialization)
4130     return;
4131
4132   // C++11 [temp.explicit]p10:
4133   //   Except for inline functions, [...] explicit instantiation declarations
4134   //   have the effect of suppressing the implicit instantiation of the entity
4135   //   to which they refer.
4136   if (TSK == TSK_ExplicitInstantiationDeclaration)
4137     return;
4138
4139   // Make sure to pass the instantiated variable to the consumer at the end.
4140   struct PassToConsumerRAII {
4141     ASTConsumer &Consumer;
4142     VarDecl *Var;
4143
4144     PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4145       : Consumer(Consumer), Var(Var) { }
4146
4147     ~PassToConsumerRAII() {
4148       Consumer.HandleCXXStaticMemberVarInstantiation(Var);
4149     }
4150   } PassToConsumerRAII(Consumer, Var);
4151
4152   // If we already have a definition, we're done.
4153   if (VarDecl *Def = Var->getDefinition()) {
4154     // We may be explicitly instantiating something we've already implicitly
4155     // instantiated.
4156     Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4157                                        PointOfInstantiation);
4158     return;
4159   }
4160
4161   InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4162   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4163     return;
4164   PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4165                                       "instantiating variable definition");
4166
4167   // If we're performing recursive template instantiation, create our own
4168   // queue of pending implicit instantiations that we will instantiate later,
4169   // while we're still within our own instantiation context.
4170   SavePendingLocalImplicitInstantiationsRAII
4171       SavedPendingLocalImplicitInstantiations(*this);
4172   SavePendingInstantiationsAndVTableUsesRAII
4173       SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
4174
4175   // Enter the scope of this instantiation. We don't use
4176   // PushDeclContext because we don't have a scope.
4177   ContextRAII PreviousContext(*this, Var->getDeclContext());
4178   LocalInstantiationScope Local(*this);
4179
4180   VarDecl *OldVar = Var;
4181   if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
4182     // We're instantiating an inline static data member whose definition was
4183     // provided inside the class.
4184     // FIXME: Update record?
4185     InstantiateVariableInitializer(Var, Def, TemplateArgs);
4186   } else if (!VarSpec) {
4187     Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
4188                                           TemplateArgs));
4189   } else if (Var->isStaticDataMember() &&
4190              Var->getLexicalDeclContext()->isRecord()) {
4191     // We need to instantiate the definition of a static data member template,
4192     // and all we have is the in-class declaration of it. Instantiate a separate
4193     // declaration of the definition.
4194     TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4195                                           TemplateArgs);
4196     Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
4197         VarSpec->getSpecializedTemplate(), Def, nullptr,
4198         VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4199     if (Var) {
4200       llvm::PointerUnion<VarTemplateDecl *,
4201                          VarTemplatePartialSpecializationDecl *> PatternPtr =
4202           VarSpec->getSpecializedTemplateOrPartial();
4203       if (VarTemplatePartialSpecializationDecl *Partial =
4204           PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4205         cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4206             Partial, &VarSpec->getTemplateInstantiationArgs());
4207
4208       // Merge the definition with the declaration.
4209       LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4210                      LookupOrdinaryName, ForRedeclaration);
4211       R.addDecl(OldVar);
4212       MergeVarDecl(Var, R);
4213
4214       // Attach the initializer.
4215       InstantiateVariableInitializer(Var, Def, TemplateArgs);
4216     }
4217   } else
4218     // Complete the existing variable's definition with an appropriately
4219     // substituted type and initializer.
4220     Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
4221
4222   PreviousContext.pop();
4223
4224   if (Var) {
4225     PassToConsumerRAII.Var = Var;
4226     Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4227                                        OldVar->getPointOfInstantiation());
4228   }
4229
4230   // This variable may have local implicit instantiations that need to be
4231   // instantiated within this scope.
4232   PerformPendingInstantiations(/*LocalOnly=*/true);
4233
4234   Local.Exit();
4235   
4236   if (Recursive) {
4237     // Define any newly required vtables.
4238     DefineUsedVTables();
4239
4240     // Instantiate any pending implicit instantiations found during the
4241     // instantiation of this template.
4242     PerformPendingInstantiations();
4243
4244     // PendingInstantiations and VTableUses are restored through
4245     // SavePendingInstantiationsAndVTableUses's destructor.
4246   }
4247 }
4248
4249 void
4250 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4251                                  const CXXConstructorDecl *Tmpl,
4252                            const MultiLevelTemplateArgumentList &TemplateArgs) {
4253
4254   SmallVector<CXXCtorInitializer*, 4> NewInits;
4255   bool AnyErrors = Tmpl->isInvalidDecl();
4256
4257   // Instantiate all the initializers.
4258   for (const auto *Init : Tmpl->inits()) {
4259     // Only instantiate written initializers, let Sema re-construct implicit
4260     // ones.
4261     if (!Init->isWritten())
4262       continue;
4263
4264     SourceLocation EllipsisLoc;
4265
4266     if (Init->isPackExpansion()) {
4267       // This is a pack expansion. We should expand it now.
4268       TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4269       SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4270       collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4271       collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4272       bool ShouldExpand = false;
4273       bool RetainExpansion = false;
4274       Optional<unsigned> NumExpansions;
4275       if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4276                                           BaseTL.getSourceRange(),
4277                                           Unexpanded,
4278                                           TemplateArgs, ShouldExpand,
4279                                           RetainExpansion,
4280                                           NumExpansions)) {
4281         AnyErrors = true;
4282         New->setInvalidDecl();
4283         continue;
4284       }
4285       assert(ShouldExpand && "Partial instantiation of base initializer?");
4286
4287       // Loop over all of the arguments in the argument pack(s),
4288       for (unsigned I = 0; I != *NumExpansions; ++I) {
4289         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4290
4291         // Instantiate the initializer.
4292         ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4293                                                /*CXXDirectInit=*/true);
4294         if (TempInit.isInvalid()) {
4295           AnyErrors = true;
4296           break;
4297         }
4298
4299         // Instantiate the base type.
4300         TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4301                                               TemplateArgs,
4302                                               Init->getSourceLocation(),
4303                                               New->getDeclName());
4304         if (!BaseTInfo) {
4305           AnyErrors = true;
4306           break;
4307         }
4308
4309         // Build the initializer.
4310         MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4311                                                      BaseTInfo, TempInit.get(),
4312                                                      New->getParent(),
4313                                                      SourceLocation());
4314         if (NewInit.isInvalid()) {
4315           AnyErrors = true;
4316           break;
4317         }
4318
4319         NewInits.push_back(NewInit.get());
4320       }
4321
4322       continue;
4323     }
4324
4325     // Instantiate the initializer.
4326     ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4327                                            /*CXXDirectInit=*/true);
4328     if (TempInit.isInvalid()) {
4329       AnyErrors = true;
4330       continue;
4331     }
4332
4333     MemInitResult NewInit;
4334     if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4335       TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4336                                         TemplateArgs,
4337                                         Init->getSourceLocation(),
4338                                         New->getDeclName());
4339       if (!TInfo) {
4340         AnyErrors = true;
4341         New->setInvalidDecl();
4342         continue;
4343       }
4344
4345       if (Init->isBaseInitializer())
4346         NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4347                                        New->getParent(), EllipsisLoc);
4348       else
4349         NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4350                                   cast<CXXRecordDecl>(CurContext->getParent()));
4351     } else if (Init->isMemberInitializer()) {
4352       FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4353                                                      Init->getMemberLocation(),
4354                                                      Init->getMember(),
4355                                                      TemplateArgs));
4356       if (!Member) {
4357         AnyErrors = true;
4358         New->setInvalidDecl();
4359         continue;
4360       }
4361
4362       NewInit = BuildMemberInitializer(Member, TempInit.get(),
4363                                        Init->getSourceLocation());
4364     } else if (Init->isIndirectMemberInitializer()) {
4365       IndirectFieldDecl *IndirectMember =
4366          cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4367                                  Init->getMemberLocation(),
4368                                  Init->getIndirectMember(), TemplateArgs));
4369
4370       if (!IndirectMember) {
4371         AnyErrors = true;
4372         New->setInvalidDecl();
4373         continue;
4374       }
4375
4376       NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4377                                        Init->getSourceLocation());
4378     }
4379
4380     if (NewInit.isInvalid()) {
4381       AnyErrors = true;
4382       New->setInvalidDecl();
4383     } else {
4384       NewInits.push_back(NewInit.get());
4385     }
4386   }
4387
4388   // Assign all the initializers to the new constructor.
4389   ActOnMemInitializers(New,
4390                        /*FIXME: ColonLoc */
4391                        SourceLocation(),
4392                        NewInits,
4393                        AnyErrors);
4394 }
4395
4396 // TODO: this could be templated if the various decl types used the
4397 // same method name.
4398 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4399                               ClassTemplateDecl *Instance) {
4400   Pattern = Pattern->getCanonicalDecl();
4401
4402   do {
4403     Instance = Instance->getCanonicalDecl();
4404     if (Pattern == Instance) return true;
4405     Instance = Instance->getInstantiatedFromMemberTemplate();
4406   } while (Instance);
4407
4408   return false;
4409 }
4410
4411 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4412                               FunctionTemplateDecl *Instance) {
4413   Pattern = Pattern->getCanonicalDecl();
4414
4415   do {
4416     Instance = Instance->getCanonicalDecl();
4417     if (Pattern == Instance) return true;
4418     Instance = Instance->getInstantiatedFromMemberTemplate();
4419   } while (Instance);
4420
4421   return false;
4422 }
4423
4424 static bool
4425 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4426                   ClassTemplatePartialSpecializationDecl *Instance) {
4427   Pattern
4428     = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4429   do {
4430     Instance = cast<ClassTemplatePartialSpecializationDecl>(
4431                                                 Instance->getCanonicalDecl());
4432     if (Pattern == Instance)
4433       return true;
4434     Instance = Instance->getInstantiatedFromMember();
4435   } while (Instance);
4436
4437   return false;
4438 }
4439
4440 static bool isInstantiationOf(CXXRecordDecl *Pattern,
4441                               CXXRecordDecl *Instance) {
4442   Pattern = Pattern->getCanonicalDecl();
4443
4444   do {
4445     Instance = Instance->getCanonicalDecl();
4446     if (Pattern == Instance) return true;
4447     Instance = Instance->getInstantiatedFromMemberClass();
4448   } while (Instance);
4449
4450   return false;
4451 }
4452
4453 static bool isInstantiationOf(FunctionDecl *Pattern,
4454                               FunctionDecl *Instance) {
4455   Pattern = Pattern->getCanonicalDecl();
4456
4457   do {
4458     Instance = Instance->getCanonicalDecl();
4459     if (Pattern == Instance) return true;
4460     Instance = Instance->getInstantiatedFromMemberFunction();
4461   } while (Instance);
4462
4463   return false;
4464 }
4465
4466 static bool isInstantiationOf(EnumDecl *Pattern,
4467                               EnumDecl *Instance) {
4468   Pattern = Pattern->getCanonicalDecl();
4469
4470   do {
4471     Instance = Instance->getCanonicalDecl();
4472     if (Pattern == Instance) return true;
4473     Instance = Instance->getInstantiatedFromMemberEnum();
4474   } while (Instance);
4475
4476   return false;
4477 }
4478
4479 static bool isInstantiationOf(UsingShadowDecl *Pattern,
4480                               UsingShadowDecl *Instance,
4481                               ASTContext &C) {
4482   return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4483                             Pattern);
4484 }
4485
4486 static bool isInstantiationOf(UsingDecl *Pattern,
4487                               UsingDecl *Instance,
4488                               ASTContext &C) {
4489   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4490 }
4491
4492 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4493                               UsingDecl *Instance,
4494                               ASTContext &C) {
4495   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4496 }
4497
4498 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
4499                               UsingDecl *Instance,
4500                               ASTContext &C) {
4501   return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4502 }
4503
4504 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4505                                               VarDecl *Instance) {
4506   assert(Instance->isStaticDataMember());
4507
4508   Pattern = Pattern->getCanonicalDecl();
4509
4510   do {
4511     Instance = Instance->getCanonicalDecl();
4512     if (Pattern == Instance) return true;
4513     Instance = Instance->getInstantiatedFromStaticDataMember();
4514   } while (Instance);
4515
4516   return false;
4517 }
4518
4519 // Other is the prospective instantiation
4520 // D is the prospective pattern
4521 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4522   if (D->getKind() != Other->getKind()) {
4523     if (UnresolvedUsingTypenameDecl *UUD
4524           = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4525       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4526         return isInstantiationOf(UUD, UD, Ctx);
4527       }
4528     }
4529
4530     if (UnresolvedUsingValueDecl *UUD
4531           = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4532       if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4533         return isInstantiationOf(UUD, UD, Ctx);
4534       }
4535     }
4536
4537     return false;
4538   }
4539
4540   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4541     return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4542
4543   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4544     return isInstantiationOf(cast<FunctionDecl>(D), Function);
4545
4546   if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4547     return isInstantiationOf(cast<EnumDecl>(D), Enum);
4548
4549   if (VarDecl *Var = dyn_cast<VarDecl>(Other))
4550     if (Var->isStaticDataMember())
4551       return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4552
4553   if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4554     return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4555
4556   if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4557     return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4558
4559   if (ClassTemplatePartialSpecializationDecl *PartialSpec
4560         = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4561     return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4562                              PartialSpec);
4563
4564   if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4565     if (!Field->getDeclName()) {
4566       // This is an unnamed field.
4567       return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4568                                 cast<FieldDecl>(D));
4569     }
4570   }
4571
4572   if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4573     return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4574
4575   if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4576     return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4577
4578   return D->getDeclName() && isa<NamedDecl>(Other) &&
4579     D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4580 }
4581
4582 template<typename ForwardIterator>
4583 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4584                                       NamedDecl *D,
4585                                       ForwardIterator first,
4586                                       ForwardIterator last) {
4587   for (; first != last; ++first)
4588     if (isInstantiationOf(Ctx, D, *first))
4589       return cast<NamedDecl>(*first);
4590
4591   return nullptr;
4592 }
4593
4594 /// \brief Finds the instantiation of the given declaration context
4595 /// within the current instantiation.
4596 ///
4597 /// \returns NULL if there was an error
4598 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4599                           const MultiLevelTemplateArgumentList &TemplateArgs) {
4600   if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4601     Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4602     return cast_or_null<DeclContext>(ID);
4603   } else return DC;
4604 }
4605
4606 /// \brief Find the instantiation of the given declaration within the
4607 /// current instantiation.
4608 ///
4609 /// This routine is intended to be used when \p D is a declaration
4610 /// referenced from within a template, that needs to mapped into the
4611 /// corresponding declaration within an instantiation. For example,
4612 /// given:
4613 ///
4614 /// \code
4615 /// template<typename T>
4616 /// struct X {
4617 ///   enum Kind {
4618 ///     KnownValue = sizeof(T)
4619 ///   };
4620 ///
4621 ///   bool getKind() const { return KnownValue; }
4622 /// };
4623 ///
4624 /// template struct X<int>;
4625 /// \endcode
4626 ///
4627 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4628 /// \p EnumConstantDecl for \p KnownValue (which refers to
4629 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4630 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4631 /// this mapping from within the instantiation of <tt>X<int></tt>.
4632 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4633                           const MultiLevelTemplateArgumentList &TemplateArgs) {
4634   DeclContext *ParentDC = D->getDeclContext();
4635   // FIXME: Parmeters of pointer to functions (y below) that are themselves 
4636   // parameters (p below) can have their ParentDC set to the translation-unit
4637   // - thus we can not consistently check if the ParentDC of such a parameter 
4638   // is Dependent or/and a FunctionOrMethod.
4639   // For e.g. this code, during Template argument deduction tries to 
4640   // find an instantiated decl for (T y) when the ParentDC for y is
4641   // the translation unit.  
4642   //   e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} 
4643   //   float baz(float(*)()) { return 0.0; }
4644   //   Foo(baz);
4645   // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4646   // it gets here, always has a FunctionOrMethod as its ParentDC??
4647   // For now:
4648   //  - as long as we have a ParmVarDecl whose parent is non-dependent and
4649   //    whose type is not instantiation dependent, do nothing to the decl
4650   //  - otherwise find its instantiated decl.
4651   if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4652       !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4653     return D;
4654   if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4655       isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4656       (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4657       (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4658     // D is a local of some kind. Look into the map of local
4659     // declarations to their instantiations.
4660     if (CurrentInstantiationScope) {
4661       if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4662         if (Decl *FD = Found->dyn_cast<Decl *>())
4663           return cast<NamedDecl>(FD);
4664
4665         int PackIdx = ArgumentPackSubstitutionIndex;
4666         assert(PackIdx != -1 &&
4667                "found declaration pack but not pack expanding");
4668         typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4669         return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4670       }
4671     }
4672
4673     // If we're performing a partial substitution during template argument
4674     // deduction, we may not have values for template parameters yet. They
4675     // just map to themselves.
4676     if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4677         isa<TemplateTemplateParmDecl>(D))
4678       return D;
4679
4680     if (D->isInvalidDecl())
4681       return nullptr;
4682
4683     // Normally this function only searches for already instantiated declaration
4684     // however we have to make an exclusion for local types used before
4685     // definition as in the code:
4686     //
4687     //   template<typename T> void f1() {
4688     //     void g1(struct x1);
4689     //     struct x1 {};
4690     //   }
4691     //
4692     // In this case instantiation of the type of 'g1' requires definition of
4693     // 'x1', which is defined later. Error recovery may produce an enum used
4694     // before definition. In these cases we need to instantiate relevant
4695     // declarations here.
4696     bool NeedInstantiate = false;
4697     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4698       NeedInstantiate = RD->isLocalClass();
4699     else
4700       NeedInstantiate = isa<EnumDecl>(D);
4701     if (NeedInstantiate) {
4702       Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4703       CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4704       return cast<TypeDecl>(Inst);
4705     }
4706
4707     // If we didn't find the decl, then we must have a label decl that hasn't
4708     // been found yet.  Lazily instantiate it and return it now.
4709     assert(isa<LabelDecl>(D));
4710
4711     Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4712     assert(Inst && "Failed to instantiate label??");
4713
4714     CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4715     return cast<LabelDecl>(Inst);
4716   }
4717
4718   // For variable template specializations, update those that are still
4719   // type-dependent.
4720   if (VarTemplateSpecializationDecl *VarSpec =
4721           dyn_cast<VarTemplateSpecializationDecl>(D)) {
4722     bool InstantiationDependent = false;
4723     const TemplateArgumentListInfo &VarTemplateArgs =
4724         VarSpec->getTemplateArgsInfo();
4725     if (TemplateSpecializationType::anyDependentTemplateArguments(
4726             VarTemplateArgs, InstantiationDependent))
4727       D = cast<NamedDecl>(
4728           SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4729     return D;
4730   }
4731
4732   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4733     if (!Record->isDependentContext())
4734       return D;
4735
4736     // Determine whether this record is the "templated" declaration describing
4737     // a class template or class template partial specialization.
4738     ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4739     if (ClassTemplate)
4740       ClassTemplate = ClassTemplate->getCanonicalDecl();
4741     else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4742                = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4743       ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4744
4745     // Walk the current context to find either the record or an instantiation of
4746     // it.
4747     DeclContext *DC = CurContext;
4748     while (!DC->isFileContext()) {
4749       // If we're performing substitution while we're inside the template
4750       // definition, we'll find our own context. We're done.
4751       if (DC->Equals(Record))
4752         return Record;
4753
4754       if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4755         // Check whether we're in the process of instantiating a class template
4756         // specialization of the template we're mapping.
4757         if (ClassTemplateSpecializationDecl *InstSpec
4758                       = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4759           ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4760           if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4761             return InstRecord;
4762         }
4763
4764         // Check whether we're in the process of instantiating a member class.
4765         if (isInstantiationOf(Record, InstRecord))
4766           return InstRecord;
4767       }
4768
4769       // Move to the outer template scope.
4770       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4771         if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4772           DC = FD->getLexicalDeclContext();
4773           continue;
4774         }
4775       }
4776
4777       DC = DC->getParent();
4778     }
4779
4780     // Fall through to deal with other dependent record types (e.g.,
4781     // anonymous unions in class templates).
4782   }
4783
4784   if (!ParentDC->isDependentContext())
4785     return D;
4786
4787   ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4788   if (!ParentDC)
4789     return nullptr;
4790
4791   if (ParentDC != D->getDeclContext()) {
4792     // We performed some kind of instantiation in the parent context,
4793     // so now we need to look into the instantiated parent context to
4794     // find the instantiation of the declaration D.
4795
4796     // If our context used to be dependent, we may need to instantiate
4797     // it before performing lookup into that context.
4798     bool IsBeingInstantiated = false;
4799     if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4800       if (!Spec->isDependentContext()) {
4801         QualType T = Context.getTypeDeclType(Spec);
4802         const RecordType *Tag = T->getAs<RecordType>();
4803         assert(Tag && "type of non-dependent record is not a RecordType");
4804         if (Tag->isBeingDefined())
4805           IsBeingInstantiated = true;
4806         if (!Tag->isBeingDefined() &&
4807             RequireCompleteType(Loc, T, diag::err_incomplete_type))
4808           return nullptr;
4809
4810         ParentDC = Tag->getDecl();
4811       }
4812     }
4813
4814     NamedDecl *Result = nullptr;
4815     if (D->getDeclName()) {
4816       DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4817       Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4818     } else {
4819       // Since we don't have a name for the entity we're looking for,
4820       // our only option is to walk through all of the declarations to
4821       // find that name. This will occur in a few cases:
4822       //
4823       //   - anonymous struct/union within a template
4824       //   - unnamed class/struct/union/enum within a template
4825       //
4826       // FIXME: Find a better way to find these instantiations!
4827       Result = findInstantiationOf(Context, D,
4828                                    ParentDC->decls_begin(),
4829                                    ParentDC->decls_end());
4830     }
4831
4832     if (!Result) {
4833       if (isa<UsingShadowDecl>(D)) {
4834         // UsingShadowDecls can instantiate to nothing because of using hiding.
4835       } else if (Diags.hasErrorOccurred()) {
4836         // We've already complained about something, so most likely this
4837         // declaration failed to instantiate. There's no point in complaining
4838         // further, since this is normal in invalid code.
4839       } else if (IsBeingInstantiated) {
4840         // The class in which this member exists is currently being
4841         // instantiated, and we haven't gotten around to instantiating this
4842         // member yet. This can happen when the code uses forward declarations
4843         // of member classes, and introduces ordering dependencies via
4844         // template instantiation.
4845         Diag(Loc, diag::err_member_not_yet_instantiated)
4846           << D->getDeclName()
4847           << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4848         Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4849       } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4850         // This enumeration constant was found when the template was defined,
4851         // but can't be found in the instantiation. This can happen if an
4852         // unscoped enumeration member is explicitly specialized.
4853         EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4854         EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4855                                                              TemplateArgs));
4856         assert(Spec->getTemplateSpecializationKind() ==
4857                  TSK_ExplicitSpecialization);
4858         Diag(Loc, diag::err_enumerator_does_not_exist)
4859           << D->getDeclName()
4860           << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4861         Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4862           << Context.getTypeDeclType(Spec);
4863       } else {
4864         // We should have found something, but didn't.
4865         llvm_unreachable("Unable to find instantiation of declaration!");
4866       }
4867     }
4868
4869     D = Result;
4870   }
4871
4872   return D;
4873 }
4874
4875 /// \brief Performs template instantiation for all implicit template
4876 /// instantiations we have seen until this point.
4877 void Sema::PerformPendingInstantiations(bool LocalOnly) {
4878   while (!PendingLocalImplicitInstantiations.empty() ||
4879          (!LocalOnly && !PendingInstantiations.empty())) {
4880     PendingImplicitInstantiation Inst;
4881
4882     if (PendingLocalImplicitInstantiations.empty()) {
4883       Inst = PendingInstantiations.front();
4884       PendingInstantiations.pop_front();
4885     } else {
4886       Inst = PendingLocalImplicitInstantiations.front();
4887       PendingLocalImplicitInstantiations.pop_front();
4888     }
4889
4890     // Instantiate function definitions
4891     if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
4892       bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4893                                 TSK_ExplicitInstantiationDefinition;
4894       InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4895                                     DefinitionRequired, true);
4896       continue;
4897     }
4898
4899     // Instantiate variable definitions
4900     VarDecl *Var = cast<VarDecl>(Inst.first);
4901
4902     assert((Var->isStaticDataMember() ||
4903             isa<VarTemplateSpecializationDecl>(Var)) &&
4904            "Not a static data member, nor a variable template"
4905            " specialization?");
4906
4907     // Don't try to instantiate declarations if the most recent redeclaration
4908     // is invalid.
4909     if (Var->getMostRecentDecl()->isInvalidDecl())
4910       continue;
4911
4912     // Check if the most recent declaration has changed the specialization kind
4913     // and removed the need for implicit instantiation.
4914     switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
4915     case TSK_Undeclared:
4916       llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4917     case TSK_ExplicitInstantiationDeclaration:
4918     case TSK_ExplicitSpecialization:
4919       continue;  // No longer need to instantiate this type.
4920     case TSK_ExplicitInstantiationDefinition:
4921       // We only need an instantiation if the pending instantiation *is* the
4922       // explicit instantiation.
4923       if (Var != Var->getMostRecentDecl()) continue;
4924     case TSK_ImplicitInstantiation:
4925       break;
4926     }
4927
4928     PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4929                                         "instantiating variable definition");
4930     bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4931                               TSK_ExplicitInstantiationDefinition;
4932
4933     // Instantiate static data member definitions or variable template
4934     // specializations.
4935     InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4936                                   DefinitionRequired, true);
4937   }
4938 }
4939
4940 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4941                        const MultiLevelTemplateArgumentList &TemplateArgs) {
4942   for (auto DD : Pattern->ddiags()) {
4943     switch (DD->getKind()) {
4944     case DependentDiagnostic::Access:
4945       HandleDependentAccessCheck(*DD, TemplateArgs);
4946       break;
4947     }
4948   }
4949 }