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