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