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