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