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