1 //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //===----------------------------------------------------------------------===/
7 //
8 //  This file implements C++ template instantiation.
9 //
10 //===----------------------------------------------------------------------===/
11 
12 #include "TreeTransform.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/PrettyDeclStackTrace.h"
20 #include "clang/AST/TypeVisitor.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/Stack.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Sema/DeclSpec.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaConcept.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "clang/Sema/TemplateInstCallback.h"
32 #include "llvm/Support/TimeProfiler.h"
33 
34 using namespace clang;
35 using namespace sema;
36 
37 //===----------------------------------------------------------------------===/
38 // Template Instantiation Support
39 //===----------------------------------------------------------------------===/
40 
41 /// Retrieve the template argument list(s) that should be used to
42 /// instantiate the definition of the given declaration.
43 ///
44 /// \param D the declaration for which we are computing template instantiation
45 /// arguments.
46 ///
47 /// \param Innermost if non-NULL, the innermost template argument list.
48 ///
49 /// \param RelativeToPrimary true if we should get the template
50 /// arguments relative to the primary template, even when we're
51 /// dealing with a specialization. This is only relevant for function
52 /// template specializations.
53 ///
54 /// \param Pattern If non-NULL, indicates the pattern from which we will be
55 /// instantiating the definition of the given declaration, \p D. This is
56 /// used to determine the proper set of template instantiation arguments for
57 /// friend function template specializations.
58 MultiLevelTemplateArgumentList
59 Sema::getTemplateInstantiationArgs(NamedDecl *D,
60                                    const TemplateArgumentList *Innermost,
61                                    bool RelativeToPrimary,
62                                    const FunctionDecl *Pattern) {
63   // Accumulate the set of template argument lists in this structure.
64   MultiLevelTemplateArgumentList Result;
65 
66   if (Innermost)
67     Result.addOuterTemplateArguments(Innermost);
68 
69   DeclContext *Ctx = dyn_cast<DeclContext>(D);
70   if (!Ctx) {
71     Ctx = D->getDeclContext();
72 
73     // Add template arguments from a variable template instantiation. For a
74     // class-scope explicit specialization, there are no template arguments
75     // at this level, but there may be enclosing template arguments.
76     VarTemplateSpecializationDecl *Spec =
77         dyn_cast<VarTemplateSpecializationDecl>(D);
78     if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
79       // We're done when we hit an explicit specialization.
80       if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
81           !isa<VarTemplatePartialSpecializationDecl>(Spec))
82         return Result;
83 
84       Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
85 
86       // If this variable template specialization was instantiated from a
87       // specialized member that is a variable template, we're done.
88       assert(Spec->getSpecializedTemplate() && "No variable template?");
89       llvm::PointerUnion<VarTemplateDecl*,
90                          VarTemplatePartialSpecializationDecl*> Specialized
91                              = Spec->getSpecializedTemplateOrPartial();
92       if (VarTemplatePartialSpecializationDecl *Partial =
93               Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
94         if (Partial->isMemberSpecialization())
95           return Result;
96       } else {
97         VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
98         if (Tmpl->isMemberSpecialization())
99           return Result;
100       }
101     }
102 
103     // If we have a template template parameter with translation unit context,
104     // then we're performing substitution into a default template argument of
105     // this template template parameter before we've constructed the template
106     // that will own this template template parameter. In this case, we
107     // use empty template parameter lists for all of the outer templates
108     // to avoid performing any substitutions.
109     if (Ctx->isTranslationUnit()) {
110       if (TemplateTemplateParmDecl *TTP
111                                       = dyn_cast<TemplateTemplateParmDecl>(D)) {
112         for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
113           Result.addOuterTemplateArguments(None);
114         return Result;
115       }
116     }
117   }
118 
119   while (!Ctx->isFileContext()) {
120     // Add template arguments from a class template instantiation.
121     ClassTemplateSpecializationDecl *Spec
122           = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
123     if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
124       // We're done when we hit an explicit specialization.
125       if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
126           !isa<ClassTemplatePartialSpecializationDecl>(Spec))
127         break;
128 
129       Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
130 
131       // If this class template specialization was instantiated from a
132       // specialized member that is a class template, we're done.
133       assert(Spec->getSpecializedTemplate() && "No class template?");
134       if (Spec->getSpecializedTemplate()->isMemberSpecialization())
135         break;
136     }
137     // Add template arguments from a function template specialization.
138     else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
139       if (!RelativeToPrimary &&
140           Function->getTemplateSpecializationKindForInstantiation() ==
141               TSK_ExplicitSpecialization)
142         break;
143 
144       if (const TemplateArgumentList *TemplateArgs
145             = Function->getTemplateSpecializationArgs()) {
146         // Add the template arguments for this specialization.
147         Result.addOuterTemplateArguments(TemplateArgs);
148 
149         // If this function was instantiated from a specialized member that is
150         // a function template, we're done.
151         assert(Function->getPrimaryTemplate() && "No function template?");
152         if (Function->getPrimaryTemplate()->isMemberSpecialization())
153           break;
154 
155         // If this function is a generic lambda specialization, we are done.
156         if (isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
157           break;
158 
159       } else if (FunctionTemplateDecl *FunTmpl
160                                    = Function->getDescribedFunctionTemplate()) {
161         // Add the "injected" template arguments.
162         Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
163       }
164 
165       // If this is a friend declaration and it declares an entity at
166       // namespace scope, take arguments from its lexical parent
167       // instead of its semantic parent, unless of course the pattern we're
168       // instantiating actually comes from the file's context!
169       if (Function->getFriendObjectKind() &&
170           Function->getDeclContext()->isFileContext() &&
171           (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
172         Ctx = Function->getLexicalDeclContext();
173         RelativeToPrimary = false;
174         continue;
175       }
176     } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
177       if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
178         QualType T = ClassTemplate->getInjectedClassNameSpecialization();
179         const TemplateSpecializationType *TST =
180             cast<TemplateSpecializationType>(Context.getCanonicalType(T));
181         Result.addOuterTemplateArguments(
182             llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
183         if (ClassTemplate->isMemberSpecialization())
184           break;
185       }
186     }
187 
188     Ctx = Ctx->getParent();
189     RelativeToPrimary = false;
190   }
191 
192   return Result;
193 }
194 
195 bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
196   switch (Kind) {
197   case TemplateInstantiation:
198   case ExceptionSpecInstantiation:
199   case DefaultTemplateArgumentInstantiation:
200   case DefaultFunctionArgumentInstantiation:
201   case ExplicitTemplateArgumentSubstitution:
202   case DeducedTemplateArgumentSubstitution:
203   case PriorTemplateArgumentSubstitution:
204   case ConstraintsCheck:
205   case NestedRequirementConstraintsCheck:
206     return true;
207 
208   case RequirementInstantiation:
209   case DefaultTemplateArgumentChecking:
210   case DeclaringSpecialMember:
211   case DeclaringImplicitEqualityComparison:
212   case DefiningSynthesizedFunction:
213   case ExceptionSpecEvaluation:
214   case ConstraintSubstitution:
215   case ParameterMappingSubstitution:
216   case ConstraintNormalization:
217   case RewritingOperatorAsSpaceship:
218     return false;
219 
220   // This function should never be called when Kind's value is Memoization.
221   case Memoization:
222     break;
223   }
224 
225   llvm_unreachable("Invalid SynthesisKind!");
226 }
227 
228 Sema::InstantiatingTemplate::InstantiatingTemplate(
229     Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
230     SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
231     Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
232     sema::TemplateDeductionInfo *DeductionInfo)
233     : SemaRef(SemaRef) {
234   // Don't allow further instantiation if a fatal error and an uncompilable
235   // error have occurred. Any diagnostics we might have raised will not be
236   // visible, and we do not need to construct a correct AST.
237   if (SemaRef.Diags.hasFatalErrorOccurred() &&
238       SemaRef.Diags.hasUncompilableErrorOccurred()) {
239     Invalid = true;
240     return;
241   }
242   Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
243   if (!Invalid) {
244     CodeSynthesisContext Inst;
245     Inst.Kind = Kind;
246     Inst.PointOfInstantiation = PointOfInstantiation;
247     Inst.Entity = Entity;
248     Inst.Template = Template;
249     Inst.TemplateArgs = TemplateArgs.data();
250     Inst.NumTemplateArgs = TemplateArgs.size();
251     Inst.DeductionInfo = DeductionInfo;
252     Inst.InstantiationRange = InstantiationRange;
253     SemaRef.pushCodeSynthesisContext(Inst);
254 
255     AlreadyInstantiating = !Inst.Entity ? false :
256         !SemaRef.InstantiatingSpecializations
257              .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
258              .second;
259     atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
260   }
261 }
262 
263 Sema::InstantiatingTemplate::InstantiatingTemplate(
264     Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
265     SourceRange InstantiationRange)
266     : InstantiatingTemplate(SemaRef,
267                             CodeSynthesisContext::TemplateInstantiation,
268                             PointOfInstantiation, InstantiationRange, Entity) {}
269 
270 Sema::InstantiatingTemplate::InstantiatingTemplate(
271     Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
272     ExceptionSpecification, SourceRange InstantiationRange)
273     : InstantiatingTemplate(
274           SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
275           PointOfInstantiation, InstantiationRange, Entity) {}
276 
277 Sema::InstantiatingTemplate::InstantiatingTemplate(
278     Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
279     TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
280     SourceRange InstantiationRange)
281     : InstantiatingTemplate(
282           SemaRef,
283           CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
284           PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
285           Template, TemplateArgs) {}
286 
287 Sema::InstantiatingTemplate::InstantiatingTemplate(
288     Sema &SemaRef, SourceLocation PointOfInstantiation,
289     FunctionTemplateDecl *FunctionTemplate,
290     ArrayRef<TemplateArgument> TemplateArgs,
291     CodeSynthesisContext::SynthesisKind Kind,
292     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
293     : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
294                             InstantiationRange, FunctionTemplate, nullptr,
295                             TemplateArgs, &DeductionInfo) {
296   assert(
297     Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
298     Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
299 }
300 
301 Sema::InstantiatingTemplate::InstantiatingTemplate(
302     Sema &SemaRef, SourceLocation PointOfInstantiation,
303     TemplateDecl *Template,
304     ArrayRef<TemplateArgument> TemplateArgs,
305     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
306     : InstantiatingTemplate(
307           SemaRef,
308           CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
309           PointOfInstantiation, InstantiationRange, Template, nullptr,
310           TemplateArgs, &DeductionInfo) {}
311 
312 Sema::InstantiatingTemplate::InstantiatingTemplate(
313     Sema &SemaRef, SourceLocation PointOfInstantiation,
314     ClassTemplatePartialSpecializationDecl *PartialSpec,
315     ArrayRef<TemplateArgument> TemplateArgs,
316     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
317     : InstantiatingTemplate(
318           SemaRef,
319           CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
320           PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
321           TemplateArgs, &DeductionInfo) {}
322 
323 Sema::InstantiatingTemplate::InstantiatingTemplate(
324     Sema &SemaRef, SourceLocation PointOfInstantiation,
325     VarTemplatePartialSpecializationDecl *PartialSpec,
326     ArrayRef<TemplateArgument> TemplateArgs,
327     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
328     : InstantiatingTemplate(
329           SemaRef,
330           CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
331           PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
332           TemplateArgs, &DeductionInfo) {}
333 
334 Sema::InstantiatingTemplate::InstantiatingTemplate(
335     Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
336     ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
337     : InstantiatingTemplate(
338           SemaRef,
339           CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
340           PointOfInstantiation, InstantiationRange, Param, nullptr,
341           TemplateArgs) {}
342 
343 Sema::InstantiatingTemplate::InstantiatingTemplate(
344     Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
345     NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
346     SourceRange InstantiationRange)
347     : InstantiatingTemplate(
348           SemaRef,
349           CodeSynthesisContext::PriorTemplateArgumentSubstitution,
350           PointOfInstantiation, InstantiationRange, Param, Template,
351           TemplateArgs) {}
352 
353 Sema::InstantiatingTemplate::InstantiatingTemplate(
354     Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
355     TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
356     SourceRange InstantiationRange)
357     : InstantiatingTemplate(
358           SemaRef,
359           CodeSynthesisContext::PriorTemplateArgumentSubstitution,
360           PointOfInstantiation, InstantiationRange, Param, Template,
361           TemplateArgs) {}
362 
363 Sema::InstantiatingTemplate::InstantiatingTemplate(
364     Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
365     NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
366     SourceRange InstantiationRange)
367     : InstantiatingTemplate(
368           SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
369           PointOfInstantiation, InstantiationRange, Param, Template,
370           TemplateArgs) {}
371 
372 Sema::InstantiatingTemplate::InstantiatingTemplate(
373     Sema &SemaRef, SourceLocation PointOfInstantiation,
374     concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo,
375     SourceRange InstantiationRange)
376     : InstantiatingTemplate(
377           SemaRef, CodeSynthesisContext::RequirementInstantiation,
378           PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
379           /*Template=*/nullptr, /*TemplateArgs=*/None, &DeductionInfo) {}
380 
381 
382 Sema::InstantiatingTemplate::InstantiatingTemplate(
383     Sema &SemaRef, SourceLocation PointOfInstantiation,
384     concepts::NestedRequirement *Req, ConstraintsCheck,
385     SourceRange InstantiationRange)
386     : InstantiatingTemplate(
387           SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
388           PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
389           /*Template=*/nullptr, /*TemplateArgs=*/None) {}
390 
391 
392 Sema::InstantiatingTemplate::InstantiatingTemplate(
393     Sema &SemaRef, SourceLocation PointOfInstantiation,
394     ConstraintsCheck, NamedDecl *Template,
395     ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
396     : InstantiatingTemplate(
397           SemaRef, CodeSynthesisContext::ConstraintsCheck,
398           PointOfInstantiation, InstantiationRange, Template, nullptr,
399           TemplateArgs) {}
400 
401 Sema::InstantiatingTemplate::InstantiatingTemplate(
402     Sema &SemaRef, SourceLocation PointOfInstantiation,
403     ConstraintSubstitution, NamedDecl *Template,
404     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
405     : InstantiatingTemplate(
406           SemaRef, CodeSynthesisContext::ConstraintSubstitution,
407           PointOfInstantiation, InstantiationRange, Template, nullptr,
408           {}, &DeductionInfo) {}
409 
410 Sema::InstantiatingTemplate::InstantiatingTemplate(
411     Sema &SemaRef, SourceLocation PointOfInstantiation,
412     ConstraintNormalization, NamedDecl *Template,
413     SourceRange InstantiationRange)
414     : InstantiatingTemplate(
415           SemaRef, CodeSynthesisContext::ConstraintNormalization,
416           PointOfInstantiation, InstantiationRange, Template) {}
417 
418 Sema::InstantiatingTemplate::InstantiatingTemplate(
419     Sema &SemaRef, SourceLocation PointOfInstantiation,
420     ParameterMappingSubstitution, NamedDecl *Template,
421     SourceRange InstantiationRange)
422     : InstantiatingTemplate(
423           SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
424           PointOfInstantiation, InstantiationRange, Template) {}
425 
426 void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
427   Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
428   InNonInstantiationSFINAEContext = false;
429 
430   CodeSynthesisContexts.push_back(Ctx);
431 
432   if (!Ctx.isInstantiationRecord())
433     ++NonInstantiationEntries;
434 
435   // Check to see if we're low on stack space. We can't do anything about this
436   // from here, but we can at least warn the user.
437   if (isStackNearlyExhausted())
438     warnStackExhausted(Ctx.PointOfInstantiation);
439 }
440 
441 void Sema::popCodeSynthesisContext() {
442   auto &Active = CodeSynthesisContexts.back();
443   if (!Active.isInstantiationRecord()) {
444     assert(NonInstantiationEntries > 0);
445     --NonInstantiationEntries;
446   }
447 
448   InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
449 
450   // Name lookup no longer looks in this template's defining module.
451   assert(CodeSynthesisContexts.size() >=
452              CodeSynthesisContextLookupModules.size() &&
453          "forgot to remove a lookup module for a template instantiation");
454   if (CodeSynthesisContexts.size() ==
455       CodeSynthesisContextLookupModules.size()) {
456     if (Module *M = CodeSynthesisContextLookupModules.back())
457       LookupModulesCache.erase(M);
458     CodeSynthesisContextLookupModules.pop_back();
459   }
460 
461   // If we've left the code synthesis context for the current context stack,
462   // stop remembering that we've emitted that stack.
463   if (CodeSynthesisContexts.size() ==
464       LastEmittedCodeSynthesisContextDepth)
465     LastEmittedCodeSynthesisContextDepth = 0;
466 
467   CodeSynthesisContexts.pop_back();
468 }
469 
470 void Sema::InstantiatingTemplate::Clear() {
471   if (!Invalid) {
472     if (!AlreadyInstantiating) {
473       auto &Active = SemaRef.CodeSynthesisContexts.back();
474       if (Active.Entity)
475         SemaRef.InstantiatingSpecializations.erase(
476             std::make_pair(Active.Entity, Active.Kind));
477     }
478 
479     atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
480                   SemaRef.CodeSynthesisContexts.back());
481 
482     SemaRef.popCodeSynthesisContext();
483     Invalid = true;
484   }
485 }
486 
487 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
488                                         SourceLocation PointOfInstantiation,
489                                            SourceRange InstantiationRange) {
490   assert(SemaRef.NonInstantiationEntries <=
491          SemaRef.CodeSynthesisContexts.size());
492   if ((SemaRef.CodeSynthesisContexts.size() -
493           SemaRef.NonInstantiationEntries)
494         <= SemaRef.getLangOpts().InstantiationDepth)
495     return false;
496 
497   SemaRef.Diag(PointOfInstantiation,
498                diag::err_template_recursion_depth_exceeded)
499     << SemaRef.getLangOpts().InstantiationDepth
500     << InstantiationRange;
501   SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
502     << SemaRef.getLangOpts().InstantiationDepth;
503   return true;
504 }
505 
506 /// Prints the current instantiation stack through a series of
507 /// notes.
508 void Sema::PrintInstantiationStack() {
509   // Determine which template instantiations to skip, if any.
510   unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
511   unsigned Limit = Diags.getTemplateBacktraceLimit();
512   if (Limit && Limit < CodeSynthesisContexts.size()) {
513     SkipStart = Limit / 2 + Limit % 2;
514     SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
515   }
516 
517   // FIXME: In all of these cases, we need to show the template arguments
518   unsigned InstantiationIdx = 0;
519   for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
520          Active = CodeSynthesisContexts.rbegin(),
521          ActiveEnd = CodeSynthesisContexts.rend();
522        Active != ActiveEnd;
523        ++Active, ++InstantiationIdx) {
524     // Skip this instantiation?
525     if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
526       if (InstantiationIdx == SkipStart) {
527         // Note that we're skipping instantiations.
528         Diags.Report(Active->PointOfInstantiation,
529                      diag::note_instantiation_contexts_suppressed)
530           << unsigned(CodeSynthesisContexts.size() - Limit);
531       }
532       continue;
533     }
534 
535     switch (Active->Kind) {
536     case CodeSynthesisContext::TemplateInstantiation: {
537       Decl *D = Active->Entity;
538       if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
539         unsigned DiagID = diag::note_template_member_class_here;
540         if (isa<ClassTemplateSpecializationDecl>(Record))
541           DiagID = diag::note_template_class_instantiation_here;
542         Diags.Report(Active->PointOfInstantiation, DiagID)
543           << Record << Active->InstantiationRange;
544       } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
545         unsigned DiagID;
546         if (Function->getPrimaryTemplate())
547           DiagID = diag::note_function_template_spec_here;
548         else
549           DiagID = diag::note_template_member_function_here;
550         Diags.Report(Active->PointOfInstantiation, DiagID)
551           << Function
552           << Active->InstantiationRange;
553       } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
554         Diags.Report(Active->PointOfInstantiation,
555                      VD->isStaticDataMember()?
556                        diag::note_template_static_data_member_def_here
557                      : diag::note_template_variable_def_here)
558           << VD
559           << Active->InstantiationRange;
560       } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
561         Diags.Report(Active->PointOfInstantiation,
562                      diag::note_template_enum_def_here)
563           << ED
564           << Active->InstantiationRange;
565       } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
566         Diags.Report(Active->PointOfInstantiation,
567                      diag::note_template_nsdmi_here)
568             << FD << Active->InstantiationRange;
569       } else {
570         Diags.Report(Active->PointOfInstantiation,
571                      diag::note_template_type_alias_instantiation_here)
572           << cast<TypeAliasTemplateDecl>(D)
573           << Active->InstantiationRange;
574       }
575       break;
576     }
577 
578     case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
579       TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
580       SmallVector<char, 128> TemplateArgsStr;
581       llvm::raw_svector_ostream OS(TemplateArgsStr);
582       Template->printName(OS);
583       printTemplateArgumentList(OS, Active->template_arguments(),
584                                 getPrintingPolicy());
585       Diags.Report(Active->PointOfInstantiation,
586                    diag::note_default_arg_instantiation_here)
587         << OS.str()
588         << Active->InstantiationRange;
589       break;
590     }
591 
592     case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
593       FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
594       Diags.Report(Active->PointOfInstantiation,
595                    diag::note_explicit_template_arg_substitution_here)
596         << FnTmpl
597         << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
598                                            Active->TemplateArgs,
599                                            Active->NumTemplateArgs)
600         << Active->InstantiationRange;
601       break;
602     }
603 
604     case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
605       if (FunctionTemplateDecl *FnTmpl =
606               dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
607         Diags.Report(Active->PointOfInstantiation,
608                      diag::note_function_template_deduction_instantiation_here)
609           << FnTmpl
610           << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
611                                              Active->TemplateArgs,
612                                              Active->NumTemplateArgs)
613           << Active->InstantiationRange;
614       } else {
615         bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
616                      isa<VarTemplateSpecializationDecl>(Active->Entity);
617         bool IsTemplate = false;
618         TemplateParameterList *Params;
619         if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
620           IsTemplate = true;
621           Params = D->getTemplateParameters();
622         } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
623                        Active->Entity)) {
624           Params = D->getTemplateParameters();
625         } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
626                        Active->Entity)) {
627           Params = D->getTemplateParameters();
628         } else {
629           llvm_unreachable("unexpected template kind");
630         }
631 
632         Diags.Report(Active->PointOfInstantiation,
633                      diag::note_deduced_template_arg_substitution_here)
634           << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
635           << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
636                                              Active->NumTemplateArgs)
637           << Active->InstantiationRange;
638       }
639       break;
640     }
641 
642     case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
643       ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
644       FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
645 
646       SmallVector<char, 128> TemplateArgsStr;
647       llvm::raw_svector_ostream OS(TemplateArgsStr);
648       FD->printName(OS);
649       printTemplateArgumentList(OS, Active->template_arguments(),
650                                 getPrintingPolicy());
651       Diags.Report(Active->PointOfInstantiation,
652                    diag::note_default_function_arg_instantiation_here)
653         << OS.str()
654         << Active->InstantiationRange;
655       break;
656     }
657 
658     case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
659       NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
660       std::string Name;
661       if (!Parm->getName().empty())
662         Name = std::string(" '") + Parm->getName().str() + "'";
663 
664       TemplateParameterList *TemplateParams = nullptr;
665       if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
666         TemplateParams = Template->getTemplateParameters();
667       else
668         TemplateParams =
669           cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
670                                                       ->getTemplateParameters();
671       Diags.Report(Active->PointOfInstantiation,
672                    diag::note_prior_template_arg_substitution)
673         << isa<TemplateTemplateParmDecl>(Parm)
674         << Name
675         << getTemplateArgumentBindingsText(TemplateParams,
676                                            Active->TemplateArgs,
677                                            Active->NumTemplateArgs)
678         << Active->InstantiationRange;
679       break;
680     }
681 
682     case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
683       TemplateParameterList *TemplateParams = nullptr;
684       if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
685         TemplateParams = Template->getTemplateParameters();
686       else
687         TemplateParams =
688           cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
689                                                       ->getTemplateParameters();
690 
691       Diags.Report(Active->PointOfInstantiation,
692                    diag::note_template_default_arg_checking)
693         << getTemplateArgumentBindingsText(TemplateParams,
694                                            Active->TemplateArgs,
695                                            Active->NumTemplateArgs)
696         << Active->InstantiationRange;
697       break;
698     }
699 
700     case CodeSynthesisContext::ExceptionSpecEvaluation:
701       Diags.Report(Active->PointOfInstantiation,
702                    diag::note_evaluating_exception_spec_here)
703           << cast<FunctionDecl>(Active->Entity);
704       break;
705 
706     case CodeSynthesisContext::ExceptionSpecInstantiation:
707       Diags.Report(Active->PointOfInstantiation,
708                    diag::note_template_exception_spec_instantiation_here)
709         << cast<FunctionDecl>(Active->Entity)
710         << Active->InstantiationRange;
711       break;
712 
713     case CodeSynthesisContext::RequirementInstantiation:
714       Diags.Report(Active->PointOfInstantiation,
715                    diag::note_template_requirement_instantiation_here)
716         << Active->InstantiationRange;
717       break;
718 
719     case CodeSynthesisContext::NestedRequirementConstraintsCheck:
720       Diags.Report(Active->PointOfInstantiation,
721                    diag::note_nested_requirement_here)
722         << Active->InstantiationRange;
723       break;
724 
725     case CodeSynthesisContext::DeclaringSpecialMember:
726       Diags.Report(Active->PointOfInstantiation,
727                    diag::note_in_declaration_of_implicit_special_member)
728         << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
729       break;
730 
731     case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
732       Diags.Report(Active->Entity->getLocation(),
733                    diag::note_in_declaration_of_implicit_equality_comparison);
734       break;
735 
736     case CodeSynthesisContext::DefiningSynthesizedFunction: {
737       // FIXME: For synthesized functions that are not defaulted,
738       // produce a note.
739       auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
740       DefaultedFunctionKind DFK =
741           FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
742       if (DFK.isSpecialMember()) {
743         auto *MD = cast<CXXMethodDecl>(FD);
744         Diags.Report(Active->PointOfInstantiation,
745                      diag::note_member_synthesized_at)
746             << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
747             << Context.getTagDeclType(MD->getParent());
748       } else if (DFK.isComparison()) {
749         Diags.Report(Active->PointOfInstantiation,
750                      diag::note_comparison_synthesized_at)
751             << (int)DFK.asComparison()
752             << Context.getTagDeclType(
753                    cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
754       }
755       break;
756     }
757 
758     case CodeSynthesisContext::RewritingOperatorAsSpaceship:
759       Diags.Report(Active->Entity->getLocation(),
760                    diag::note_rewriting_operator_as_spaceship);
761       break;
762 
763     case CodeSynthesisContext::Memoization:
764       break;
765 
766     case CodeSynthesisContext::ConstraintsCheck: {
767       unsigned DiagID = 0;
768       if (!Active->Entity) {
769         Diags.Report(Active->PointOfInstantiation,
770                      diag::note_nested_requirement_here)
771           << Active->InstantiationRange;
772         break;
773       }
774       if (isa<ConceptDecl>(Active->Entity))
775         DiagID = diag::note_concept_specialization_here;
776       else if (isa<TemplateDecl>(Active->Entity))
777         DiagID = diag::note_checking_constraints_for_template_id_here;
778       else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
779         DiagID = diag::note_checking_constraints_for_var_spec_id_here;
780       else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
781         DiagID = diag::note_checking_constraints_for_class_spec_id_here;
782       else {
783         assert(isa<FunctionDecl>(Active->Entity));
784         DiagID = diag::note_checking_constraints_for_function_here;
785       }
786       SmallVector<char, 128> TemplateArgsStr;
787       llvm::raw_svector_ostream OS(TemplateArgsStr);
788       cast<NamedDecl>(Active->Entity)->printName(OS);
789       if (!isa<FunctionDecl>(Active->Entity))
790         printTemplateArgumentList(OS, Active->template_arguments(),
791                                   getPrintingPolicy());
792       Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
793         << Active->InstantiationRange;
794       break;
795     }
796     case CodeSynthesisContext::ConstraintSubstitution:
797       Diags.Report(Active->PointOfInstantiation,
798                    diag::note_constraint_substitution_here)
799           << Active->InstantiationRange;
800       break;
801     case CodeSynthesisContext::ConstraintNormalization:
802       Diags.Report(Active->PointOfInstantiation,
803                    diag::note_constraint_normalization_here)
804           << cast<NamedDecl>(Active->Entity)->getName()
805           << Active->InstantiationRange;
806       break;
807     case CodeSynthesisContext::ParameterMappingSubstitution:
808       Diags.Report(Active->PointOfInstantiation,
809                    diag::note_parameter_mapping_substitution_here)
810           << Active->InstantiationRange;
811       break;
812     }
813   }
814 }
815 
816 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
817   if (InNonInstantiationSFINAEContext)
818     return Optional<TemplateDeductionInfo *>(nullptr);
819 
820   for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
821          Active = CodeSynthesisContexts.rbegin(),
822          ActiveEnd = CodeSynthesisContexts.rend();
823        Active != ActiveEnd;
824        ++Active)
825   {
826     switch (Active->Kind) {
827     case CodeSynthesisContext::TemplateInstantiation:
828       // An instantiation of an alias template may or may not be a SFINAE
829       // context, depending on what else is on the stack.
830       if (isa<TypeAliasTemplateDecl>(Active->Entity))
831         break;
832       LLVM_FALLTHROUGH;
833     case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
834     case CodeSynthesisContext::ExceptionSpecInstantiation:
835     case CodeSynthesisContext::ConstraintsCheck:
836     case CodeSynthesisContext::ParameterMappingSubstitution:
837     case CodeSynthesisContext::ConstraintNormalization:
838     case CodeSynthesisContext::NestedRequirementConstraintsCheck:
839       // This is a template instantiation, so there is no SFINAE.
840       return None;
841 
842     case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
843     case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
844     case CodeSynthesisContext::DefaultTemplateArgumentChecking:
845       // A default template argument instantiation and substitution into
846       // template parameters with arguments for prior parameters may or may
847       // not be a SFINAE context; look further up the stack.
848       break;
849 
850     case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
851     case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
852     case CodeSynthesisContext::ConstraintSubstitution:
853     case CodeSynthesisContext::RequirementInstantiation:
854       // We're either substituting explicitly-specified template arguments,
855       // deduced template arguments, a constraint expression or a requirement
856       // in a requires expression, so SFINAE applies.
857       assert(Active->DeductionInfo && "Missing deduction info pointer");
858       return Active->DeductionInfo;
859 
860     case CodeSynthesisContext::DeclaringSpecialMember:
861     case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
862     case CodeSynthesisContext::DefiningSynthesizedFunction:
863     case CodeSynthesisContext::RewritingOperatorAsSpaceship:
864       // This happens in a context unrelated to template instantiation, so
865       // there is no SFINAE.
866       return None;
867 
868     case CodeSynthesisContext::ExceptionSpecEvaluation:
869       // FIXME: This should not be treated as a SFINAE context, because
870       // we will cache an incorrect exception specification. However, clang
871       // bootstrap relies this! See PR31692.
872       break;
873 
874     case CodeSynthesisContext::Memoization:
875       break;
876     }
877 
878     // The inner context was transparent for SFINAE. If it occurred within a
879     // non-instantiation SFINAE context, then SFINAE applies.
880     if (Active->SavedInNonInstantiationSFINAEContext)
881       return Optional<TemplateDeductionInfo *>(nullptr);
882   }
883 
884   return None;
885 }
886 
887 //===----------------------------------------------------------------------===/
888 // Template Instantiation for Types
889 //===----------------------------------------------------------------------===/
890 namespace {
891   class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
892     const MultiLevelTemplateArgumentList &TemplateArgs;
893     SourceLocation Loc;
894     DeclarationName Entity;
895 
896   public:
897     typedef TreeTransform<TemplateInstantiator> inherited;
898 
899     TemplateInstantiator(Sema &SemaRef,
900                          const MultiLevelTemplateArgumentList &TemplateArgs,
901                          SourceLocation Loc,
902                          DeclarationName Entity)
903       : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
904         Entity(Entity) { }
905 
906     /// Determine whether the given type \p T has already been
907     /// transformed.
908     ///
909     /// For the purposes of template instantiation, a type has already been
910     /// transformed if it is NULL or if it is not dependent.
911     bool AlreadyTransformed(QualType T);
912 
913     /// Returns the location of the entity being instantiated, if known.
914     SourceLocation getBaseLocation() { return Loc; }
915 
916     /// Returns the name of the entity being instantiated, if any.
917     DeclarationName getBaseEntity() { return Entity; }
918 
919     /// Sets the "base" location and entity when that
920     /// information is known based on another transformation.
921     void setBase(SourceLocation Loc, DeclarationName Entity) {
922       this->Loc = Loc;
923       this->Entity = Entity;
924     }
925 
926     unsigned TransformTemplateDepth(unsigned Depth) {
927       return TemplateArgs.getNewDepth(Depth);
928     }
929 
930     bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
931                                  SourceRange PatternRange,
932                                  ArrayRef<UnexpandedParameterPack> Unexpanded,
933                                  bool &ShouldExpand, bool &RetainExpansion,
934                                  Optional<unsigned> &NumExpansions) {
935       return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
936                                                        PatternRange, Unexpanded,
937                                                        TemplateArgs,
938                                                        ShouldExpand,
939                                                        RetainExpansion,
940                                                        NumExpansions);
941     }
942 
943     void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
944       SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
945     }
946 
947     TemplateArgument ForgetPartiallySubstitutedPack() {
948       TemplateArgument Result;
949       if (NamedDecl *PartialPack
950             = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
951         MultiLevelTemplateArgumentList &TemplateArgs
952           = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
953         unsigned Depth, Index;
954         std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
955         if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
956           Result = TemplateArgs(Depth, Index);
957           TemplateArgs.setArgument(Depth, Index, TemplateArgument());
958         }
959       }
960 
961       return Result;
962     }
963 
964     void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
965       if (Arg.isNull())
966         return;
967 
968       if (NamedDecl *PartialPack
969             = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
970         MultiLevelTemplateArgumentList &TemplateArgs
971         = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
972         unsigned Depth, Index;
973         std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
974         TemplateArgs.setArgument(Depth, Index, Arg);
975       }
976     }
977 
978     /// Transform the given declaration by instantiating a reference to
979     /// this declaration.
980     Decl *TransformDecl(SourceLocation Loc, Decl *D);
981 
982     void transformAttrs(Decl *Old, Decl *New) {
983       SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
984     }
985 
986     void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
987       if (Old->isParameterPack()) {
988         SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
989         for (auto *New : NewDecls)
990           SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
991               Old, cast<VarDecl>(New));
992         return;
993       }
994 
995       assert(NewDecls.size() == 1 &&
996              "should only have multiple expansions for a pack");
997       Decl *New = NewDecls.front();
998 
999       // If we've instantiated the call operator of a lambda or the call
1000       // operator template of a generic lambda, update the "instantiation of"
1001       // information.
1002       auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1003       if (NewMD && isLambdaCallOperator(NewMD)) {
1004         auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1005         if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1006           NewTD->setInstantiatedFromMemberTemplate(
1007               OldMD->getDescribedFunctionTemplate());
1008         else
1009           NewMD->setInstantiationOfMemberFunction(OldMD,
1010                                                   TSK_ImplicitInstantiation);
1011       }
1012 
1013       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
1014 
1015       // We recreated a local declaration, but not by instantiating it. There
1016       // may be pending dependent diagnostics to produce.
1017       if (auto *DC = dyn_cast<DeclContext>(Old))
1018         SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1019     }
1020 
1021     /// Transform the definition of the given declaration by
1022     /// instantiating it.
1023     Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1024 
1025     /// Transform the first qualifier within a scope by instantiating the
1026     /// declaration.
1027     NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1028 
1029     /// Rebuild the exception declaration and register the declaration
1030     /// as an instantiated local.
1031     VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1032                                   TypeSourceInfo *Declarator,
1033                                   SourceLocation StartLoc,
1034                                   SourceLocation NameLoc,
1035                                   IdentifierInfo *Name);
1036 
1037     /// Rebuild the Objective-C exception declaration and register the
1038     /// declaration as an instantiated local.
1039     VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1040                                       TypeSourceInfo *TSInfo, QualType T);
1041 
1042     /// Check for tag mismatches when instantiating an
1043     /// elaborated type.
1044     QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1045                                    ElaboratedTypeKeyword Keyword,
1046                                    NestedNameSpecifierLoc QualifierLoc,
1047                                    QualType T);
1048 
1049     TemplateName
1050     TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1051                           SourceLocation NameLoc,
1052                           QualType ObjectType = QualType(),
1053                           NamedDecl *FirstQualifierInScope = nullptr,
1054                           bool AllowInjectedClassName = false);
1055 
1056     const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1057 
1058     ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1059     ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1060     ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1061 
1062     ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1063                                             NonTypeTemplateParmDecl *D);
1064     ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1065                                            SubstNonTypeTemplateParmPackExpr *E);
1066     ExprResult TransformSubstNonTypeTemplateParmExpr(
1067                                            SubstNonTypeTemplateParmExpr *E);
1068 
1069     /// Rebuild a DeclRefExpr for a VarDecl reference.
1070     ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1071 
1072     /// Transform a reference to a function or init-capture parameter pack.
1073     ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1074 
1075     /// Transform a FunctionParmPackExpr which was built when we couldn't
1076     /// expand a function parameter pack reference which refers to an expanded
1077     /// pack.
1078     ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1079 
1080     QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1081                                         FunctionProtoTypeLoc TL) {
1082       // Call the base version; it will forward to our overridden version below.
1083       return inherited::TransformFunctionProtoType(TLB, TL);
1084     }
1085 
1086     template<typename Fn>
1087     QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1088                                         FunctionProtoTypeLoc TL,
1089                                         CXXRecordDecl *ThisContext,
1090                                         Qualifiers ThisTypeQuals,
1091                                         Fn TransformExceptionSpec);
1092 
1093     ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1094                                             int indexAdjustment,
1095                                             Optional<unsigned> NumExpansions,
1096                                             bool ExpectParameterPack);
1097 
1098     /// Transforms a template type parameter type by performing
1099     /// substitution of the corresponding template type argument.
1100     QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1101                                            TemplateTypeParmTypeLoc TL);
1102 
1103     /// Transforms an already-substituted template type parameter pack
1104     /// into either itself (if we aren't substituting into its pack expansion)
1105     /// or the appropriate substituted argument.
1106     QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1107                                            SubstTemplateTypeParmPackTypeLoc TL);
1108 
1109     ExprResult TransformLambdaExpr(LambdaExpr *E) {
1110       LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1111       return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
1112     }
1113 
1114     ExprResult TransformRequiresExpr(RequiresExpr *E) {
1115       LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1116       return TreeTransform<TemplateInstantiator>::TransformRequiresExpr(E);
1117     }
1118 
1119     bool TransformRequiresExprRequirements(
1120         ArrayRef<concepts::Requirement *> Reqs,
1121         SmallVectorImpl<concepts::Requirement *> &Transformed) {
1122       bool SatisfactionDetermined = false;
1123       for (concepts::Requirement *Req : Reqs) {
1124         concepts::Requirement *TransReq = nullptr;
1125         if (!SatisfactionDetermined) {
1126           if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1127             TransReq = TransformTypeRequirement(TypeReq);
1128           else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1129             TransReq = TransformExprRequirement(ExprReq);
1130           else
1131             TransReq = TransformNestedRequirement(
1132                 cast<concepts::NestedRequirement>(Req));
1133           if (!TransReq)
1134             return true;
1135           if (!TransReq->isDependent() && !TransReq->isSatisfied())
1136             // [expr.prim.req]p6
1137             //   [...]  The substitution and semantic constraint checking
1138             //   proceeds in lexical order and stops when a condition that
1139             //   determines the result of the requires-expression is
1140             //   encountered. [..]
1141             SatisfactionDetermined = true;
1142         } else
1143           TransReq = Req;
1144         Transformed.push_back(TransReq);
1145       }
1146       return false;
1147     }
1148 
1149     TemplateParameterList *TransformTemplateParameterList(
1150                               TemplateParameterList *OrigTPL)  {
1151       if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1152 
1153       DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1154       TemplateDeclInstantiator  DeclInstantiator(getSema(),
1155                         /* DeclContext *Owner */ Owner, TemplateArgs);
1156       return DeclInstantiator.SubstTemplateParams(OrigTPL);
1157     }
1158 
1159     concepts::TypeRequirement *
1160     TransformTypeRequirement(concepts::TypeRequirement *Req);
1161     concepts::ExprRequirement *
1162     TransformExprRequirement(concepts::ExprRequirement *Req);
1163     concepts::NestedRequirement *
1164     TransformNestedRequirement(concepts::NestedRequirement *Req);
1165 
1166   private:
1167     ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
1168                                                SourceLocation loc,
1169                                                TemplateArgument arg);
1170   };
1171 }
1172 
1173 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1174   if (T.isNull())
1175     return true;
1176 
1177   if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
1178     return false;
1179 
1180   getSema().MarkDeclarationsReferencedInType(Loc, T);
1181   return true;
1182 }
1183 
1184 static TemplateArgument
1185 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1186   assert(S.ArgumentPackSubstitutionIndex >= 0);
1187   assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1188   Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1189   if (Arg.isPackExpansion())
1190     Arg = Arg.getPackExpansionPattern();
1191   return Arg;
1192 }
1193 
1194 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1195   if (!D)
1196     return nullptr;
1197 
1198   if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1199     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1200       // If the corresponding template argument is NULL or non-existent, it's
1201       // because we are performing instantiation from explicitly-specified
1202       // template arguments in a function template, but there were some
1203       // arguments left unspecified.
1204       if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1205                                             TTP->getPosition()))
1206         return D;
1207 
1208       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1209 
1210       if (TTP->isParameterPack()) {
1211         assert(Arg.getKind() == TemplateArgument::Pack &&
1212                "Missing argument pack");
1213         Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1214       }
1215 
1216       TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1217       assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1218              "Wrong kind of template template argument");
1219       return Template.getAsTemplateDecl();
1220     }
1221 
1222     // Fall through to find the instantiated declaration for this template
1223     // template parameter.
1224   }
1225 
1226   return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1227 }
1228 
1229 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1230   Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1231   if (!Inst)
1232     return nullptr;
1233 
1234   getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1235   return Inst;
1236 }
1237 
1238 NamedDecl *
1239 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1240                                                      SourceLocation Loc) {
1241   // If the first part of the nested-name-specifier was a template type
1242   // parameter, instantiate that type parameter down to a tag type.
1243   if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1244     const TemplateTypeParmType *TTP
1245       = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1246 
1247     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1248       // FIXME: This needs testing w/ member access expressions.
1249       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1250 
1251       if (TTP->isParameterPack()) {
1252         assert(Arg.getKind() == TemplateArgument::Pack &&
1253                "Missing argument pack");
1254 
1255         if (getSema().ArgumentPackSubstitutionIndex == -1)
1256           return nullptr;
1257 
1258         Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1259       }
1260 
1261       QualType T = Arg.getAsType();
1262       if (T.isNull())
1263         return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1264 
1265       if (const TagType *Tag = T->getAs<TagType>())
1266         return Tag->getDecl();
1267 
1268       // The resulting type is not a tag; complain.
1269       getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1270       return nullptr;
1271     }
1272   }
1273 
1274   return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1275 }
1276 
1277 VarDecl *
1278 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1279                                            TypeSourceInfo *Declarator,
1280                                            SourceLocation StartLoc,
1281                                            SourceLocation NameLoc,
1282                                            IdentifierInfo *Name) {
1283   VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1284                                                  StartLoc, NameLoc, Name);
1285   if (Var)
1286     getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1287   return Var;
1288 }
1289 
1290 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1291                                                         TypeSourceInfo *TSInfo,
1292                                                         QualType T) {
1293   VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1294   if (Var)
1295     getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1296   return Var;
1297 }
1298 
1299 QualType
1300 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1301                                             ElaboratedTypeKeyword Keyword,
1302                                             NestedNameSpecifierLoc QualifierLoc,
1303                                             QualType T) {
1304   if (const TagType *TT = T->getAs<TagType>()) {
1305     TagDecl* TD = TT->getDecl();
1306 
1307     SourceLocation TagLocation = KeywordLoc;
1308 
1309     IdentifierInfo *Id = TD->getIdentifier();
1310 
1311     // TODO: should we even warn on struct/class mismatches for this?  Seems
1312     // like it's likely to produce a lot of spurious errors.
1313     if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1314       TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1315       if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1316                                                 TagLocation, Id)) {
1317         SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1318           << Id
1319           << FixItHint::CreateReplacement(SourceRange(TagLocation),
1320                                           TD->getKindName());
1321         SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1322       }
1323     }
1324   }
1325 
1326   return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1327                                                                     Keyword,
1328                                                                   QualifierLoc,
1329                                                                     T);
1330 }
1331 
1332 TemplateName TemplateInstantiator::TransformTemplateName(
1333     CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1334     QualType ObjectType, NamedDecl *FirstQualifierInScope,
1335     bool AllowInjectedClassName) {
1336   if (TemplateTemplateParmDecl *TTP
1337        = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1338     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1339       // If the corresponding template argument is NULL or non-existent, it's
1340       // because we are performing instantiation from explicitly-specified
1341       // template arguments in a function template, but there were some
1342       // arguments left unspecified.
1343       if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1344                                             TTP->getPosition()))
1345         return Name;
1346 
1347       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1348 
1349       if (TTP->isParameterPack()) {
1350         assert(Arg.getKind() == TemplateArgument::Pack &&
1351                "Missing argument pack");
1352 
1353         if (getSema().ArgumentPackSubstitutionIndex == -1) {
1354           // We have the template argument pack to substitute, but we're not
1355           // actually expanding the enclosing pack expansion yet. So, just
1356           // keep the entire argument pack.
1357           return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1358         }
1359 
1360         Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1361       }
1362 
1363       TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1364       assert(!Template.isNull() && "Null template template argument");
1365       assert(!Template.getAsQualifiedTemplateName() &&
1366              "template decl to substitute is qualified?");
1367 
1368       Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1369       return Template;
1370     }
1371   }
1372 
1373   if (SubstTemplateTemplateParmPackStorage *SubstPack
1374       = Name.getAsSubstTemplateTemplateParmPack()) {
1375     if (getSema().ArgumentPackSubstitutionIndex == -1)
1376       return Name;
1377 
1378     TemplateArgument Arg = SubstPack->getArgumentPack();
1379     Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1380     return Arg.getAsTemplate().getNameToSubstitute();
1381   }
1382 
1383   return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1384                                           FirstQualifierInScope,
1385                                           AllowInjectedClassName);
1386 }
1387 
1388 ExprResult
1389 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1390   if (!E->isTypeDependent())
1391     return E;
1392 
1393   return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1394 }
1395 
1396 ExprResult
1397 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1398                                                NonTypeTemplateParmDecl *NTTP) {
1399   // If the corresponding template argument is NULL or non-existent, it's
1400   // because we are performing instantiation from explicitly-specified
1401   // template arguments in a function template, but there were some
1402   // arguments left unspecified.
1403   if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1404                                         NTTP->getPosition()))
1405     return E;
1406 
1407   TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1408 
1409   if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1410     // We're performing a partial substitution, so the substituted argument
1411     // could be dependent. As a result we can't create a SubstNonType*Expr
1412     // node now, since that represents a fully-substituted argument.
1413     // FIXME: We should have some AST representation for this.
1414     if (Arg.getKind() == TemplateArgument::Pack) {
1415       // FIXME: This won't work for alias templates.
1416       assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1417              "unexpected pack arguments in partial substitution");
1418       Arg = Arg.pack_begin()->getPackExpansionPattern();
1419     }
1420     assert(Arg.getKind() == TemplateArgument::Expression &&
1421            "unexpected nontype template argument kind in partial substitution");
1422     return Arg.getAsExpr();
1423   }
1424 
1425   if (NTTP->isParameterPack()) {
1426     assert(Arg.getKind() == TemplateArgument::Pack &&
1427            "Missing argument pack");
1428 
1429     if (getSema().ArgumentPackSubstitutionIndex == -1) {
1430       // We have an argument pack, but we can't select a particular argument
1431       // out of it yet. Therefore, we'll build an expression to hold on to that
1432       // argument pack.
1433       QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1434                                               E->getLocation(),
1435                                               NTTP->getDeclName());
1436       if (TargetType.isNull())
1437         return ExprError();
1438 
1439       return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1440           TargetType.getNonLValueExprType(SemaRef.Context),
1441           TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1442           E->getLocation(), Arg);
1443     }
1444 
1445     Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1446   }
1447 
1448   return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1449 }
1450 
1451 const LoopHintAttr *
1452 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1453   Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1454 
1455   if (TransformedExpr == LH->getValue())
1456     return LH;
1457 
1458   // Generate error if there is a problem with the value.
1459   if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1460     return LH;
1461 
1462   // Create new LoopHintValueAttr with integral expression in place of the
1463   // non-type template parameter.
1464   return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1465                                       LH->getState(), TransformedExpr, *LH);
1466 }
1467 
1468 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1469                                                  NonTypeTemplateParmDecl *parm,
1470                                                  SourceLocation loc,
1471                                                  TemplateArgument arg) {
1472   ExprResult result;
1473   QualType type;
1474 
1475   // The template argument itself might be an expression, in which
1476   // case we just return that expression.
1477   if (arg.getKind() == TemplateArgument::Expression) {
1478     Expr *argExpr = arg.getAsExpr();
1479     result = argExpr;
1480     type = argExpr->getType();
1481 
1482   } else if (arg.getKind() == TemplateArgument::Declaration ||
1483              arg.getKind() == TemplateArgument::NullPtr) {
1484     ValueDecl *VD;
1485     if (arg.getKind() == TemplateArgument::Declaration) {
1486       VD = arg.getAsDecl();
1487 
1488       // Find the instantiation of the template argument.  This is
1489       // required for nested templates.
1490       VD = cast_or_null<ValueDecl>(
1491              getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1492       if (!VD)
1493         return ExprError();
1494     } else {
1495       // Propagate NULL template argument.
1496       VD = nullptr;
1497     }
1498 
1499     // Derive the type we want the substituted decl to have.  This had
1500     // better be non-dependent, or these checks will have serious problems.
1501     if (parm->isExpandedParameterPack()) {
1502       type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1503     } else if (parm->isParameterPack() &&
1504                isa<PackExpansionType>(parm->getType())) {
1505       type = SemaRef.SubstType(
1506                         cast<PackExpansionType>(parm->getType())->getPattern(),
1507                                      TemplateArgs, loc, parm->getDeclName());
1508     } else {
1509       type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1510                                TemplateArgs, loc, parm->getDeclName());
1511     }
1512     assert(!type.isNull() && "type substitution failed for param type");
1513     assert(!type->isDependentType() && "param type still dependent");
1514     result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1515 
1516     if (!result.isInvalid()) type = result.get()->getType();
1517   } else {
1518     result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1519 
1520     // Note that this type can be different from the type of 'result',
1521     // e.g. if it's an enum type.
1522     type = arg.getIntegralType();
1523   }
1524   if (result.isInvalid()) return ExprError();
1525 
1526   Expr *resultExpr = result.get();
1527   return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1528       type, resultExpr->getValueKind(), loc, parm, resultExpr);
1529 }
1530 
1531 ExprResult
1532 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1533                                           SubstNonTypeTemplateParmPackExpr *E) {
1534   if (getSema().ArgumentPackSubstitutionIndex == -1) {
1535     // We aren't expanding the parameter pack, so just return ourselves.
1536     return E;
1537   }
1538 
1539   TemplateArgument Arg = E->getArgumentPack();
1540   Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1541   return transformNonTypeTemplateParmRef(E->getParameterPack(),
1542                                          E->getParameterPackLocation(),
1543                                          Arg);
1544 }
1545 
1546 ExprResult
1547 TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
1548                                           SubstNonTypeTemplateParmExpr *E) {
1549   ExprResult SubstReplacement = TransformExpr(E->getReplacement());
1550   if (SubstReplacement.isInvalid())
1551     return true;
1552   QualType SubstType = TransformType(E->getType());
1553   if (SubstType.isNull())
1554     return true;
1555   // The type may have been previously dependent and not now, which means we
1556   // might have to implicit cast the argument to the new type, for example:
1557   // template<auto T, decltype(T) U>
1558   // concept C = sizeof(U) == 4;
1559   // void foo() requires C<2, 'a'> { }
1560   // When normalizing foo(), we first form the normalized constraints of C:
1561   // AtomicExpr(sizeof(U) == 4,
1562   //            U=SubstNonTypeTemplateParmExpr(Param=U,
1563   //                                           Expr=DeclRef(U),
1564   //                                           Type=decltype(T)))
1565   // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
1566   // produce:
1567   // AtomicExpr(sizeof(U) == 4,
1568   //            U=SubstNonTypeTemplateParmExpr(Param=U,
1569   //                                           Expr=ImpCast(
1570   //                                               decltype(2),
1571   //                                               SubstNTTPE(Param=U, Expr='a',
1572   //                                                          Type=char)),
1573   //                                           Type=decltype(2)))
1574   // The call to CheckTemplateArgument here produces the ImpCast.
1575   TemplateArgument Converted;
1576   if (SemaRef.CheckTemplateArgument(E->getParameter(), SubstType,
1577                                     SubstReplacement.get(),
1578                                     Converted).isInvalid())
1579     return true;
1580   return transformNonTypeTemplateParmRef(E->getParameter(),
1581                                          E->getExprLoc(), Converted);
1582 }
1583 
1584 ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1585                                                        SourceLocation Loc) {
1586   DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1587   return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1588 }
1589 
1590 ExprResult
1591 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1592   if (getSema().ArgumentPackSubstitutionIndex != -1) {
1593     // We can expand this parameter pack now.
1594     VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1595     VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1596     if (!VD)
1597       return ExprError();
1598     return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1599   }
1600 
1601   QualType T = TransformType(E->getType());
1602   if (T.isNull())
1603     return ExprError();
1604 
1605   // Transform each of the parameter expansions into the corresponding
1606   // parameters in the instantiation of the function decl.
1607   SmallVector<VarDecl *, 8> Vars;
1608   Vars.reserve(E->getNumExpansions());
1609   for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1610        I != End; ++I) {
1611     VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1612     if (!D)
1613       return ExprError();
1614     Vars.push_back(D);
1615   }
1616 
1617   auto *PackExpr =
1618       FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1619                                    E->getParameterPackLocation(), Vars);
1620   getSema().MarkFunctionParmPackReferenced(PackExpr);
1621   return PackExpr;
1622 }
1623 
1624 ExprResult
1625 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1626                                                        VarDecl *PD) {
1627   typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1628   llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1629     = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1630   assert(Found && "no instantiation for parameter pack");
1631 
1632   Decl *TransformedDecl;
1633   if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1634     // If this is a reference to a function parameter pack which we can
1635     // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1636     if (getSema().ArgumentPackSubstitutionIndex == -1) {
1637       QualType T = TransformType(E->getType());
1638       if (T.isNull())
1639         return ExprError();
1640       auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1641                                                     E->getExprLoc(), *Pack);
1642       getSema().MarkFunctionParmPackReferenced(PackExpr);
1643       return PackExpr;
1644     }
1645 
1646     TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1647   } else {
1648     TransformedDecl = Found->get<Decl*>();
1649   }
1650 
1651   // We have either an unexpanded pack or a specific expansion.
1652   return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1653 }
1654 
1655 ExprResult
1656 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1657   NamedDecl *D = E->getDecl();
1658 
1659   // Handle references to non-type template parameters and non-type template
1660   // parameter packs.
1661   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1662     if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1663       return TransformTemplateParmRefExpr(E, NTTP);
1664 
1665     // We have a non-type template parameter that isn't fully substituted;
1666     // FindInstantiatedDecl will find it in the local instantiation scope.
1667   }
1668 
1669   // Handle references to function parameter packs.
1670   if (VarDecl *PD = dyn_cast<VarDecl>(D))
1671     if (PD->isParameterPack())
1672       return TransformFunctionParmPackRefExpr(E, PD);
1673 
1674   return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1675 }
1676 
1677 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1678     CXXDefaultArgExpr *E) {
1679   assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1680              getDescribedFunctionTemplate() &&
1681          "Default arg expressions are never formed in dependent cases.");
1682   return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1683                            cast<FunctionDecl>(E->getParam()->getDeclContext()),
1684                                         E->getParam());
1685 }
1686 
1687 template<typename Fn>
1688 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1689                                  FunctionProtoTypeLoc TL,
1690                                  CXXRecordDecl *ThisContext,
1691                                  Qualifiers ThisTypeQuals,
1692                                  Fn TransformExceptionSpec) {
1693   // We need a local instantiation scope for this function prototype.
1694   LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1695   return inherited::TransformFunctionProtoType(
1696       TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1697 }
1698 
1699 ParmVarDecl *
1700 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1701                                                  int indexAdjustment,
1702                                                Optional<unsigned> NumExpansions,
1703                                                  bool ExpectParameterPack) {
1704   auto NewParm =
1705       SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1706                                NumExpansions, ExpectParameterPack);
1707   if (NewParm && SemaRef.getLangOpts().OpenCL)
1708     SemaRef.deduceOpenCLAddressSpace(NewParm);
1709   return NewParm;
1710 }
1711 
1712 QualType
1713 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1714                                                 TemplateTypeParmTypeLoc TL) {
1715   const TemplateTypeParmType *T = TL.getTypePtr();
1716   if (T->getDepth() < TemplateArgs.getNumLevels()) {
1717     // Replace the template type parameter with its corresponding
1718     // template argument.
1719 
1720     // If the corresponding template argument is NULL or doesn't exist, it's
1721     // because we are performing instantiation from explicitly-specified
1722     // template arguments in a function template class, but there were some
1723     // arguments left unspecified.
1724     if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1725       TemplateTypeParmTypeLoc NewTL
1726         = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1727       NewTL.setNameLoc(TL.getNameLoc());
1728       return TL.getType();
1729     }
1730 
1731     TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1732 
1733     if (T->isParameterPack()) {
1734       assert(Arg.getKind() == TemplateArgument::Pack &&
1735              "Missing argument pack");
1736 
1737       if (getSema().ArgumentPackSubstitutionIndex == -1) {
1738         // We have the template argument pack, but we're not expanding the
1739         // enclosing pack expansion yet. Just save the template argument
1740         // pack for later substitution.
1741         QualType Result
1742           = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1743         SubstTemplateTypeParmPackTypeLoc NewTL
1744           = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1745         NewTL.setNameLoc(TL.getNameLoc());
1746         return Result;
1747       }
1748 
1749       Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1750     }
1751 
1752     assert(Arg.getKind() == TemplateArgument::Type &&
1753            "Template argument kind mismatch");
1754 
1755     QualType Replacement = Arg.getAsType();
1756 
1757     // TODO: only do this uniquing once, at the start of instantiation.
1758     QualType Result
1759       = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1760     SubstTemplateTypeParmTypeLoc NewTL
1761       = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1762     NewTL.setNameLoc(TL.getNameLoc());
1763     return Result;
1764   }
1765 
1766   // The template type parameter comes from an inner template (e.g.,
1767   // the template parameter list of a member template inside the
1768   // template we are instantiating). Create a new template type
1769   // parameter with the template "level" reduced by one.
1770   TemplateTypeParmDecl *NewTTPDecl = nullptr;
1771   if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1772     NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1773                                   TransformDecl(TL.getNameLoc(), OldTTPDecl));
1774 
1775   QualType Result = getSema().Context.getTemplateTypeParmType(
1776       T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1777       T->isParameterPack(), NewTTPDecl);
1778   TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1779   NewTL.setNameLoc(TL.getNameLoc());
1780   return Result;
1781 }
1782 
1783 QualType
1784 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1785                                                             TypeLocBuilder &TLB,
1786                                          SubstTemplateTypeParmPackTypeLoc TL) {
1787   if (getSema().ArgumentPackSubstitutionIndex == -1) {
1788     // We aren't expanding the parameter pack, so just return ourselves.
1789     SubstTemplateTypeParmPackTypeLoc NewTL
1790       = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1791     NewTL.setNameLoc(TL.getNameLoc());
1792     return TL.getType();
1793   }
1794 
1795   TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1796   Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1797   QualType Result = Arg.getAsType();
1798 
1799   Result = getSema().Context.getSubstTemplateTypeParmType(
1800                                       TL.getTypePtr()->getReplacedParameter(),
1801                                                           Result);
1802   SubstTemplateTypeParmTypeLoc NewTL
1803     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1804   NewTL.setNameLoc(TL.getNameLoc());
1805   return Result;
1806 }
1807 
1808 template<typename EntityPrinter>
1809 static concepts::Requirement::SubstitutionDiagnostic *
1810 createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
1811   SmallString<128> Message;
1812   SourceLocation ErrorLoc;
1813   if (Info.hasSFINAEDiagnostic()) {
1814     PartialDiagnosticAt PDA(SourceLocation(),
1815                             PartialDiagnostic::NullDiagnostic{});
1816     Info.takeSFINAEDiagnostic(PDA);
1817     PDA.second.EmitToString(S.getDiagnostics(), Message);
1818     ErrorLoc = PDA.first;
1819   } else {
1820     ErrorLoc = Info.getLocation();
1821   }
1822   char *MessageBuf = new (S.Context) char[Message.size()];
1823   std::copy(Message.begin(), Message.end(), MessageBuf);
1824   SmallString<128> Entity;
1825   llvm::raw_svector_ostream OS(Entity);
1826   Printer(OS);
1827   char *EntityBuf = new (S.Context) char[Entity.size()];
1828   std::copy(Entity.begin(), Entity.end(), EntityBuf);
1829   return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
1830       StringRef(EntityBuf, Entity.size()), ErrorLoc,
1831       StringRef(MessageBuf, Message.size())};
1832 }
1833 
1834 concepts::TypeRequirement *
1835 TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
1836   if (!Req->isDependent() && !AlwaysRebuild())
1837     return Req;
1838   if (Req->isSubstitutionFailure()) {
1839     if (AlwaysRebuild())
1840       return RebuildTypeRequirement(
1841               Req->getSubstitutionDiagnostic());
1842     return Req;
1843   }
1844 
1845   Sema::SFINAETrap Trap(SemaRef);
1846   TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
1847   Sema::InstantiatingTemplate TypeInst(SemaRef,
1848       Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
1849       Req->getType()->getTypeLoc().getSourceRange());
1850   if (TypeInst.isInvalid())
1851     return nullptr;
1852   TypeSourceInfo *TransType = TransformType(Req->getType());
1853   if (!TransType || Trap.hasErrorOccurred())
1854     return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
1855         [&] (llvm::raw_ostream& OS) {
1856             Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
1857         }));
1858   return RebuildTypeRequirement(TransType);
1859 }
1860 
1861 concepts::ExprRequirement *
1862 TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
1863   if (!Req->isDependent() && !AlwaysRebuild())
1864     return Req;
1865 
1866   Sema::SFINAETrap Trap(SemaRef);
1867   TemplateDeductionInfo Info(Req->getExpr()->getBeginLoc());
1868 
1869   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
1870       TransExpr;
1871   if (Req->isExprSubstitutionFailure())
1872     TransExpr = Req->getExprSubstitutionDiagnostic();
1873   else {
1874     Sema::InstantiatingTemplate ExprInst(SemaRef, Req->getExpr()->getBeginLoc(),
1875                                          Req, Info,
1876                                          Req->getExpr()->getSourceRange());
1877     if (ExprInst.isInvalid())
1878       return nullptr;
1879     ExprResult TransExprRes = TransformExpr(Req->getExpr());
1880     if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
1881       TransExpr = createSubstDiag(SemaRef, Info,
1882           [&] (llvm::raw_ostream& OS) {
1883               Req->getExpr()->printPretty(OS, nullptr,
1884                                           SemaRef.getPrintingPolicy());
1885           });
1886     else
1887       TransExpr = TransExprRes.get();
1888   }
1889 
1890   llvm::Optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
1891   const auto &RetReq = Req->getReturnTypeRequirement();
1892   if (RetReq.isEmpty())
1893     TransRetReq.emplace();
1894   else if (RetReq.isSubstitutionFailure())
1895     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
1896   else if (RetReq.isTypeConstraint()) {
1897     TemplateParameterList *OrigTPL =
1898         RetReq.getTypeConstraintTemplateParameterList();
1899     Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
1900                                         Req, Info, OrigTPL->getSourceRange());
1901     if (TPLInst.isInvalid())
1902       return nullptr;
1903     TemplateParameterList *TPL =
1904         TransformTemplateParameterList(OrigTPL);
1905     if (!TPL)
1906       TransRetReq.emplace(createSubstDiag(SemaRef, Info,
1907           [&] (llvm::raw_ostream& OS) {
1908               RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
1909                   ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
1910           }));
1911     else {
1912       TPLInst.Clear();
1913       TransRetReq.emplace(TPL);
1914     }
1915   }
1916   assert(TransRetReq.hasValue() &&
1917          "All code paths leading here must set TransRetReq");
1918   if (Expr *E = TransExpr.dyn_cast<Expr *>())
1919     return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
1920                                   std::move(*TransRetReq));
1921   return RebuildExprRequirement(
1922       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
1923       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
1924 }
1925 
1926 concepts::NestedRequirement *
1927 TemplateInstantiator::TransformNestedRequirement(
1928     concepts::NestedRequirement *Req) {
1929   if (!Req->isDependent() && !AlwaysRebuild())
1930     return Req;
1931   if (Req->isSubstitutionFailure()) {
1932     if (AlwaysRebuild())
1933       return RebuildNestedRequirement(
1934           Req->getSubstitutionDiagnostic());
1935     return Req;
1936   }
1937   Sema::InstantiatingTemplate ReqInst(SemaRef,
1938       Req->getConstraintExpr()->getBeginLoc(), Req,
1939       Sema::InstantiatingTemplate::ConstraintsCheck{},
1940       Req->getConstraintExpr()->getSourceRange());
1941 
1942   ExprResult TransConstraint;
1943   TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc());
1944   {
1945     EnterExpressionEvaluationContext ContextRAII(
1946         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1947     Sema::SFINAETrap Trap(SemaRef);
1948     Sema::InstantiatingTemplate ConstrInst(SemaRef,
1949         Req->getConstraintExpr()->getBeginLoc(), Req, Info,
1950         Req->getConstraintExpr()->getSourceRange());
1951     if (ConstrInst.isInvalid())
1952       return nullptr;
1953     TransConstraint = TransformExpr(Req->getConstraintExpr());
1954     if (TransConstraint.isInvalid() || Trap.hasErrorOccurred())
1955       return RebuildNestedRequirement(createSubstDiag(SemaRef, Info,
1956           [&] (llvm::raw_ostream& OS) {
1957               Req->getConstraintExpr()->printPretty(OS, nullptr,
1958                                                     SemaRef.getPrintingPolicy());
1959           }));
1960   }
1961   return RebuildNestedRequirement(TransConstraint.get());
1962 }
1963 
1964 
1965 /// Perform substitution on the type T with a given set of template
1966 /// arguments.
1967 ///
1968 /// This routine substitutes the given template arguments into the
1969 /// type T and produces the instantiated type.
1970 ///
1971 /// \param T the type into which the template arguments will be
1972 /// substituted. If this type is not dependent, it will be returned
1973 /// immediately.
1974 ///
1975 /// \param Args the template arguments that will be
1976 /// substituted for the top-level template parameters within T.
1977 ///
1978 /// \param Loc the location in the source code where this substitution
1979 /// is being performed. It will typically be the location of the
1980 /// declarator (if we're instantiating the type of some declaration)
1981 /// or the location of the type in the source code (if, e.g., we're
1982 /// instantiating the type of a cast expression).
1983 ///
1984 /// \param Entity the name of the entity associated with a declaration
1985 /// being instantiated (if any). May be empty to indicate that there
1986 /// is no such entity (if, e.g., this is a type that occurs as part of
1987 /// a cast expression) or that the entity has no name (e.g., an
1988 /// unnamed function parameter).
1989 ///
1990 /// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1991 /// acceptable as the top level type of the result.
1992 ///
1993 /// \returns If the instantiation succeeds, the instantiated
1994 /// type. Otherwise, produces diagnostics and returns a NULL type.
1995 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1996                                 const MultiLevelTemplateArgumentList &Args,
1997                                 SourceLocation Loc,
1998                                 DeclarationName Entity,
1999                                 bool AllowDeducedTST) {
2000   assert(!CodeSynthesisContexts.empty() &&
2001          "Cannot perform an instantiation without some context on the "
2002          "instantiation stack");
2003 
2004   if (!T->getType()->isInstantiationDependentType() &&
2005       !T->getType()->isVariablyModifiedType())
2006     return T;
2007 
2008   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2009   return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2010                          : Instantiator.TransformType(T);
2011 }
2012 
2013 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
2014                                 const MultiLevelTemplateArgumentList &Args,
2015                                 SourceLocation Loc,
2016                                 DeclarationName Entity) {
2017   assert(!CodeSynthesisContexts.empty() &&
2018          "Cannot perform an instantiation without some context on the "
2019          "instantiation stack");
2020 
2021   if (TL.getType().isNull())
2022     return nullptr;
2023 
2024   if (!TL.getType()->isInstantiationDependentType() &&
2025       !TL.getType()->isVariablyModifiedType()) {
2026     // FIXME: Make a copy of the TypeLoc data here, so that we can
2027     // return a new TypeSourceInfo. Inefficient!
2028     TypeLocBuilder TLB;
2029     TLB.pushFullCopy(TL);
2030     return TLB.getTypeSourceInfo(Context, TL.getType());
2031   }
2032 
2033   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2034   TypeLocBuilder TLB;
2035   TLB.reserve(TL.getFullDataSize());
2036   QualType Result = Instantiator.TransformType(TLB, TL);
2037   if (Result.isNull())
2038     return nullptr;
2039 
2040   return TLB.getTypeSourceInfo(Context, Result);
2041 }
2042 
2043 /// Deprecated form of the above.
2044 QualType Sema::SubstType(QualType T,
2045                          const MultiLevelTemplateArgumentList &TemplateArgs,
2046                          SourceLocation Loc, DeclarationName Entity) {
2047   assert(!CodeSynthesisContexts.empty() &&
2048          "Cannot perform an instantiation without some context on the "
2049          "instantiation stack");
2050 
2051   // If T is not a dependent type or a variably-modified type, there
2052   // is nothing to do.
2053   if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2054     return T;
2055 
2056   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2057   return Instantiator.TransformType(T);
2058 }
2059 
2060 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
2061   if (T->getType()->isInstantiationDependentType() ||
2062       T->getType()->isVariablyModifiedType())
2063     return true;
2064 
2065   TypeLoc TL = T->getTypeLoc().IgnoreParens();
2066   if (!TL.getAs<FunctionProtoTypeLoc>())
2067     return false;
2068 
2069   FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
2070   for (ParmVarDecl *P : FP.getParams()) {
2071     // This must be synthesized from a typedef.
2072     if (!P) continue;
2073 
2074     // If there are any parameters, a new TypeSourceInfo that refers to the
2075     // instantiated parameters must be built.
2076     return true;
2077   }
2078 
2079   return false;
2080 }
2081 
2082 /// A form of SubstType intended specifically for instantiating the
2083 /// type of a FunctionDecl.  Its purpose is solely to force the
2084 /// instantiation of default-argument expressions and to avoid
2085 /// instantiating an exception-specification.
2086 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
2087                                 const MultiLevelTemplateArgumentList &Args,
2088                                 SourceLocation Loc,
2089                                 DeclarationName Entity,
2090                                 CXXRecordDecl *ThisContext,
2091                                 Qualifiers ThisTypeQuals) {
2092   assert(!CodeSynthesisContexts.empty() &&
2093          "Cannot perform an instantiation without some context on the "
2094          "instantiation stack");
2095 
2096   if (!NeedsInstantiationAsFunctionType(T))
2097     return T;
2098 
2099   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2100 
2101   TypeLocBuilder TLB;
2102 
2103   TypeLoc TL = T->getTypeLoc();
2104   TLB.reserve(TL.getFullDataSize());
2105 
2106   QualType Result;
2107 
2108   if (FunctionProtoTypeLoc Proto =
2109           TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
2110     // Instantiate the type, other than its exception specification. The
2111     // exception specification is instantiated in InitFunctionInstantiation
2112     // once we've built the FunctionDecl.
2113     // FIXME: Set the exception specification to EST_Uninstantiated here,
2114     // instead of rebuilding the function type again later.
2115     Result = Instantiator.TransformFunctionProtoType(
2116         TLB, Proto, ThisContext, ThisTypeQuals,
2117         [](FunctionProtoType::ExceptionSpecInfo &ESI,
2118            bool &Changed) { return false; });
2119   } else {
2120     Result = Instantiator.TransformType(TLB, TL);
2121   }
2122   if (Result.isNull())
2123     return nullptr;
2124 
2125   return TLB.getTypeSourceInfo(Context, Result);
2126 }
2127 
2128 bool Sema::SubstExceptionSpec(SourceLocation Loc,
2129                               FunctionProtoType::ExceptionSpecInfo &ESI,
2130                               SmallVectorImpl<QualType> &ExceptionStorage,
2131                               const MultiLevelTemplateArgumentList &Args) {
2132   assert(ESI.Type != EST_Uninstantiated);
2133 
2134   bool Changed = false;
2135   TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2136   return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2137                                              Changed);
2138 }
2139 
2140 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
2141                               const MultiLevelTemplateArgumentList &Args) {
2142   FunctionProtoType::ExceptionSpecInfo ESI =
2143       Proto->getExtProtoInfo().ExceptionSpec;
2144 
2145   SmallVector<QualType, 4> ExceptionStorage;
2146   if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2147                          ESI, ExceptionStorage, Args))
2148     // On error, recover by dropping the exception specification.
2149     ESI.Type = EST_None;
2150 
2151   UpdateExceptionSpec(New, ESI);
2152 }
2153 
2154 namespace {
2155 
2156   struct GetContainedInventedTypeParmVisitor :
2157     public TypeVisitor<GetContainedInventedTypeParmVisitor,
2158                        TemplateTypeParmDecl *> {
2159     using TypeVisitor<GetContainedInventedTypeParmVisitor,
2160                       TemplateTypeParmDecl *>::Visit;
2161 
2162     TemplateTypeParmDecl *Visit(QualType T) {
2163       if (T.isNull())
2164         return nullptr;
2165       return Visit(T.getTypePtr());
2166     }
2167     // The deduced type itself.
2168     TemplateTypeParmDecl *VisitTemplateTypeParmType(
2169         const TemplateTypeParmType *T) {
2170       if (!T->getDecl() || !T->getDecl()->isImplicit())
2171         return nullptr;
2172       return T->getDecl();
2173     }
2174 
2175     // Only these types can contain 'auto' types, and subsequently be replaced
2176     // by references to invented parameters.
2177 
2178     TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2179       return Visit(T->getNamedType());
2180     }
2181 
2182     TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2183       return Visit(T->getPointeeType());
2184     }
2185 
2186     TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2187       return Visit(T->getPointeeType());
2188     }
2189 
2190     TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2191       return Visit(T->getPointeeTypeAsWritten());
2192     }
2193 
2194     TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2195       return Visit(T->getPointeeType());
2196     }
2197 
2198     TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2199       return Visit(T->getElementType());
2200     }
2201 
2202     TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2203       const DependentSizedExtVectorType *T) {
2204       return Visit(T->getElementType());
2205     }
2206 
2207     TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2208       return Visit(T->getElementType());
2209     }
2210 
2211     TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2212       return VisitFunctionType(T);
2213     }
2214 
2215     TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2216       return Visit(T->getReturnType());
2217     }
2218 
2219     TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2220       return Visit(T->getInnerType());
2221     }
2222 
2223     TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2224       return Visit(T->getModifiedType());
2225     }
2226 
2227     TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2228       return Visit(T->getUnderlyingType());
2229     }
2230 
2231     TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2232       return Visit(T->getOriginalType());
2233     }
2234 
2235     TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2236       return Visit(T->getPattern());
2237     }
2238   };
2239 
2240 } // namespace
2241 
2242 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
2243                             const MultiLevelTemplateArgumentList &TemplateArgs,
2244                                     int indexAdjustment,
2245                                     Optional<unsigned> NumExpansions,
2246                                     bool ExpectParameterPack) {
2247   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2248   TypeSourceInfo *NewDI = nullptr;
2249 
2250   TypeLoc OldTL = OldDI->getTypeLoc();
2251   if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2252 
2253     // We have a function parameter pack. Substitute into the pattern of the
2254     // expansion.
2255     NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2256                       OldParm->getLocation(), OldParm->getDeclName());
2257     if (!NewDI)
2258       return nullptr;
2259 
2260     if (NewDI->getType()->containsUnexpandedParameterPack()) {
2261       // We still have unexpanded parameter packs, which means that
2262       // our function parameter is still a function parameter pack.
2263       // Therefore, make its type a pack expansion type.
2264       NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
2265                                  NumExpansions);
2266     } else if (ExpectParameterPack) {
2267       // We expected to get a parameter pack but didn't (because the type
2268       // itself is not a pack expansion type), so complain. This can occur when
2269       // the substitution goes through an alias template that "loses" the
2270       // pack expansion.
2271       Diag(OldParm->getLocation(),
2272            diag::err_function_parameter_pack_without_parameter_packs)
2273         << NewDI->getType();
2274       return nullptr;
2275     }
2276   } else {
2277     NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
2278                       OldParm->getDeclName());
2279   }
2280 
2281   if (!NewDI)
2282     return nullptr;
2283 
2284   if (NewDI->getType()->isVoidType()) {
2285     Diag(OldParm->getLocation(), diag::err_param_with_void_type);
2286     return nullptr;
2287   }
2288 
2289   // In abbreviated templates, TemplateTypeParmDecls with possible
2290   // TypeConstraints are created when the parameter list is originally parsed.
2291   // The TypeConstraints can therefore reference other functions parameters in
2292   // the abbreviated function template, which is why we must instantiate them
2293   // here, when the instantiated versions of those referenced parameters are in
2294   // scope.
2295   if (TemplateTypeParmDecl *TTP =
2296           GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
2297     if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
2298       auto *Inst = cast_or_null<TemplateTypeParmDecl>(
2299           FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
2300       // We will first get here when instantiating the abbreviated function
2301       // template's described function, but we might also get here later.
2302       // Make sure we do not instantiate the TypeConstraint more than once.
2303       if (Inst && !Inst->getTypeConstraint()) {
2304         // TODO: Concepts: do not instantiate the constraint (delayed constraint
2305         // substitution)
2306         const ASTTemplateArgumentListInfo *TemplArgInfo
2307           = TC->getTemplateArgsAsWritten();
2308         TemplateArgumentListInfo InstArgs;
2309 
2310         if (TemplArgInfo) {
2311           InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2312           InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2313           if (Subst(TemplArgInfo->getTemplateArgs(),
2314                     TemplArgInfo->NumTemplateArgs, InstArgs, TemplateArgs))
2315             return nullptr;
2316         }
2317         if (AttachTypeConstraint(
2318                 TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2319                 TC->getNamedConcept(), &InstArgs, Inst,
2320                 TTP->isParameterPack()
2321                     ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2322                         ->getEllipsisLoc()
2323                     : SourceLocation()))
2324           return nullptr;
2325       }
2326     }
2327   }
2328 
2329   ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
2330                                         OldParm->getInnerLocStart(),
2331                                         OldParm->getLocation(),
2332                                         OldParm->getIdentifier(),
2333                                         NewDI->getType(), NewDI,
2334                                         OldParm->getStorageClass());
2335   if (!NewParm)
2336     return nullptr;
2337 
2338   // Mark the (new) default argument as uninstantiated (if any).
2339   if (OldParm->hasUninstantiatedDefaultArg()) {
2340     Expr *Arg = OldParm->getUninstantiatedDefaultArg();
2341     NewParm->setUninstantiatedDefaultArg(Arg);
2342   } else if (OldParm->hasUnparsedDefaultArg()) {
2343     NewParm->setUnparsedDefaultArg();
2344     UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
2345   } else if (Expr *Arg = OldParm->getDefaultArg()) {
2346     FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
2347     if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
2348       // Instantiate default arguments for methods of local classes (DR1484)
2349       // and non-defining declarations.
2350       Sema::ContextRAII SavedContext(*this, OwningFunc);
2351       LocalInstantiationScope Local(*this, true);
2352       ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
2353       if (NewArg.isUsable()) {
2354         // It would be nice if we still had this.
2355         SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
2356         SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
2357       }
2358     } else {
2359       // FIXME: if we non-lazily instantiated non-dependent default args for
2360       // non-dependent parameter types we could remove a bunch of duplicate
2361       // conversion warnings for such arguments.
2362       NewParm->setUninstantiatedDefaultArg(Arg);
2363     }
2364   }
2365 
2366   NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
2367 
2368   if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
2369     // Add the new parameter to the instantiated parameter pack.
2370     CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
2371   } else {
2372     // Introduce an Old -> New mapping
2373     CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
2374   }
2375 
2376   // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
2377   // can be anything, is this right ?
2378   NewParm->setDeclContext(CurContext);
2379 
2380   NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
2381                         OldParm->getFunctionScopeIndex() + indexAdjustment);
2382 
2383   InstantiateAttrs(TemplateArgs, OldParm, NewParm);
2384 
2385   return NewParm;
2386 }
2387 
2388 /// Substitute the given template arguments into the given set of
2389 /// parameters, producing the set of parameter types that would be generated
2390 /// from such a substitution.
2391 bool Sema::SubstParmTypes(
2392     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
2393     const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
2394     const MultiLevelTemplateArgumentList &TemplateArgs,
2395     SmallVectorImpl<QualType> &ParamTypes,
2396     SmallVectorImpl<ParmVarDecl *> *OutParams,
2397     ExtParameterInfoBuilder &ParamInfos) {
2398   assert(!CodeSynthesisContexts.empty() &&
2399          "Cannot perform an instantiation without some context on the "
2400          "instantiation stack");
2401 
2402   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2403                                     DeclarationName());
2404   return Instantiator.TransformFunctionTypeParams(
2405       Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
2406 }
2407 
2408 /// Perform substitution on the base class specifiers of the
2409 /// given class template specialization.
2410 ///
2411 /// Produces a diagnostic and returns true on error, returns false and
2412 /// attaches the instantiated base classes to the class template
2413 /// specialization if successful.
2414 bool
2415 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
2416                           CXXRecordDecl *Pattern,
2417                           const MultiLevelTemplateArgumentList &TemplateArgs) {
2418   bool Invalid = false;
2419   SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
2420   for (const auto &Base : Pattern->bases()) {
2421     if (!Base.getType()->isDependentType()) {
2422       if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
2423         if (RD->isInvalidDecl())
2424           Instantiation->setInvalidDecl();
2425       }
2426       InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
2427       continue;
2428     }
2429 
2430     SourceLocation EllipsisLoc;
2431     TypeSourceInfo *BaseTypeLoc;
2432     if (Base.isPackExpansion()) {
2433       // This is a pack expansion. See whether we should expand it now, or
2434       // wait until later.
2435       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2436       collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
2437                                       Unexpanded);
2438       bool ShouldExpand = false;
2439       bool RetainExpansion = false;
2440       Optional<unsigned> NumExpansions;
2441       if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
2442                                           Base.getSourceRange(),
2443                                           Unexpanded,
2444                                           TemplateArgs, ShouldExpand,
2445                                           RetainExpansion,
2446                                           NumExpansions)) {
2447         Invalid = true;
2448         continue;
2449       }
2450 
2451       // If we should expand this pack expansion now, do so.
2452       if (ShouldExpand) {
2453         for (unsigned I = 0; I != *NumExpansions; ++I) {
2454             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2455 
2456           TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2457                                                   TemplateArgs,
2458                                               Base.getSourceRange().getBegin(),
2459                                                   DeclarationName());
2460           if (!BaseTypeLoc) {
2461             Invalid = true;
2462             continue;
2463           }
2464 
2465           if (CXXBaseSpecifier *InstantiatedBase
2466                 = CheckBaseSpecifier(Instantiation,
2467                                      Base.getSourceRange(),
2468                                      Base.isVirtual(),
2469                                      Base.getAccessSpecifierAsWritten(),
2470                                      BaseTypeLoc,
2471                                      SourceLocation()))
2472             InstantiatedBases.push_back(InstantiatedBase);
2473           else
2474             Invalid = true;
2475         }
2476 
2477         continue;
2478       }
2479 
2480       // The resulting base specifier will (still) be a pack expansion.
2481       EllipsisLoc = Base.getEllipsisLoc();
2482       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2483       BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2484                               TemplateArgs,
2485                               Base.getSourceRange().getBegin(),
2486                               DeclarationName());
2487     } else {
2488       BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2489                               TemplateArgs,
2490                               Base.getSourceRange().getBegin(),
2491                               DeclarationName());
2492     }
2493 
2494     if (!BaseTypeLoc) {
2495       Invalid = true;
2496       continue;
2497     }
2498 
2499     if (CXXBaseSpecifier *InstantiatedBase
2500           = CheckBaseSpecifier(Instantiation,
2501                                Base.getSourceRange(),
2502                                Base.isVirtual(),
2503                                Base.getAccessSpecifierAsWritten(),
2504                                BaseTypeLoc,
2505                                EllipsisLoc))
2506       InstantiatedBases.push_back(InstantiatedBase);
2507     else
2508       Invalid = true;
2509   }
2510 
2511   if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
2512     Invalid = true;
2513 
2514   return Invalid;
2515 }
2516 
2517 // Defined via #include from SemaTemplateInstantiateDecl.cpp
2518 namespace clang {
2519   namespace sema {
2520     Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
2521                             const MultiLevelTemplateArgumentList &TemplateArgs);
2522     Attr *instantiateTemplateAttributeForDecl(
2523         const Attr *At, ASTContext &C, Sema &S,
2524         const MultiLevelTemplateArgumentList &TemplateArgs);
2525   }
2526 }
2527 
2528 /// Instantiate the definition of a class from a given pattern.
2529 ///
2530 /// \param PointOfInstantiation The point of instantiation within the
2531 /// source code.
2532 ///
2533 /// \param Instantiation is the declaration whose definition is being
2534 /// instantiated. This will be either a class template specialization
2535 /// or a member class of a class template specialization.
2536 ///
2537 /// \param Pattern is the pattern from which the instantiation
2538 /// occurs. This will be either the declaration of a class template or
2539 /// the declaration of a member class of a class template.
2540 ///
2541 /// \param TemplateArgs The template arguments to be substituted into
2542 /// the pattern.
2543 ///
2544 /// \param TSK the kind of implicit or explicit instantiation to perform.
2545 ///
2546 /// \param Complain whether to complain if the class cannot be instantiated due
2547 /// to the lack of a definition.
2548 ///
2549 /// \returns true if an error occurred, false otherwise.
2550 bool
2551 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2552                        CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
2553                        const MultiLevelTemplateArgumentList &TemplateArgs,
2554                        TemplateSpecializationKind TSK,
2555                        bool Complain) {
2556   CXXRecordDecl *PatternDef
2557     = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
2558   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2559                                 Instantiation->getInstantiatedFromMemberClass(),
2560                                      Pattern, PatternDef, TSK, Complain))
2561     return true;
2562 
2563   llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
2564     std::string Name;
2565     llvm::raw_string_ostream OS(Name);
2566     Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2567                                         /*Qualified=*/true);
2568     return Name;
2569   });
2570 
2571   Pattern = PatternDef;
2572 
2573   // Record the point of instantiation.
2574   if (MemberSpecializationInfo *MSInfo
2575         = Instantiation->getMemberSpecializationInfo()) {
2576     MSInfo->setTemplateSpecializationKind(TSK);
2577     MSInfo->setPointOfInstantiation(PointOfInstantiation);
2578   } else if (ClassTemplateSpecializationDecl *Spec
2579         = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
2580     Spec->setTemplateSpecializationKind(TSK);
2581     Spec->setPointOfInstantiation(PointOfInstantiation);
2582   }
2583 
2584   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2585   if (Inst.isInvalid())
2586     return true;
2587   assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
2588   PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2589                                       "instantiating class definition");
2590 
2591   // Enter the scope of this instantiation. We don't use
2592   // PushDeclContext because we don't have a scope.
2593   ContextRAII SavedContext(*this, Instantiation);
2594   EnterExpressionEvaluationContext EvalContext(
2595       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2596 
2597   // If this is an instantiation of a local class, merge this local
2598   // instantiation scope with the enclosing scope. Otherwise, every
2599   // instantiation of a class has its own local instantiation scope.
2600   bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
2601   LocalInstantiationScope Scope(*this, MergeWithParentScope);
2602 
2603   // Some class state isn't processed immediately but delayed till class
2604   // instantiation completes. We may not be ready to handle any delayed state
2605   // already on the stack as it might correspond to a different class, so save
2606   // it now and put it back later.
2607   SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
2608 
2609   // Pull attributes from the pattern onto the instantiation.
2610   InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2611 
2612   // Start the definition of this instantiation.
2613   Instantiation->startDefinition();
2614 
2615   // The instantiation is visible here, even if it was first declared in an
2616   // unimported module.
2617   Instantiation->setVisibleDespiteOwningModule();
2618 
2619   // FIXME: This loses the as-written tag kind for an explicit instantiation.
2620   Instantiation->setTagKind(Pattern->getTagKind());
2621 
2622   // Do substitution on the base class specifiers.
2623   if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2624     Instantiation->setInvalidDecl();
2625 
2626   TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2627   SmallVector<Decl*, 4> Fields;
2628   // Delay instantiation of late parsed attributes.
2629   LateInstantiatedAttrVec LateAttrs;
2630   Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2631 
2632   bool MightHaveConstexprVirtualFunctions = false;
2633   for (auto *Member : Pattern->decls()) {
2634     // Don't instantiate members not belonging in this semantic context.
2635     // e.g. for:
2636     // @code
2637     //    template <int i> class A {
2638     //      class B *g;
2639     //    };
2640     // @endcode
2641     // 'class B' has the template as lexical context but semantically it is
2642     // introduced in namespace scope.
2643     if (Member->getDeclContext() != Pattern)
2644       continue;
2645 
2646     // BlockDecls can appear in a default-member-initializer. They must be the
2647     // child of a BlockExpr, so we only know how to instantiate them from there.
2648     if (isa<BlockDecl>(Member))
2649       continue;
2650 
2651     if (Member->isInvalidDecl()) {
2652       Instantiation->setInvalidDecl();
2653       continue;
2654     }
2655 
2656     Decl *NewMember = Instantiator.Visit(Member);
2657     if (NewMember) {
2658       if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2659         Fields.push_back(Field);
2660       } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2661         // C++11 [temp.inst]p1: The implicit instantiation of a class template
2662         // specialization causes the implicit instantiation of the definitions
2663         // of unscoped member enumerations.
2664         // Record a point of instantiation for this implicit instantiation.
2665         if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2666             Enum->isCompleteDefinition()) {
2667           MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2668           assert(MSInfo && "no spec info for member enum specialization");
2669           MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2670           MSInfo->setPointOfInstantiation(PointOfInstantiation);
2671         }
2672       } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2673         if (SA->isFailed()) {
2674           // A static_assert failed. Bail out; instantiating this
2675           // class is probably not meaningful.
2676           Instantiation->setInvalidDecl();
2677           break;
2678         }
2679       } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2680         if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
2681             (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
2682           MightHaveConstexprVirtualFunctions = true;
2683       }
2684 
2685       if (NewMember->isInvalidDecl())
2686         Instantiation->setInvalidDecl();
2687     } else {
2688       // FIXME: Eventually, a NULL return will mean that one of the
2689       // instantiations was a semantic disaster, and we'll want to mark the
2690       // declaration invalid.
2691       // For now, we expect to skip some members that we can't yet handle.
2692     }
2693   }
2694 
2695   // Finish checking fields.
2696   ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2697               SourceLocation(), SourceLocation(), ParsedAttributesView());
2698   CheckCompletedCXXClass(nullptr, Instantiation);
2699 
2700   // Default arguments are parsed, if not instantiated. We can go instantiate
2701   // default arg exprs for default constructors if necessary now. Unless we're
2702   // parsing a class, in which case wait until that's finished.
2703   if (ParsingClassDepth == 0)
2704     ActOnFinishCXXNonNestedClass();
2705 
2706   // Instantiate late parsed attributes, and attach them to their decls.
2707   // See Sema::InstantiateAttrs
2708   for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2709        E = LateAttrs.end(); I != E; ++I) {
2710     assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2711     CurrentInstantiationScope = I->Scope;
2712 
2713     // Allow 'this' within late-parsed attributes.
2714     NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2715     CXXRecordDecl *ThisContext =
2716         dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2717     CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
2718                                ND && ND->isCXXInstanceMember());
2719 
2720     Attr *NewAttr =
2721       instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2722     I->NewDecl->addAttr(NewAttr);
2723     LocalInstantiationScope::deleteScopes(I->Scope,
2724                                           Instantiator.getStartingScope());
2725   }
2726   Instantiator.disableLateAttributeInstantiation();
2727   LateAttrs.clear();
2728 
2729   ActOnFinishDelayedMemberInitializers(Instantiation);
2730 
2731   // FIXME: We should do something similar for explicit instantiations so they
2732   // end up in the right module.
2733   if (TSK == TSK_ImplicitInstantiation) {
2734     Instantiation->setLocation(Pattern->getLocation());
2735     Instantiation->setLocStart(Pattern->getInnerLocStart());
2736     Instantiation->setBraceRange(Pattern->getBraceRange());
2737   }
2738 
2739   if (!Instantiation->isInvalidDecl()) {
2740     // Perform any dependent diagnostics from the pattern.
2741     PerformDependentDiagnostics(Pattern, TemplateArgs);
2742 
2743     // Instantiate any out-of-line class template partial
2744     // specializations now.
2745     for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2746               P = Instantiator.delayed_partial_spec_begin(),
2747            PEnd = Instantiator.delayed_partial_spec_end();
2748          P != PEnd; ++P) {
2749       if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2750               P->first, P->second)) {
2751         Instantiation->setInvalidDecl();
2752         break;
2753       }
2754     }
2755 
2756     // Instantiate any out-of-line variable template partial
2757     // specializations now.
2758     for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2759               P = Instantiator.delayed_var_partial_spec_begin(),
2760            PEnd = Instantiator.delayed_var_partial_spec_end();
2761          P != PEnd; ++P) {
2762       if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2763               P->first, P->second)) {
2764         Instantiation->setInvalidDecl();
2765         break;
2766       }
2767     }
2768   }
2769 
2770   // Exit the scope of this instantiation.
2771   SavedContext.pop();
2772 
2773   if (!Instantiation->isInvalidDecl()) {
2774     Consumer.HandleTagDeclDefinition(Instantiation);
2775 
2776     // Always emit the vtable for an explicit instantiation definition
2777     // of a polymorphic class template specialization. Otherwise, eagerly
2778     // instantiate only constexpr virtual functions in preparation for their use
2779     // in constant evaluation.
2780     if (TSK == TSK_ExplicitInstantiationDefinition)
2781       MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2782     else if (MightHaveConstexprVirtualFunctions)
2783       MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2784                                    /*ConstexprOnly*/ true);
2785   }
2786 
2787   return Instantiation->isInvalidDecl();
2788 }
2789 
2790 /// Instantiate the definition of an enum from a given pattern.
2791 ///
2792 /// \param PointOfInstantiation The point of instantiation within the
2793 ///        source code.
2794 /// \param Instantiation is the declaration whose definition is being
2795 ///        instantiated. This will be a member enumeration of a class
2796 ///        temploid specialization, or a local enumeration within a
2797 ///        function temploid specialization.
2798 /// \param Pattern The templated declaration from which the instantiation
2799 ///        occurs.
2800 /// \param TemplateArgs The template arguments to be substituted into
2801 ///        the pattern.
2802 /// \param TSK The kind of implicit or explicit instantiation to perform.
2803 ///
2804 /// \return \c true if an error occurred, \c false otherwise.
2805 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2806                            EnumDecl *Instantiation, EnumDecl *Pattern,
2807                            const MultiLevelTemplateArgumentList &TemplateArgs,
2808                            TemplateSpecializationKind TSK) {
2809   EnumDecl *PatternDef = Pattern->getDefinition();
2810   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
2811                                  Instantiation->getInstantiatedFromMemberEnum(),
2812                                      Pattern, PatternDef, TSK,/*Complain*/true))
2813     return true;
2814   Pattern = PatternDef;
2815 
2816   // Record the point of instantiation.
2817   if (MemberSpecializationInfo *MSInfo
2818         = Instantiation->getMemberSpecializationInfo()) {
2819     MSInfo->setTemplateSpecializationKind(TSK);
2820     MSInfo->setPointOfInstantiation(PointOfInstantiation);
2821   }
2822 
2823   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2824   if (Inst.isInvalid())
2825     return true;
2826   if (Inst.isAlreadyInstantiating())
2827     return false;
2828   PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2829                                       "instantiating enum definition");
2830 
2831   // The instantiation is visible here, even if it was first declared in an
2832   // unimported module.
2833   Instantiation->setVisibleDespiteOwningModule();
2834 
2835   // Enter the scope of this instantiation. We don't use
2836   // PushDeclContext because we don't have a scope.
2837   ContextRAII SavedContext(*this, Instantiation);
2838   EnterExpressionEvaluationContext EvalContext(
2839       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2840 
2841   LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2842 
2843   // Pull attributes from the pattern onto the instantiation.
2844   InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2845 
2846   TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2847   Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2848 
2849   // Exit the scope of this instantiation.
2850   SavedContext.pop();
2851 
2852   return Instantiation->isInvalidDecl();
2853 }
2854 
2855 
2856 /// Instantiate the definition of a field from the given pattern.
2857 ///
2858 /// \param PointOfInstantiation The point of instantiation within the
2859 ///        source code.
2860 /// \param Instantiation is the declaration whose definition is being
2861 ///        instantiated. This will be a class of a class temploid
2862 ///        specialization, or a local enumeration within a function temploid
2863 ///        specialization.
2864 /// \param Pattern The templated declaration from which the instantiation
2865 ///        occurs.
2866 /// \param TemplateArgs The template arguments to be substituted into
2867 ///        the pattern.
2868 ///
2869 /// \return \c true if an error occurred, \c false otherwise.
2870 bool Sema::InstantiateInClassInitializer(
2871     SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2872     FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2873   // If there is no initializer, we don't need to do anything.
2874   if (!Pattern->hasInClassInitializer())
2875     return false;
2876 
2877   assert(Instantiation->getInClassInitStyle() ==
2878              Pattern->getInClassInitStyle() &&
2879          "pattern and instantiation disagree about init style");
2880 
2881   // Error out if we haven't parsed the initializer of the pattern yet because
2882   // we are waiting for the closing brace of the outer class.
2883   Expr *OldInit = Pattern->getInClassInitializer();
2884   if (!OldInit) {
2885     RecordDecl *PatternRD = Pattern->getParent();
2886     RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2887     Diag(PointOfInstantiation,
2888          diag::err_in_class_initializer_not_yet_parsed)
2889         << OutermostClass << Pattern;
2890     Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
2891     Instantiation->setInvalidDecl();
2892     return true;
2893   }
2894 
2895   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2896   if (Inst.isInvalid())
2897     return true;
2898   if (Inst.isAlreadyInstantiating()) {
2899     // Error out if we hit an instantiation cycle for this initializer.
2900     Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2901       << Instantiation;
2902     return true;
2903   }
2904   PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
2905                                       "instantiating default member init");
2906 
2907   // Enter the scope of this instantiation. We don't use PushDeclContext because
2908   // we don't have a scope.
2909   ContextRAII SavedContext(*this, Instantiation->getParent());
2910   EnterExpressionEvaluationContext EvalContext(
2911       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2912 
2913   LocalInstantiationScope Scope(*this, true);
2914 
2915   // Instantiate the initializer.
2916   ActOnStartCXXInClassMemberInitializer();
2917   CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
2918 
2919   ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2920                                         /*CXXDirectInit=*/false);
2921   Expr *Init = NewInit.get();
2922   assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2923   ActOnFinishCXXInClassMemberInitializer(
2924       Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
2925 
2926   if (auto *L = getASTMutationListener())
2927     L->DefaultMemberInitializerInstantiated(Instantiation);
2928 
2929   // Return true if the in-class initializer is still missing.
2930   return !Instantiation->getInClassInitializer();
2931 }
2932 
2933 namespace {
2934   /// A partial specialization whose template arguments have matched
2935   /// a given template-id.
2936   struct PartialSpecMatchResult {
2937     ClassTemplatePartialSpecializationDecl *Partial;
2938     TemplateArgumentList *Args;
2939   };
2940 }
2941 
2942 bool Sema::usesPartialOrExplicitSpecialization(
2943     SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2944   if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2945       TSK_ExplicitSpecialization)
2946     return true;
2947 
2948   SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2949   ClassTemplateSpec->getSpecializedTemplate()
2950                    ->getPartialSpecializations(PartialSpecs);
2951   for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2952     TemplateDeductionInfo Info(Loc);
2953     if (!DeduceTemplateArguments(PartialSpecs[I],
2954                                  ClassTemplateSpec->getTemplateArgs(), Info))
2955       return true;
2956   }
2957 
2958   return false;
2959 }
2960 
2961 /// Get the instantiation pattern to use to instantiate the definition of a
2962 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
2963 /// template or of a partial specialization).
2964 static CXXRecordDecl *
2965 getPatternForClassTemplateSpecialization(
2966     Sema &S, SourceLocation PointOfInstantiation,
2967     ClassTemplateSpecializationDecl *ClassTemplateSpec,
2968     TemplateSpecializationKind TSK, bool Complain) {
2969   Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2970   if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2971     return nullptr;
2972 
2973   llvm::PointerUnion<ClassTemplateDecl *,
2974                      ClassTemplatePartialSpecializationDecl *>
2975       Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2976   if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2977     // Find best matching specialization.
2978     ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2979 
2980     // C++ [temp.class.spec.match]p1:
2981     //   When a class template is used in a context that requires an
2982     //   instantiation of the class, it is necessary to determine
2983     //   whether the instantiation is to be generated using the primary
2984     //   template or one of the partial specializations. This is done by
2985     //   matching the template arguments of the class template
2986     //   specialization with the template argument lists of the partial
2987     //   specializations.
2988     typedef PartialSpecMatchResult MatchResult;
2989     SmallVector<MatchResult, 4> Matched;
2990     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2991     Template->getPartialSpecializations(PartialSpecs);
2992     TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2993     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2994       ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2995       TemplateDeductionInfo Info(FailedCandidates.getLocation());
2996       if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2997               Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2998         // Store the failed-deduction information for use in diagnostics, later.
2999         // TODO: Actually use the failed-deduction info?
3000         FailedCandidates.addCandidate().set(
3001             DeclAccessPair::make(Template, AS_public), Partial,
3002             MakeDeductionFailureInfo(S.Context, Result, Info));
3003         (void)Result;
3004       } else {
3005         Matched.push_back(PartialSpecMatchResult());
3006         Matched.back().Partial = Partial;
3007         Matched.back().Args = Info.take();
3008       }
3009     }
3010 
3011     // If we're dealing with a member template where the template parameters
3012     // have been instantiated, this provides the original template parameters
3013     // from which the member template's parameters were instantiated.
3014 
3015     if (Matched.size() >= 1) {
3016       SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3017       if (Matched.size() == 1) {
3018         //   -- If exactly one matching specialization is found, the
3019         //      instantiation is generated from that specialization.
3020         // We don't need to do anything for this.
3021       } else {
3022         //   -- If more than one matching specialization is found, the
3023         //      partial order rules (14.5.4.2) are used to determine
3024         //      whether one of the specializations is more specialized
3025         //      than the others. If none of the specializations is more
3026         //      specialized than all of the other matching
3027         //      specializations, then the use of the class template is
3028         //      ambiguous and the program is ill-formed.
3029         for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
3030                                                  PEnd = Matched.end();
3031              P != PEnd; ++P) {
3032           if (S.getMoreSpecializedPartialSpecialization(
3033                   P->Partial, Best->Partial, PointOfInstantiation) ==
3034               P->Partial)
3035             Best = P;
3036         }
3037 
3038         // Determine if the best partial specialization is more specialized than
3039         // the others.
3040         bool Ambiguous = false;
3041         for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3042                                                  PEnd = Matched.end();
3043              P != PEnd; ++P) {
3044           if (P != Best && S.getMoreSpecializedPartialSpecialization(
3045                                P->Partial, Best->Partial,
3046                                PointOfInstantiation) != Best->Partial) {
3047             Ambiguous = true;
3048             break;
3049           }
3050         }
3051 
3052         if (Ambiguous) {
3053           // Partial ordering did not produce a clear winner. Complain.
3054           Inst.Clear();
3055           ClassTemplateSpec->setInvalidDecl();
3056           S.Diag(PointOfInstantiation,
3057                  diag::err_partial_spec_ordering_ambiguous)
3058               << ClassTemplateSpec;
3059 
3060           // Print the matching partial specializations.
3061           for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3062                                                    PEnd = Matched.end();
3063                P != PEnd; ++P)
3064             S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3065                 << S.getTemplateArgumentBindingsText(
3066                        P->Partial->getTemplateParameters(), *P->Args);
3067 
3068           return nullptr;
3069         }
3070       }
3071 
3072       ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3073     } else {
3074       //   -- If no matches are found, the instantiation is generated
3075       //      from the primary template.
3076     }
3077   }
3078 
3079   CXXRecordDecl *Pattern = nullptr;
3080   Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3081   if (auto *PartialSpec =
3082           Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3083     // Instantiate using the best class template partial specialization.
3084     while (PartialSpec->getInstantiatedFromMember()) {
3085       // If we've found an explicit specialization of this class template,
3086       // stop here and use that as the pattern.
3087       if (PartialSpec->isMemberSpecialization())
3088         break;
3089 
3090       PartialSpec = PartialSpec->getInstantiatedFromMember();
3091     }
3092     Pattern = PartialSpec;
3093   } else {
3094     ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3095     while (Template->getInstantiatedFromMemberTemplate()) {
3096       // If we've found an explicit specialization of this class template,
3097       // stop here and use that as the pattern.
3098       if (Template->isMemberSpecialization())
3099         break;
3100 
3101       Template = Template->getInstantiatedFromMemberTemplate();
3102     }
3103     Pattern = Template->getTemplatedDecl();
3104   }
3105 
3106   return Pattern;
3107 }
3108 
3109 bool Sema::InstantiateClassTemplateSpecialization(
3110     SourceLocation PointOfInstantiation,
3111     ClassTemplateSpecializationDecl *ClassTemplateSpec,
3112     TemplateSpecializationKind TSK, bool Complain) {
3113   // Perform the actual instantiation on the canonical declaration.
3114   ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3115       ClassTemplateSpec->getCanonicalDecl());
3116   if (ClassTemplateSpec->isInvalidDecl())
3117     return true;
3118 
3119   CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
3120       *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
3121   if (!Pattern)
3122     return true;
3123 
3124   return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
3125                           getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
3126                           Complain);
3127 }
3128 
3129 /// Instantiates the definitions of all of the member
3130 /// of the given class, which is an instantiation of a class template
3131 /// or a member class of a template.
3132 void
3133 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
3134                               CXXRecordDecl *Instantiation,
3135                         const MultiLevelTemplateArgumentList &TemplateArgs,
3136                               TemplateSpecializationKind TSK) {
3137   // FIXME: We need to notify the ASTMutationListener that we did all of these
3138   // things, in case we have an explicit instantiation definition in a PCM, a
3139   // module, or preamble, and the declaration is in an imported AST.
3140   assert(
3141       (TSK == TSK_ExplicitInstantiationDefinition ||
3142        TSK == TSK_ExplicitInstantiationDeclaration ||
3143        (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
3144       "Unexpected template specialization kind!");
3145   for (auto *D : Instantiation->decls()) {
3146     bool SuppressNew = false;
3147     if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3148       if (FunctionDecl *Pattern =
3149               Function->getInstantiatedFromMemberFunction()) {
3150 
3151         if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3152           continue;
3153 
3154         MemberSpecializationInfo *MSInfo =
3155             Function->getMemberSpecializationInfo();
3156         assert(MSInfo && "No member specialization information?");
3157         if (MSInfo->getTemplateSpecializationKind()
3158                                                  == TSK_ExplicitSpecialization)
3159           continue;
3160 
3161         if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3162                                                    Function,
3163                                         MSInfo->getTemplateSpecializationKind(),
3164                                               MSInfo->getPointOfInstantiation(),
3165                                                    SuppressNew) ||
3166             SuppressNew)
3167           continue;
3168 
3169         // C++11 [temp.explicit]p8:
3170         //   An explicit instantiation definition that names a class template
3171         //   specialization explicitly instantiates the class template
3172         //   specialization and is only an explicit instantiation definition
3173         //   of members whose definition is visible at the point of
3174         //   instantiation.
3175         if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
3176           continue;
3177 
3178         Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3179 
3180         if (Function->isDefined()) {
3181           // Let the ASTConsumer know that this function has been explicitly
3182           // instantiated now, and its linkage might have changed.
3183           Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
3184         } else if (TSK == TSK_ExplicitInstantiationDefinition) {
3185           InstantiateFunctionDefinition(PointOfInstantiation, Function);
3186         } else if (TSK == TSK_ImplicitInstantiation) {
3187           PendingLocalImplicitInstantiations.push_back(
3188               std::make_pair(Function, PointOfInstantiation));
3189         }
3190       }
3191     } else if (auto *Var = dyn_cast<VarDecl>(D)) {
3192       if (isa<VarTemplateSpecializationDecl>(Var))
3193         continue;
3194 
3195       if (Var->isStaticDataMember()) {
3196         if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3197           continue;
3198 
3199         MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3200         assert(MSInfo && "No member specialization information?");
3201         if (MSInfo->getTemplateSpecializationKind()
3202                                                  == TSK_ExplicitSpecialization)
3203           continue;
3204 
3205         if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3206                                                    Var,
3207                                         MSInfo->getTemplateSpecializationKind(),
3208                                               MSInfo->getPointOfInstantiation(),
3209                                                    SuppressNew) ||
3210             SuppressNew)
3211           continue;
3212 
3213         if (TSK == TSK_ExplicitInstantiationDefinition) {
3214           // C++0x [temp.explicit]p8:
3215           //   An explicit instantiation definition that names a class template
3216           //   specialization explicitly instantiates the class template
3217           //   specialization and is only an explicit instantiation definition
3218           //   of members whose definition is visible at the point of
3219           //   instantiation.
3220           if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
3221             continue;
3222 
3223           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3224           InstantiateVariableDefinition(PointOfInstantiation, Var);
3225         } else {
3226           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3227         }
3228       }
3229     } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
3230       if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3231         continue;
3232 
3233       // Always skip the injected-class-name, along with any
3234       // redeclarations of nested classes, since both would cause us
3235       // to try to instantiate the members of a class twice.
3236       // Skip closure types; they'll get instantiated when we instantiate
3237       // the corresponding lambda-expression.
3238       if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
3239           Record->isLambda())
3240         continue;
3241 
3242       MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
3243       assert(MSInfo && "No member specialization information?");
3244 
3245       if (MSInfo->getTemplateSpecializationKind()
3246                                                 == TSK_ExplicitSpecialization)
3247         continue;
3248 
3249       if (Context.getTargetInfo().getTriple().isOSWindows() &&
3250           TSK == TSK_ExplicitInstantiationDeclaration) {
3251         // On Windows, explicit instantiation decl of the outer class doesn't
3252         // affect the inner class. Typically extern template declarations are
3253         // used in combination with dll import/export annotations, but those
3254         // are not propagated from the outer class templates to inner classes.
3255         // Therefore, do not instantiate inner classes on this platform, so
3256         // that users don't end up with undefined symbols during linking.
3257         continue;
3258       }
3259 
3260       if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3261                                                  Record,
3262                                         MSInfo->getTemplateSpecializationKind(),
3263                                               MSInfo->getPointOfInstantiation(),
3264                                                  SuppressNew) ||
3265           SuppressNew)
3266         continue;
3267 
3268       CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3269       assert(Pattern && "Missing instantiated-from-template information");
3270 
3271       if (!Record->getDefinition()) {
3272         if (!Pattern->getDefinition()) {
3273           // C++0x [temp.explicit]p8:
3274           //   An explicit instantiation definition that names a class template
3275           //   specialization explicitly instantiates the class template
3276           //   specialization and is only an explicit instantiation definition
3277           //   of members whose definition is visible at the point of
3278           //   instantiation.
3279           if (TSK == TSK_ExplicitInstantiationDeclaration) {
3280             MSInfo->setTemplateSpecializationKind(TSK);
3281             MSInfo->setPointOfInstantiation(PointOfInstantiation);
3282           }
3283 
3284           continue;
3285         }
3286 
3287         InstantiateClass(PointOfInstantiation, Record, Pattern,
3288                          TemplateArgs,
3289                          TSK);
3290       } else {
3291         if (TSK == TSK_ExplicitInstantiationDefinition &&
3292             Record->getTemplateSpecializationKind() ==
3293                 TSK_ExplicitInstantiationDeclaration) {
3294           Record->setTemplateSpecializationKind(TSK);
3295           MarkVTableUsed(PointOfInstantiation, Record, true);
3296         }
3297       }
3298 
3299       Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
3300       if (Pattern)
3301         InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
3302                                 TSK);
3303     } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
3304       MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
3305       assert(MSInfo && "No member specialization information?");
3306 
3307       if (MSInfo->getTemplateSpecializationKind()
3308             == TSK_ExplicitSpecialization)
3309         continue;
3310 
3311       if (CheckSpecializationInstantiationRedecl(
3312             PointOfInstantiation, TSK, Enum,
3313             MSInfo->getTemplateSpecializationKind(),
3314             MSInfo->getPointOfInstantiation(), SuppressNew) ||
3315           SuppressNew)
3316         continue;
3317 
3318       if (Enum->getDefinition())
3319         continue;
3320 
3321       EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
3322       assert(Pattern && "Missing instantiated-from-template information");
3323 
3324       if (TSK == TSK_ExplicitInstantiationDefinition) {
3325         if (!Pattern->getDefinition())
3326           continue;
3327 
3328         InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
3329       } else {
3330         MSInfo->setTemplateSpecializationKind(TSK);
3331         MSInfo->setPointOfInstantiation(PointOfInstantiation);
3332       }
3333     } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3334       // No need to instantiate in-class initializers during explicit
3335       // instantiation.
3336       if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
3337         CXXRecordDecl *ClassPattern =
3338             Instantiation->getTemplateInstantiationPattern();
3339         DeclContext::lookup_result Lookup =
3340             ClassPattern->lookup(Field->getDeclName());
3341         FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
3342         InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
3343                                       TemplateArgs);
3344       }
3345     }
3346   }
3347 }
3348 
3349 /// Instantiate the definitions of all of the members of the
3350 /// given class template specialization, which was named as part of an
3351 /// explicit instantiation.
3352 void
3353 Sema::InstantiateClassTemplateSpecializationMembers(
3354                                            SourceLocation PointOfInstantiation,
3355                             ClassTemplateSpecializationDecl *ClassTemplateSpec,
3356                                                TemplateSpecializationKind TSK) {
3357   // C++0x [temp.explicit]p7:
3358   //   An explicit instantiation that names a class template
3359   //   specialization is an explicit instantion of the same kind
3360   //   (declaration or definition) of each of its members (not
3361   //   including members inherited from base classes) that has not
3362   //   been previously explicitly specialized in the translation unit
3363   //   containing the explicit instantiation, except as described
3364   //   below.
3365   InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
3366                           getTemplateInstantiationArgs(ClassTemplateSpec),
3367                           TSK);
3368 }
3369 
3370 StmtResult
3371 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
3372   if (!S)
3373     return S;
3374 
3375   TemplateInstantiator Instantiator(*this, TemplateArgs,
3376                                     SourceLocation(),
3377                                     DeclarationName());
3378   return Instantiator.TransformStmt(S);
3379 }
3380 
3381 bool Sema::SubstTemplateArguments(
3382     ArrayRef<TemplateArgumentLoc> Args,
3383     const MultiLevelTemplateArgumentList &TemplateArgs,
3384     TemplateArgumentListInfo &Out) {
3385   TemplateInstantiator Instantiator(*this, TemplateArgs,
3386                                     SourceLocation(),
3387                                     DeclarationName());
3388   return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(),
3389                                                  Out);
3390 }
3391 
3392 ExprResult
3393 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
3394   if (!E)
3395     return E;
3396 
3397   TemplateInstantiator Instantiator(*this, TemplateArgs,
3398                                     SourceLocation(),
3399                                     DeclarationName());
3400   return Instantiator.TransformExpr(E);
3401 }
3402 
3403 ExprResult Sema::SubstInitializer(Expr *Init,
3404                           const MultiLevelTemplateArgumentList &TemplateArgs,
3405                           bool CXXDirectInit) {
3406   TemplateInstantiator Instantiator(*this, TemplateArgs,
3407                                     SourceLocation(),
3408                                     DeclarationName());
3409   return Instantiator.TransformInitializer(Init, CXXDirectInit);
3410 }
3411 
3412 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
3413                       const MultiLevelTemplateArgumentList &TemplateArgs,
3414                       SmallVectorImpl<Expr *> &Outputs) {
3415   if (Exprs.empty())
3416     return false;
3417 
3418   TemplateInstantiator Instantiator(*this, TemplateArgs,
3419                                     SourceLocation(),
3420                                     DeclarationName());
3421   return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
3422                                      IsCall, Outputs);
3423 }
3424 
3425 NestedNameSpecifierLoc
3426 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3427                         const MultiLevelTemplateArgumentList &TemplateArgs) {
3428   if (!NNS)
3429     return NestedNameSpecifierLoc();
3430 
3431   TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
3432                                     DeclarationName());
3433   return Instantiator.TransformNestedNameSpecifierLoc(NNS);
3434 }
3435 
3436 /// Do template substitution on declaration name info.
3437 DeclarationNameInfo
3438 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3439                          const MultiLevelTemplateArgumentList &TemplateArgs) {
3440   TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
3441                                     NameInfo.getName());
3442   return Instantiator.TransformDeclarationNameInfo(NameInfo);
3443 }
3444 
3445 TemplateName
3446 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
3447                         TemplateName Name, SourceLocation Loc,
3448                         const MultiLevelTemplateArgumentList &TemplateArgs) {
3449   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3450                                     DeclarationName());
3451   CXXScopeSpec SS;
3452   SS.Adopt(QualifierLoc);
3453   return Instantiator.TransformTemplateName(SS, Name, Loc);
3454 }
3455 
3456 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
3457                  TemplateArgumentListInfo &Result,
3458                  const MultiLevelTemplateArgumentList &TemplateArgs) {
3459   TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
3460                                     DeclarationName());
3461 
3462   return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
3463 }
3464 
3465 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
3466   // When storing ParmVarDecls in the local instantiation scope, we always
3467   // want to use the ParmVarDecl from the canonical function declaration,
3468   // since the map is then valid for any redeclaration or definition of that
3469   // function.
3470   if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
3471     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
3472       unsigned i = PV->getFunctionScopeIndex();
3473       // This parameter might be from a freestanding function type within the
3474       // function and isn't necessarily referring to one of FD's parameters.
3475       if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
3476         return FD->getCanonicalDecl()->getParamDecl(i);
3477     }
3478   }
3479   return D;
3480 }
3481 
3482 
3483 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
3484 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
3485   D = getCanonicalParmVarDecl(D);
3486   for (LocalInstantiationScope *Current = this; Current;
3487        Current = Current->Outer) {
3488 
3489     // Check if we found something within this scope.
3490     const Decl *CheckD = D;
3491     do {
3492       LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
3493       if (Found != Current->LocalDecls.end())
3494         return &Found->second;
3495 
3496       // If this is a tag declaration, it's possible that we need to look for
3497       // a previous declaration.
3498       if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
3499         CheckD = Tag->getPreviousDecl();
3500       else
3501         CheckD = nullptr;
3502     } while (CheckD);
3503 
3504     // If we aren't combined with our outer scope, we're done.
3505     if (!Current->CombineWithOuterScope)
3506       break;
3507   }
3508 
3509   // If we're performing a partial substitution during template argument
3510   // deduction, we may not have values for template parameters yet.
3511   if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
3512       isa<TemplateTemplateParmDecl>(D))
3513     return nullptr;
3514 
3515   // Local types referenced prior to definition may require instantiation.
3516   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
3517     if (RD->isLocalClass())
3518       return nullptr;
3519 
3520   // Enumeration types referenced prior to definition may appear as a result of
3521   // error recovery.
3522   if (isa<EnumDecl>(D))
3523     return nullptr;
3524 
3525   // If we didn't find the decl, then we either have a sema bug, or we have a
3526   // forward reference to a label declaration.  Return null to indicate that
3527   // we have an uninstantiated label.
3528   assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
3529   return nullptr;
3530 }
3531 
3532 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
3533   D = getCanonicalParmVarDecl(D);
3534   llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3535   if (Stored.isNull()) {
3536 #ifndef NDEBUG
3537     // It should not be present in any surrounding scope either.
3538     LocalInstantiationScope *Current = this;
3539     while (Current->CombineWithOuterScope && Current->Outer) {
3540       Current = Current->Outer;
3541       assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3542              "Instantiated local in inner and outer scopes");
3543     }
3544 #endif
3545     Stored = Inst;
3546   } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
3547     Pack->push_back(cast<VarDecl>(Inst));
3548   } else {
3549     assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
3550   }
3551 }
3552 
3553 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
3554                                                        VarDecl *Inst) {
3555   D = getCanonicalParmVarDecl(D);
3556   DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3557   Pack->push_back(Inst);
3558 }
3559 
3560 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
3561 #ifndef NDEBUG
3562   // This should be the first time we've been told about this decl.
3563   for (LocalInstantiationScope *Current = this;
3564        Current && Current->CombineWithOuterScope; Current = Current->Outer)
3565     assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3566            "Creating local pack after instantiation of local");
3567 #endif
3568 
3569   D = getCanonicalParmVarDecl(D);
3570   llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
3571   DeclArgumentPack *Pack = new DeclArgumentPack;
3572   Stored = Pack;
3573   ArgumentPacks.push_back(Pack);
3574 }
3575 
3576 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
3577                                           const TemplateArgument *ExplicitArgs,
3578                                                     unsigned NumExplicitArgs) {
3579   assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3580          "Already have a partially-substituted pack");
3581   assert((!PartiallySubstitutedPack
3582           || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3583          "Wrong number of arguments in partially-substituted pack");
3584   PartiallySubstitutedPack = Pack;
3585   ArgsInPartiallySubstitutedPack = ExplicitArgs;
3586   NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3587 }
3588 
3589 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
3590                                          const TemplateArgument **ExplicitArgs,
3591                                               unsigned *NumExplicitArgs) const {
3592   if (ExplicitArgs)
3593     *ExplicitArgs = nullptr;
3594   if (NumExplicitArgs)
3595     *NumExplicitArgs = 0;
3596 
3597   for (const LocalInstantiationScope *Current = this; Current;
3598        Current = Current->Outer) {
3599     if (Current->PartiallySubstitutedPack) {
3600       if (ExplicitArgs)
3601         *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3602       if (NumExplicitArgs)
3603         *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
3604 
3605       return Current->PartiallySubstitutedPack;
3606     }
3607 
3608     if (!Current->CombineWithOuterScope)
3609       break;
3610   }
3611 
3612   return nullptr;
3613 }
3614