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