xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaTemplateInstantiate.cpp (revision ffc5ee0f57d56459df93f4107b9835ae78a546b5)
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/ASTConcept.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/DeclBase.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprConcepts.h"
22 #include "clang/AST/PrettyDeclStackTrace.h"
23 #include "clang/AST/RecursiveASTVisitor.h"
24 #include "clang/AST/Type.h"
25 #include "clang/AST/TypeLoc.h"
26 #include "clang/AST/TypeVisitor.h"
27 #include "clang/Basic/LangOptions.h"
28 #include "clang/Basic/Stack.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/EnterExpressionEvaluationContext.h"
32 #include "clang/Sema/Initialization.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaConcept.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "clang/Sema/Template.h"
38 #include "clang/Sema/TemplateDeduction.h"
39 #include "clang/Sema/TemplateInstCallback.h"
40 #include "llvm/ADT/STLForwardCompat.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include "llvm/Support/TimeProfiler.h"
44 #include <optional>
45 
46 using namespace clang;
47 using namespace sema;
48 
49 //===----------------------------------------------------------------------===/
50 // Template Instantiation Support
51 //===----------------------------------------------------------------------===/
52 
53 namespace {
54 namespace TemplateInstArgsHelpers {
55 struct Response {
56   const Decl *NextDecl = nullptr;
57   bool IsDone = false;
58   bool ClearRelativeToPrimary = true;
Done__anondb690eb50111::TemplateInstArgsHelpers::Response59   static Response Done() {
60     Response R;
61     R.IsDone = true;
62     return R;
63   }
ChangeDecl__anondb690eb50111::TemplateInstArgsHelpers::Response64   static Response ChangeDecl(const Decl *ND) {
65     Response R;
66     R.NextDecl = ND;
67     return R;
68   }
ChangeDecl__anondb690eb50111::TemplateInstArgsHelpers::Response69   static Response ChangeDecl(const DeclContext *Ctx) {
70     Response R;
71     R.NextDecl = Decl::castFromDeclContext(Ctx);
72     return R;
73   }
74 
UseNextDecl__anondb690eb50111::TemplateInstArgsHelpers::Response75   static Response UseNextDecl(const Decl *CurDecl) {
76     return ChangeDecl(CurDecl->getDeclContext());
77   }
78 
DontClearRelativeToPrimaryNextDecl__anondb690eb50111::TemplateInstArgsHelpers::Response79   static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
80     Response R = Response::UseNextDecl(CurDecl);
81     R.ClearRelativeToPrimary = false;
82     return R;
83   }
84 };
85 
86 // Retrieve the primary template for a lambda call operator. It's
87 // unfortunate that we only have the mappings of call operators rather
88 // than lambda classes.
89 const FunctionDecl *
getPrimaryTemplateOfGenericLambda(const FunctionDecl * LambdaCallOperator)90 getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
91   if (!isLambdaCallOperator(LambdaCallOperator))
92     return LambdaCallOperator;
93   while (true) {
94     if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
95             LambdaCallOperator->getDescribedTemplate());
96         FTD && FTD->getInstantiatedFromMemberTemplate()) {
97       LambdaCallOperator =
98           FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
99     } else if (LambdaCallOperator->getPrimaryTemplate()) {
100       // Cases where the lambda operator is instantiated in
101       // TemplateDeclInstantiator::VisitCXXMethodDecl.
102       LambdaCallOperator =
103           LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
104     } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator)
105                                 ->getInstantiatedFromMemberFunction())
106       LambdaCallOperator = Prev;
107     else
108       break;
109   }
110   return LambdaCallOperator;
111 }
112 
113 struct EnclosingTypeAliasTemplateDetails {
114   TypeAliasTemplateDecl *Template = nullptr;
115   TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
116   ArrayRef<TemplateArgument> AssociatedTemplateArguments;
117 
operator bool__anondb690eb50111::TemplateInstArgsHelpers::EnclosingTypeAliasTemplateDetails118   explicit operator bool() noexcept { return Template; }
119 };
120 
121 // Find the enclosing type alias template Decl from CodeSynthesisContexts, as
122 // well as its primary template and instantiating template arguments.
123 EnclosingTypeAliasTemplateDetails
getEnclosingTypeAliasTemplateDecl(Sema & SemaRef)124 getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
125   for (auto &CSC : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
126     if (CSC.Kind != Sema::CodeSynthesisContext::SynthesisKind::
127                         TypeAliasTemplateInstantiation)
128       continue;
129     EnclosingTypeAliasTemplateDetails Result;
130     auto *TATD = cast<TypeAliasTemplateDecl>(CSC.Entity),
131          *Next = TATD->getInstantiatedFromMemberTemplate();
132     Result = {
133         /*Template=*/TATD,
134         /*PrimaryTypeAliasDecl=*/TATD,
135         /*AssociatedTemplateArguments=*/CSC.template_arguments(),
136     };
137     while (Next) {
138       Result.PrimaryTypeAliasDecl = Next;
139       Next = Next->getInstantiatedFromMemberTemplate();
140     }
141     return Result;
142   }
143   return {};
144 }
145 
146 // Check if we are currently inside of a lambda expression that is
147 // surrounded by a using alias declaration. e.g.
148 //   template <class> using type = decltype([](auto) { ^ }());
149 // We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
150 // a DeclContext, nor does it have an associated specialization Decl from which
151 // we could collect these template arguments.
isLambdaEnclosedByTypeAliasDecl(const FunctionDecl * LambdaCallOperator,const TypeAliasTemplateDecl * PrimaryTypeAliasDecl)152 bool isLambdaEnclosedByTypeAliasDecl(
153     const FunctionDecl *LambdaCallOperator,
154     const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
155   struct Visitor : RecursiveASTVisitor<Visitor> {
156     Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
157     bool VisitLambdaExpr(const LambdaExpr *LE) {
158       // Return true to bail out of the traversal, implying the Decl contains
159       // the lambda.
160       return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) !=
161              CallOperator;
162     }
163     const FunctionDecl *CallOperator;
164   };
165 
166   QualType Underlying =
167       PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
168 
169   return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
170               .TraverseType(Underlying);
171 }
172 
173 // Add template arguments from a variable template instantiation.
174 Response
HandleVarTemplateSpec(const VarTemplateSpecializationDecl * VarTemplSpec,MultiLevelTemplateArgumentList & Result,bool SkipForSpecialization)175 HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
176                       MultiLevelTemplateArgumentList &Result,
177                       bool SkipForSpecialization) {
178   // For a class-scope explicit specialization, there are no template arguments
179   // at this level, but there may be enclosing template arguments.
180   if (VarTemplSpec->isClassScopeExplicitSpecialization())
181     return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
182 
183   // We're done when we hit an explicit specialization.
184   if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
185       !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
186     return Response::Done();
187 
188   // If this variable template specialization was instantiated from a
189   // specialized member that is a variable template, we're done.
190   assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
191   llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
192       Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
193   if (VarTemplatePartialSpecializationDecl *Partial =
194           Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
195     if (!SkipForSpecialization)
196       Result.addOuterTemplateArguments(
197           Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
198           /*Final=*/false);
199     if (Partial->isMemberSpecialization())
200       return Response::Done();
201   } else {
202     VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
203     if (!SkipForSpecialization)
204       Result.addOuterTemplateArguments(
205           Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
206           /*Final=*/false);
207     if (Tmpl->isMemberSpecialization())
208       return Response::Done();
209   }
210   return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
211 }
212 
213 // If we have a template template parameter with translation unit context,
214 // then we're performing substitution into a default template argument of
215 // this template template parameter before we've constructed the template
216 // that will own this template template parameter. In this case, we
217 // use empty template parameter lists for all of the outer templates
218 // to avoid performing any substitutions.
219 Response
HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl * TTP,MultiLevelTemplateArgumentList & Result)220 HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
221                                       MultiLevelTemplateArgumentList &Result) {
222   for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
223     Result.addOuterTemplateArguments(std::nullopt);
224   return Response::Done();
225 }
226 
HandlePartialClassTemplateSpec(const ClassTemplatePartialSpecializationDecl * PartialClassTemplSpec,MultiLevelTemplateArgumentList & Result,bool SkipForSpecialization)227 Response HandlePartialClassTemplateSpec(
228     const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
229     MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
230   if (!SkipForSpecialization)
231       Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
232   return Response::Done();
233 }
234 
235 // Add template arguments from a class template instantiation.
236 Response
HandleClassTemplateSpec(const ClassTemplateSpecializationDecl * ClassTemplSpec,MultiLevelTemplateArgumentList & Result,bool SkipForSpecialization)237 HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
238                         MultiLevelTemplateArgumentList &Result,
239                         bool SkipForSpecialization) {
240   if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
241     // We're done when we hit an explicit specialization.
242     if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
243         !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
244       return Response::Done();
245 
246     if (!SkipForSpecialization)
247       Result.addOuterTemplateArguments(
248           const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
249           ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
250           /*Final=*/false);
251 
252     // If this class template specialization was instantiated from a
253     // specialized member that is a class template, we're done.
254     assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
255     if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
256       return Response::Done();
257 
258     // If this was instantiated from a partial template specialization, we need
259     // to get the next level of declaration context from the partial
260     // specialization, as the ClassTemplateSpecializationDecl's
261     // DeclContext/LexicalDeclContext will be for the primary template.
262     if (auto *InstFromPartialTempl = ClassTemplSpec->getSpecializedTemplateOrPartial()
263                       .dyn_cast<ClassTemplatePartialSpecializationDecl *>())
264       return Response::ChangeDecl(InstFromPartialTempl->getLexicalDeclContext());
265   }
266   return Response::UseNextDecl(ClassTemplSpec);
267 }
268 
HandleFunction(Sema & SemaRef,const FunctionDecl * Function,MultiLevelTemplateArgumentList & Result,const FunctionDecl * Pattern,bool RelativeToPrimary,bool ForConstraintInstantiation,bool ForDefaultArgumentSubstitution)269 Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
270                         MultiLevelTemplateArgumentList &Result,
271                         const FunctionDecl *Pattern, bool RelativeToPrimary,
272                         bool ForConstraintInstantiation,
273                         bool ForDefaultArgumentSubstitution) {
274   // Add template arguments from a function template specialization.
275   if (!RelativeToPrimary &&
276       Function->getTemplateSpecializationKindForInstantiation() ==
277           TSK_ExplicitSpecialization)
278     return Response::Done();
279 
280   if (!RelativeToPrimary &&
281       Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
282     // This is an implicit instantiation of an explicit specialization. We
283     // don't get any template arguments from this function but might get
284     // some from an enclosing template.
285     return Response::UseNextDecl(Function);
286   } else if (const TemplateArgumentList *TemplateArgs =
287                  Function->getTemplateSpecializationArgs()) {
288     // Add the template arguments for this specialization.
289     Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
290                                      TemplateArgs->asArray(),
291                                      /*Final=*/false);
292 
293     if (RelativeToPrimary &&
294         (Function->getTemplateSpecializationKind() ==
295              TSK_ExplicitSpecialization ||
296          (Function->getFriendObjectKind() &&
297           !Function->getPrimaryTemplate()->getFriendObjectKind())))
298       return Response::UseNextDecl(Function);
299 
300     // If this function was instantiated from a specialized member that is
301     // a function template, we're done.
302     assert(Function->getPrimaryTemplate() && "No function template?");
303     if (!ForDefaultArgumentSubstitution &&
304         Function->getPrimaryTemplate()->isMemberSpecialization())
305       return Response::Done();
306 
307     // If this function is a generic lambda specialization, we are done.
308     if (!ForConstraintInstantiation &&
309         isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
310       return Response::Done();
311 
312   } else if (Function->getDescribedFunctionTemplate()) {
313     assert(
314         (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
315         "Outer template not instantiated?");
316   }
317   // If this is a friend or local declaration and it declares an entity at
318   // namespace scope, take arguments from its lexical parent
319   // instead of its semantic parent, unless of course the pattern we're
320   // instantiating actually comes from the file's context!
321   if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
322       Function->getNonTransparentDeclContext()->isFileContext() &&
323       (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
324     return Response::ChangeDecl(Function->getLexicalDeclContext());
325   }
326 
327   if (ForConstraintInstantiation && Function->getFriendObjectKind())
328     return Response::ChangeDecl(Function->getLexicalDeclContext());
329   return Response::UseNextDecl(Function);
330 }
331 
HandleFunctionTemplateDecl(const FunctionTemplateDecl * FTD,MultiLevelTemplateArgumentList & Result)332 Response HandleFunctionTemplateDecl(const FunctionTemplateDecl *FTD,
333                                     MultiLevelTemplateArgumentList &Result) {
334   if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
335     Result.addOuterTemplateArguments(
336         const_cast<FunctionTemplateDecl *>(FTD),
337         const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(),
338         /*Final=*/false);
339 
340     NestedNameSpecifier *NNS = FTD->getTemplatedDecl()->getQualifier();
341 
342     while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
343       if (NNS->isInstantiationDependent()) {
344         if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) {
345           ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
346           // Prefer template arguments from the injected-class-type if possible.
347           // For example,
348           // ```cpp
349           // template <class... Pack> struct S {
350           //   template <class T> void foo();
351           // };
352           // template <class... Pack> template <class T>
353           //           ^^^^^^^^^^^^^ InjectedTemplateArgs
354           //           They're of kind TemplateArgument::Pack, not of
355           //           TemplateArgument::Type.
356           // void S<Pack...>::foo() {}
357           //        ^^^^^^^
358           //        TSTy->template_arguments() (which are of PackExpansionType)
359           // ```
360           // This meets the contract in
361           // TreeTransform::TryExpandParameterPacks that the template arguments
362           // for unexpanded parameters should be of a Pack kind.
363           if (TSTy->isCurrentInstantiation()) {
364             auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
365             if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
366               Arguments = CTD->getInjectedTemplateArgs();
367             else if (auto *Specialization =
368                          dyn_cast<ClassTemplateSpecializationDecl>(RD))
369               Arguments =
370                   Specialization->getTemplateInstantiationArgs().asArray();
371           }
372           Result.addOuterTemplateArguments(
373               const_cast<FunctionTemplateDecl *>(FTD), Arguments,
374               /*Final=*/false);
375         }
376       }
377 
378       NNS = NNS->getPrefix();
379     }
380   }
381 
382   return Response::ChangeDecl(FTD->getLexicalDeclContext());
383 }
384 
HandleRecordDecl(Sema & SemaRef,const CXXRecordDecl * Rec,MultiLevelTemplateArgumentList & Result,ASTContext & Context,bool ForConstraintInstantiation)385 Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
386                           MultiLevelTemplateArgumentList &Result,
387                           ASTContext &Context,
388                           bool ForConstraintInstantiation) {
389   if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
390     assert(
391         (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
392         "Outer template not instantiated?");
393     if (ClassTemplate->isMemberSpecialization())
394       return Response::Done();
395     if (ForConstraintInstantiation)
396       Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
397                                        ClassTemplate->getInjectedTemplateArgs(),
398                                        /*Final=*/false);
399   }
400 
401   if (const MemberSpecializationInfo *MSInfo =
402           Rec->getMemberSpecializationInfo())
403     if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
404       return Response::Done();
405 
406   bool IsFriend = Rec->getFriendObjectKind() ||
407                   (Rec->getDescribedClassTemplate() &&
408                    Rec->getDescribedClassTemplate()->getFriendObjectKind());
409   if (ForConstraintInstantiation && IsFriend &&
410       Rec->getNonTransparentDeclContext()->isFileContext()) {
411     return Response::ChangeDecl(Rec->getLexicalDeclContext());
412   }
413 
414   // This is to make sure we pick up the VarTemplateSpecializationDecl or the
415   // TypeAliasTemplateDecl that this lambda is defined inside of.
416   if (Rec->isLambda()) {
417     if (const Decl *LCD = Rec->getLambdaContextDecl())
418       return Response::ChangeDecl(LCD);
419     // Retrieve the template arguments for a using alias declaration.
420     // This is necessary for constraint checking, since we always keep
421     // constraints relative to the primary template.
422     if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef);
423         ForConstraintInstantiation && TypeAlias) {
424       if (isLambdaEnclosedByTypeAliasDecl(Rec->getLambdaCallOperator(),
425                                           TypeAlias.PrimaryTypeAliasDecl)) {
426         Result.addOuterTemplateArguments(TypeAlias.Template,
427                                          TypeAlias.AssociatedTemplateArguments,
428                                          /*Final=*/false);
429         // Visit the parent of the current type alias declaration rather than
430         // the lambda thereof.
431         // E.g., in the following example:
432         // struct S {
433         //  template <class> using T = decltype([]<Concept> {} ());
434         // };
435         // void foo() {
436         //   S::T var;
437         // }
438         // The instantiated lambda expression (which we're visiting at 'var')
439         // has a function DeclContext 'foo' rather than the Record DeclContext
440         // S. This seems to be an oversight to me that we may want to set a
441         // Sema Context from the CXXScopeSpec before substituting into T.
442         return Response::ChangeDecl(TypeAlias.Template->getDeclContext());
443       }
444     }
445   }
446 
447   return Response::UseNextDecl(Rec);
448 }
449 
HandleImplicitConceptSpecializationDecl(const ImplicitConceptSpecializationDecl * CSD,MultiLevelTemplateArgumentList & Result)450 Response HandleImplicitConceptSpecializationDecl(
451     const ImplicitConceptSpecializationDecl *CSD,
452     MultiLevelTemplateArgumentList &Result) {
453   Result.addOuterTemplateArguments(
454       const_cast<ImplicitConceptSpecializationDecl *>(CSD),
455       CSD->getTemplateArguments(),
456       /*Final=*/false);
457   return Response::UseNextDecl(CSD);
458 }
459 
HandleGenericDeclContext(const Decl * CurDecl)460 Response HandleGenericDeclContext(const Decl *CurDecl) {
461   return Response::UseNextDecl(CurDecl);
462 }
463 } // namespace TemplateInstArgsHelpers
464 } // namespace
465 
getTemplateInstantiationArgs(const NamedDecl * ND,const DeclContext * DC,bool Final,std::optional<ArrayRef<TemplateArgument>> Innermost,bool RelativeToPrimary,const FunctionDecl * Pattern,bool ForConstraintInstantiation,bool SkipForSpecialization,bool ForDefaultArgumentSubstitution)466 MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs(
467     const NamedDecl *ND, const DeclContext *DC, bool Final,
468     std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
469     const FunctionDecl *Pattern, bool ForConstraintInstantiation,
470     bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
471   assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
472   // Accumulate the set of template argument lists in this structure.
473   MultiLevelTemplateArgumentList Result;
474 
475   using namespace TemplateInstArgsHelpers;
476   const Decl *CurDecl = ND;
477 
478   if (!CurDecl)
479     CurDecl = Decl::castFromDeclContext(DC);
480 
481   if (Innermost) {
482     Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
483                                      Final);
484     // Populate placeholder template arguments for TemplateTemplateParmDecls.
485     // This is essential for the case e.g.
486     //
487     // template <class> concept Concept = false;
488     // template <template <Concept C> class T> void foo(T<int>)
489     //
490     // where parameter C has a depth of 1 but the substituting argument `int`
491     // has a depth of 0.
492     if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
493       HandleDefaultTempArgIntoTempTempParam(TTP, Result);
494     CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
495   }
496 
497   while (!CurDecl->isFileContextDecl()) {
498     Response R;
499     if (const auto *VarTemplSpec =
500             dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
501       R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
502     } else if (const auto *PartialClassTemplSpec =
503                    dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
504       R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
505                                          SkipForSpecialization);
506     } else if (const auto *ClassTemplSpec =
507                    dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
508       R = HandleClassTemplateSpec(ClassTemplSpec, Result,
509                                   SkipForSpecialization);
510     } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
511       R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
512                          ForConstraintInstantiation,
513                          ForDefaultArgumentSubstitution);
514     } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
515       R = HandleRecordDecl(*this, Rec, Result, Context,
516                            ForConstraintInstantiation);
517     } else if (const auto *CSD =
518                    dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
519       R = HandleImplicitConceptSpecializationDecl(CSD, Result);
520     } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
521       R = HandleFunctionTemplateDecl(FTD, Result);
522     } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
523       R = Response::ChangeDecl(CTD->getLexicalDeclContext());
524     } else if (!isa<DeclContext>(CurDecl)) {
525       R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
526       if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
527         R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
528       }
529     } else {
530       R = HandleGenericDeclContext(CurDecl);
531     }
532 
533     if (R.IsDone)
534       return Result;
535     if (R.ClearRelativeToPrimary)
536       RelativeToPrimary = false;
537     assert(R.NextDecl);
538     CurDecl = R.NextDecl;
539   }
540 
541   return Result;
542 }
543 
isInstantiationRecord() const544 bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
545   switch (Kind) {
546   case TemplateInstantiation:
547   case ExceptionSpecInstantiation:
548   case DefaultTemplateArgumentInstantiation:
549   case DefaultFunctionArgumentInstantiation:
550   case ExplicitTemplateArgumentSubstitution:
551   case DeducedTemplateArgumentSubstitution:
552   case PriorTemplateArgumentSubstitution:
553   case ConstraintsCheck:
554   case NestedRequirementConstraintsCheck:
555     return true;
556 
557   case RequirementInstantiation:
558   case RequirementParameterInstantiation:
559   case DefaultTemplateArgumentChecking:
560   case DeclaringSpecialMember:
561   case DeclaringImplicitEqualityComparison:
562   case DefiningSynthesizedFunction:
563   case ExceptionSpecEvaluation:
564   case ConstraintSubstitution:
565   case ParameterMappingSubstitution:
566   case ConstraintNormalization:
567   case RewritingOperatorAsSpaceship:
568   case InitializingStructuredBinding:
569   case MarkingClassDllexported:
570   case BuildingBuiltinDumpStructCall:
571   case LambdaExpressionSubstitution:
572   case BuildingDeductionGuides:
573   case TypeAliasTemplateInstantiation:
574     return false;
575 
576   // This function should never be called when Kind's value is Memoization.
577   case Memoization:
578     break;
579   }
580 
581   llvm_unreachable("Invalid SynthesisKind!");
582 }
583 
InstantiatingTemplate(Sema & SemaRef,CodeSynthesisContext::SynthesisKind Kind,SourceLocation PointOfInstantiation,SourceRange InstantiationRange,Decl * Entity,NamedDecl * Template,ArrayRef<TemplateArgument> TemplateArgs,sema::TemplateDeductionInfo * DeductionInfo)584 Sema::InstantiatingTemplate::InstantiatingTemplate(
585     Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
586     SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
587     Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
588     sema::TemplateDeductionInfo *DeductionInfo)
589     : SemaRef(SemaRef) {
590   // Don't allow further instantiation if a fatal error and an uncompilable
591   // error have occurred. Any diagnostics we might have raised will not be
592   // visible, and we do not need to construct a correct AST.
593   if (SemaRef.Diags.hasFatalErrorOccurred() &&
594       SemaRef.hasUncompilableErrorOccurred()) {
595     Invalid = true;
596     return;
597   }
598   Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
599   if (!Invalid) {
600     CodeSynthesisContext Inst;
601     Inst.Kind = Kind;
602     Inst.PointOfInstantiation = PointOfInstantiation;
603     Inst.Entity = Entity;
604     Inst.Template = Template;
605     Inst.TemplateArgs = TemplateArgs.data();
606     Inst.NumTemplateArgs = TemplateArgs.size();
607     Inst.DeductionInfo = DeductionInfo;
608     Inst.InstantiationRange = InstantiationRange;
609     SemaRef.pushCodeSynthesisContext(Inst);
610 
611     AlreadyInstantiating = !Inst.Entity ? false :
612         !SemaRef.InstantiatingSpecializations
613              .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
614              .second;
615     atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
616   }
617 }
618 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,Decl * Entity,SourceRange InstantiationRange)619 Sema::InstantiatingTemplate::InstantiatingTemplate(
620     Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
621     SourceRange InstantiationRange)
622     : InstantiatingTemplate(SemaRef,
623                             CodeSynthesisContext::TemplateInstantiation,
624                             PointOfInstantiation, InstantiationRange, Entity) {}
625 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,FunctionDecl * Entity,ExceptionSpecification,SourceRange InstantiationRange)626 Sema::InstantiatingTemplate::InstantiatingTemplate(
627     Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
628     ExceptionSpecification, SourceRange InstantiationRange)
629     : InstantiatingTemplate(
630           SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
631           PointOfInstantiation, InstantiationRange, Entity) {}
632 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,TemplateParameter Param,TemplateDecl * Template,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)633 Sema::InstantiatingTemplate::InstantiatingTemplate(
634     Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
635     TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
636     SourceRange InstantiationRange)
637     : InstantiatingTemplate(
638           SemaRef,
639           CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
640           PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
641           Template, TemplateArgs) {}
642 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,FunctionTemplateDecl * FunctionTemplate,ArrayRef<TemplateArgument> TemplateArgs,CodeSynthesisContext::SynthesisKind Kind,sema::TemplateDeductionInfo & DeductionInfo,SourceRange InstantiationRange)643 Sema::InstantiatingTemplate::InstantiatingTemplate(
644     Sema &SemaRef, SourceLocation PointOfInstantiation,
645     FunctionTemplateDecl *FunctionTemplate,
646     ArrayRef<TemplateArgument> TemplateArgs,
647     CodeSynthesisContext::SynthesisKind Kind,
648     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
649     : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
650                             InstantiationRange, FunctionTemplate, nullptr,
651                             TemplateArgs, &DeductionInfo) {
652   assert(Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
653          Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution ||
654          Kind == CodeSynthesisContext::BuildingDeductionGuides);
655 }
656 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,TemplateDecl * Template,ArrayRef<TemplateArgument> TemplateArgs,sema::TemplateDeductionInfo & DeductionInfo,SourceRange InstantiationRange)657 Sema::InstantiatingTemplate::InstantiatingTemplate(
658     Sema &SemaRef, SourceLocation PointOfInstantiation,
659     TemplateDecl *Template,
660     ArrayRef<TemplateArgument> TemplateArgs,
661     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
662     : InstantiatingTemplate(
663           SemaRef,
664           CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
665           PointOfInstantiation, InstantiationRange, Template, nullptr,
666           TemplateArgs, &DeductionInfo) {}
667 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,ClassTemplatePartialSpecializationDecl * PartialSpec,ArrayRef<TemplateArgument> TemplateArgs,sema::TemplateDeductionInfo & DeductionInfo,SourceRange InstantiationRange)668 Sema::InstantiatingTemplate::InstantiatingTemplate(
669     Sema &SemaRef, SourceLocation PointOfInstantiation,
670     ClassTemplatePartialSpecializationDecl *PartialSpec,
671     ArrayRef<TemplateArgument> TemplateArgs,
672     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
673     : InstantiatingTemplate(
674           SemaRef,
675           CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
676           PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
677           TemplateArgs, &DeductionInfo) {}
678 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,VarTemplatePartialSpecializationDecl * PartialSpec,ArrayRef<TemplateArgument> TemplateArgs,sema::TemplateDeductionInfo & DeductionInfo,SourceRange InstantiationRange)679 Sema::InstantiatingTemplate::InstantiatingTemplate(
680     Sema &SemaRef, SourceLocation PointOfInstantiation,
681     VarTemplatePartialSpecializationDecl *PartialSpec,
682     ArrayRef<TemplateArgument> TemplateArgs,
683     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
684     : InstantiatingTemplate(
685           SemaRef,
686           CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
687           PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
688           TemplateArgs, &DeductionInfo) {}
689 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,ParmVarDecl * Param,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)690 Sema::InstantiatingTemplate::InstantiatingTemplate(
691     Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
692     ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
693     : InstantiatingTemplate(
694           SemaRef,
695           CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
696           PointOfInstantiation, InstantiationRange, Param, nullptr,
697           TemplateArgs) {}
698 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,NamedDecl * Template,NonTypeTemplateParmDecl * Param,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)699 Sema::InstantiatingTemplate::InstantiatingTemplate(
700     Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
701     NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
702     SourceRange InstantiationRange)
703     : InstantiatingTemplate(
704           SemaRef,
705           CodeSynthesisContext::PriorTemplateArgumentSubstitution,
706           PointOfInstantiation, InstantiationRange, Param, Template,
707           TemplateArgs) {}
708 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,NamedDecl * Template,TemplateTemplateParmDecl * Param,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)709 Sema::InstantiatingTemplate::InstantiatingTemplate(
710     Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
711     TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
712     SourceRange InstantiationRange)
713     : InstantiatingTemplate(
714           SemaRef,
715           CodeSynthesisContext::PriorTemplateArgumentSubstitution,
716           PointOfInstantiation, InstantiationRange, Param, Template,
717           TemplateArgs) {}
718 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,TypeAliasTemplateDecl * Entity,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)719 Sema::InstantiatingTemplate::InstantiatingTemplate(
720     Sema &SemaRef, SourceLocation PointOfInstantiation,
721     TypeAliasTemplateDecl *Entity, ArrayRef<TemplateArgument> TemplateArgs,
722     SourceRange InstantiationRange)
723     : InstantiatingTemplate(
724           SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
725           PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
726           /*Template=*/nullptr, TemplateArgs) {}
727 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,TemplateDecl * Template,NamedDecl * Param,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)728 Sema::InstantiatingTemplate::InstantiatingTemplate(
729     Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
730     NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
731     SourceRange InstantiationRange)
732     : InstantiatingTemplate(
733           SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
734           PointOfInstantiation, InstantiationRange, Param, Template,
735           TemplateArgs) {}
736 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,concepts::Requirement * Req,sema::TemplateDeductionInfo & DeductionInfo,SourceRange InstantiationRange)737 Sema::InstantiatingTemplate::InstantiatingTemplate(
738     Sema &SemaRef, SourceLocation PointOfInstantiation,
739     concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo,
740     SourceRange InstantiationRange)
741     : InstantiatingTemplate(
742           SemaRef, CodeSynthesisContext::RequirementInstantiation,
743           PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
744           /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
745 }
746 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,concepts::NestedRequirement * Req,ConstraintsCheck,SourceRange InstantiationRange)747 Sema::InstantiatingTemplate::InstantiatingTemplate(
748     Sema &SemaRef, SourceLocation PointOfInstantiation,
749     concepts::NestedRequirement *Req, ConstraintsCheck,
750     SourceRange InstantiationRange)
751     : InstantiatingTemplate(
752           SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
753           PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
754           /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
755 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,const RequiresExpr * RE,sema::TemplateDeductionInfo & DeductionInfo,SourceRange InstantiationRange)756 Sema::InstantiatingTemplate::InstantiatingTemplate(
757     Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
758     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
759     : InstantiatingTemplate(
760           SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
761           PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
762           /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
763 }
764 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,ConstraintsCheck,NamedDecl * Template,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)765 Sema::InstantiatingTemplate::InstantiatingTemplate(
766     Sema &SemaRef, SourceLocation PointOfInstantiation,
767     ConstraintsCheck, NamedDecl *Template,
768     ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
769     : InstantiatingTemplate(
770           SemaRef, CodeSynthesisContext::ConstraintsCheck,
771           PointOfInstantiation, InstantiationRange, Template, nullptr,
772           TemplateArgs) {}
773 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,ConstraintSubstitution,NamedDecl * Template,sema::TemplateDeductionInfo & DeductionInfo,SourceRange InstantiationRange)774 Sema::InstantiatingTemplate::InstantiatingTemplate(
775     Sema &SemaRef, SourceLocation PointOfInstantiation,
776     ConstraintSubstitution, NamedDecl *Template,
777     sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
778     : InstantiatingTemplate(
779           SemaRef, CodeSynthesisContext::ConstraintSubstitution,
780           PointOfInstantiation, InstantiationRange, Template, nullptr,
781           {}, &DeductionInfo) {}
782 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,ConstraintNormalization,NamedDecl * Template,SourceRange InstantiationRange)783 Sema::InstantiatingTemplate::InstantiatingTemplate(
784     Sema &SemaRef, SourceLocation PointOfInstantiation,
785     ConstraintNormalization, NamedDecl *Template,
786     SourceRange InstantiationRange)
787     : InstantiatingTemplate(
788           SemaRef, CodeSynthesisContext::ConstraintNormalization,
789           PointOfInstantiation, InstantiationRange, Template) {}
790 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,ParameterMappingSubstitution,NamedDecl * Template,SourceRange InstantiationRange)791 Sema::InstantiatingTemplate::InstantiatingTemplate(
792     Sema &SemaRef, SourceLocation PointOfInstantiation,
793     ParameterMappingSubstitution, NamedDecl *Template,
794     SourceRange InstantiationRange)
795     : InstantiatingTemplate(
796           SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
797           PointOfInstantiation, InstantiationRange, Template) {}
798 
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,TemplateDecl * Entity,BuildingDeductionGuidesTag,SourceRange InstantiationRange)799 Sema::InstantiatingTemplate::InstantiatingTemplate(
800     Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
801     BuildingDeductionGuidesTag, SourceRange InstantiationRange)
802     : InstantiatingTemplate(
803           SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
804           PointOfInstantiation, InstantiationRange, Entity) {}
805 
806 
pushCodeSynthesisContext(CodeSynthesisContext Ctx)807 void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
808   Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
809   InNonInstantiationSFINAEContext = false;
810 
811   CodeSynthesisContexts.push_back(Ctx);
812 
813   if (!Ctx.isInstantiationRecord())
814     ++NonInstantiationEntries;
815 
816   // Check to see if we're low on stack space. We can't do anything about this
817   // from here, but we can at least warn the user.
818   if (isStackNearlyExhausted())
819     warnStackExhausted(Ctx.PointOfInstantiation);
820 }
821 
popCodeSynthesisContext()822 void Sema::popCodeSynthesisContext() {
823   auto &Active = CodeSynthesisContexts.back();
824   if (!Active.isInstantiationRecord()) {
825     assert(NonInstantiationEntries > 0);
826     --NonInstantiationEntries;
827   }
828 
829   InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
830 
831   // Name lookup no longer looks in this template's defining module.
832   assert(CodeSynthesisContexts.size() >=
833              CodeSynthesisContextLookupModules.size() &&
834          "forgot to remove a lookup module for a template instantiation");
835   if (CodeSynthesisContexts.size() ==
836       CodeSynthesisContextLookupModules.size()) {
837     if (Module *M = CodeSynthesisContextLookupModules.back())
838       LookupModulesCache.erase(M);
839     CodeSynthesisContextLookupModules.pop_back();
840   }
841 
842   // If we've left the code synthesis context for the current context stack,
843   // stop remembering that we've emitted that stack.
844   if (CodeSynthesisContexts.size() ==
845       LastEmittedCodeSynthesisContextDepth)
846     LastEmittedCodeSynthesisContextDepth = 0;
847 
848   CodeSynthesisContexts.pop_back();
849 }
850 
Clear()851 void Sema::InstantiatingTemplate::Clear() {
852   if (!Invalid) {
853     if (!AlreadyInstantiating) {
854       auto &Active = SemaRef.CodeSynthesisContexts.back();
855       if (Active.Entity)
856         SemaRef.InstantiatingSpecializations.erase(
857             {Active.Entity->getCanonicalDecl(), Active.Kind});
858     }
859 
860     atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
861                   SemaRef.CodeSynthesisContexts.back());
862 
863     SemaRef.popCodeSynthesisContext();
864     Invalid = true;
865   }
866 }
867 
convertCallArgsToString(Sema & S,llvm::ArrayRef<const Expr * > Args)868 static std::string convertCallArgsToString(Sema &S,
869                                            llvm::ArrayRef<const Expr *> Args) {
870   std::string Result;
871   llvm::raw_string_ostream OS(Result);
872   llvm::ListSeparator Comma;
873   for (const Expr *Arg : Args) {
874     OS << Comma;
875     Arg->IgnoreParens()->printPretty(OS, nullptr,
876                                      S.Context.getPrintingPolicy());
877   }
878   return Result;
879 }
880 
CheckInstantiationDepth(SourceLocation PointOfInstantiation,SourceRange InstantiationRange)881 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
882                                         SourceLocation PointOfInstantiation,
883                                            SourceRange InstantiationRange) {
884   assert(SemaRef.NonInstantiationEntries <=
885          SemaRef.CodeSynthesisContexts.size());
886   if ((SemaRef.CodeSynthesisContexts.size() -
887           SemaRef.NonInstantiationEntries)
888         <= SemaRef.getLangOpts().InstantiationDepth)
889     return false;
890 
891   SemaRef.Diag(PointOfInstantiation,
892                diag::err_template_recursion_depth_exceeded)
893     << SemaRef.getLangOpts().InstantiationDepth
894     << InstantiationRange;
895   SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
896     << SemaRef.getLangOpts().InstantiationDepth;
897   return true;
898 }
899 
PrintInstantiationStack()900 void Sema::PrintInstantiationStack() {
901   // Determine which template instantiations to skip, if any.
902   unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
903   unsigned Limit = Diags.getTemplateBacktraceLimit();
904   if (Limit && Limit < CodeSynthesisContexts.size()) {
905     SkipStart = Limit / 2 + Limit % 2;
906     SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
907   }
908 
909   // FIXME: In all of these cases, we need to show the template arguments
910   unsigned InstantiationIdx = 0;
911   for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
912          Active = CodeSynthesisContexts.rbegin(),
913          ActiveEnd = CodeSynthesisContexts.rend();
914        Active != ActiveEnd;
915        ++Active, ++InstantiationIdx) {
916     // Skip this instantiation?
917     if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
918       if (InstantiationIdx == SkipStart) {
919         // Note that we're skipping instantiations.
920         Diags.Report(Active->PointOfInstantiation,
921                      diag::note_instantiation_contexts_suppressed)
922           << unsigned(CodeSynthesisContexts.size() - Limit);
923       }
924       continue;
925     }
926 
927     switch (Active->Kind) {
928     case CodeSynthesisContext::TemplateInstantiation: {
929       Decl *D = Active->Entity;
930       if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
931         unsigned DiagID = diag::note_template_member_class_here;
932         if (isa<ClassTemplateSpecializationDecl>(Record))
933           DiagID = diag::note_template_class_instantiation_here;
934         Diags.Report(Active->PointOfInstantiation, DiagID)
935           << Record << Active->InstantiationRange;
936       } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
937         unsigned DiagID;
938         if (Function->getPrimaryTemplate())
939           DiagID = diag::note_function_template_spec_here;
940         else
941           DiagID = diag::note_template_member_function_here;
942         Diags.Report(Active->PointOfInstantiation, DiagID)
943           << Function
944           << Active->InstantiationRange;
945       } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
946         Diags.Report(Active->PointOfInstantiation,
947                      VD->isStaticDataMember()?
948                        diag::note_template_static_data_member_def_here
949                      : diag::note_template_variable_def_here)
950           << VD
951           << Active->InstantiationRange;
952       } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
953         Diags.Report(Active->PointOfInstantiation,
954                      diag::note_template_enum_def_here)
955           << ED
956           << Active->InstantiationRange;
957       } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
958         Diags.Report(Active->PointOfInstantiation,
959                      diag::note_template_nsdmi_here)
960             << FD << Active->InstantiationRange;
961       } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
962         Diags.Report(Active->PointOfInstantiation,
963                      diag::note_template_class_instantiation_here)
964             << CTD << Active->InstantiationRange;
965       }
966       break;
967     }
968 
969     case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
970       TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
971       SmallString<128> TemplateArgsStr;
972       llvm::raw_svector_ostream OS(TemplateArgsStr);
973       Template->printName(OS, getPrintingPolicy());
974       printTemplateArgumentList(OS, Active->template_arguments(),
975                                 getPrintingPolicy());
976       Diags.Report(Active->PointOfInstantiation,
977                    diag::note_default_arg_instantiation_here)
978         << OS.str()
979         << Active->InstantiationRange;
980       break;
981     }
982 
983     case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
984       FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
985       Diags.Report(Active->PointOfInstantiation,
986                    diag::note_explicit_template_arg_substitution_here)
987         << FnTmpl
988         << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
989                                            Active->TemplateArgs,
990                                            Active->NumTemplateArgs)
991         << Active->InstantiationRange;
992       break;
993     }
994 
995     case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
996       if (FunctionTemplateDecl *FnTmpl =
997               dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
998         Diags.Report(Active->PointOfInstantiation,
999                      diag::note_function_template_deduction_instantiation_here)
1000           << FnTmpl
1001           << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
1002                                              Active->TemplateArgs,
1003                                              Active->NumTemplateArgs)
1004           << Active->InstantiationRange;
1005       } else {
1006         bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1007                      isa<VarTemplateSpecializationDecl>(Active->Entity);
1008         bool IsTemplate = false;
1009         TemplateParameterList *Params;
1010         if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1011           IsTemplate = true;
1012           Params = D->getTemplateParameters();
1013         } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1014                        Active->Entity)) {
1015           Params = D->getTemplateParameters();
1016         } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1017                        Active->Entity)) {
1018           Params = D->getTemplateParameters();
1019         } else {
1020           llvm_unreachable("unexpected template kind");
1021         }
1022 
1023         Diags.Report(Active->PointOfInstantiation,
1024                      diag::note_deduced_template_arg_substitution_here)
1025           << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1026           << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
1027                                              Active->NumTemplateArgs)
1028           << Active->InstantiationRange;
1029       }
1030       break;
1031     }
1032 
1033     case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
1034       ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1035       FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1036 
1037       SmallString<128> TemplateArgsStr;
1038       llvm::raw_svector_ostream OS(TemplateArgsStr);
1039       FD->printName(OS, getPrintingPolicy());
1040       printTemplateArgumentList(OS, Active->template_arguments(),
1041                                 getPrintingPolicy());
1042       Diags.Report(Active->PointOfInstantiation,
1043                    diag::note_default_function_arg_instantiation_here)
1044         << OS.str()
1045         << Active->InstantiationRange;
1046       break;
1047     }
1048 
1049     case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
1050       NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1051       std::string Name;
1052       if (!Parm->getName().empty())
1053         Name = std::string(" '") + Parm->getName().str() + "'";
1054 
1055       TemplateParameterList *TemplateParams = nullptr;
1056       if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1057         TemplateParams = Template->getTemplateParameters();
1058       else
1059         TemplateParams =
1060           cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1061                                                       ->getTemplateParameters();
1062       Diags.Report(Active->PointOfInstantiation,
1063                    diag::note_prior_template_arg_substitution)
1064         << isa<TemplateTemplateParmDecl>(Parm)
1065         << Name
1066         << getTemplateArgumentBindingsText(TemplateParams,
1067                                            Active->TemplateArgs,
1068                                            Active->NumTemplateArgs)
1069         << Active->InstantiationRange;
1070       break;
1071     }
1072 
1073     case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
1074       TemplateParameterList *TemplateParams = nullptr;
1075       if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1076         TemplateParams = Template->getTemplateParameters();
1077       else
1078         TemplateParams =
1079           cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1080                                                       ->getTemplateParameters();
1081 
1082       Diags.Report(Active->PointOfInstantiation,
1083                    diag::note_template_default_arg_checking)
1084         << getTemplateArgumentBindingsText(TemplateParams,
1085                                            Active->TemplateArgs,
1086                                            Active->NumTemplateArgs)
1087         << Active->InstantiationRange;
1088       break;
1089     }
1090 
1091     case CodeSynthesisContext::ExceptionSpecEvaluation:
1092       Diags.Report(Active->PointOfInstantiation,
1093                    diag::note_evaluating_exception_spec_here)
1094           << cast<FunctionDecl>(Active->Entity);
1095       break;
1096 
1097     case CodeSynthesisContext::ExceptionSpecInstantiation:
1098       Diags.Report(Active->PointOfInstantiation,
1099                    diag::note_template_exception_spec_instantiation_here)
1100         << cast<FunctionDecl>(Active->Entity)
1101         << Active->InstantiationRange;
1102       break;
1103 
1104     case CodeSynthesisContext::RequirementInstantiation:
1105       Diags.Report(Active->PointOfInstantiation,
1106                    diag::note_template_requirement_instantiation_here)
1107         << Active->InstantiationRange;
1108       break;
1109     case CodeSynthesisContext::RequirementParameterInstantiation:
1110       Diags.Report(Active->PointOfInstantiation,
1111                    diag::note_template_requirement_params_instantiation_here)
1112           << Active->InstantiationRange;
1113       break;
1114 
1115     case CodeSynthesisContext::NestedRequirementConstraintsCheck:
1116       Diags.Report(Active->PointOfInstantiation,
1117                    diag::note_nested_requirement_here)
1118         << Active->InstantiationRange;
1119       break;
1120 
1121     case CodeSynthesisContext::DeclaringSpecialMember:
1122       Diags.Report(Active->PointOfInstantiation,
1123                    diag::note_in_declaration_of_implicit_special_member)
1124           << cast<CXXRecordDecl>(Active->Entity)
1125           << llvm::to_underlying(Active->SpecialMember);
1126       break;
1127 
1128     case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
1129       Diags.Report(Active->Entity->getLocation(),
1130                    diag::note_in_declaration_of_implicit_equality_comparison);
1131       break;
1132 
1133     case CodeSynthesisContext::DefiningSynthesizedFunction: {
1134       // FIXME: For synthesized functions that are not defaulted,
1135       // produce a note.
1136       auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1137       DefaultedFunctionKind DFK =
1138           FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
1139       if (DFK.isSpecialMember()) {
1140         auto *MD = cast<CXXMethodDecl>(FD);
1141         Diags.Report(Active->PointOfInstantiation,
1142                      diag::note_member_synthesized_at)
1143             << MD->isExplicitlyDefaulted()
1144             << llvm::to_underlying(DFK.asSpecialMember())
1145             << Context.getTagDeclType(MD->getParent());
1146       } else if (DFK.isComparison()) {
1147         QualType RecordType = FD->getParamDecl(0)
1148                                   ->getType()
1149                                   .getNonReferenceType()
1150                                   .getUnqualifiedType();
1151         Diags.Report(Active->PointOfInstantiation,
1152                      diag::note_comparison_synthesized_at)
1153             << (int)DFK.asComparison() << RecordType;
1154       }
1155       break;
1156     }
1157 
1158     case CodeSynthesisContext::RewritingOperatorAsSpaceship:
1159       Diags.Report(Active->Entity->getLocation(),
1160                    diag::note_rewriting_operator_as_spaceship);
1161       break;
1162 
1163     case CodeSynthesisContext::InitializingStructuredBinding:
1164       Diags.Report(Active->PointOfInstantiation,
1165                    diag::note_in_binding_decl_init)
1166           << cast<BindingDecl>(Active->Entity);
1167       break;
1168 
1169     case CodeSynthesisContext::MarkingClassDllexported:
1170       Diags.Report(Active->PointOfInstantiation,
1171                    diag::note_due_to_dllexported_class)
1172           << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1173       break;
1174 
1175     case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
1176       Diags.Report(Active->PointOfInstantiation,
1177                    diag::note_building_builtin_dump_struct_call)
1178           << convertCallArgsToString(
1179                  *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1180       break;
1181 
1182     case CodeSynthesisContext::Memoization:
1183       break;
1184 
1185     case CodeSynthesisContext::LambdaExpressionSubstitution:
1186       Diags.Report(Active->PointOfInstantiation,
1187                    diag::note_lambda_substitution_here);
1188       break;
1189     case CodeSynthesisContext::ConstraintsCheck: {
1190       unsigned DiagID = 0;
1191       if (!Active->Entity) {
1192         Diags.Report(Active->PointOfInstantiation,
1193                      diag::note_nested_requirement_here)
1194           << Active->InstantiationRange;
1195         break;
1196       }
1197       if (isa<ConceptDecl>(Active->Entity))
1198         DiagID = diag::note_concept_specialization_here;
1199       else if (isa<TemplateDecl>(Active->Entity))
1200         DiagID = diag::note_checking_constraints_for_template_id_here;
1201       else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1202         DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1203       else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1204         DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1205       else {
1206         assert(isa<FunctionDecl>(Active->Entity));
1207         DiagID = diag::note_checking_constraints_for_function_here;
1208       }
1209       SmallString<128> TemplateArgsStr;
1210       llvm::raw_svector_ostream OS(TemplateArgsStr);
1211       cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1212       if (!isa<FunctionDecl>(Active->Entity)) {
1213         printTemplateArgumentList(OS, Active->template_arguments(),
1214                                   getPrintingPolicy());
1215       }
1216       Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1217         << Active->InstantiationRange;
1218       break;
1219     }
1220     case CodeSynthesisContext::ConstraintSubstitution:
1221       Diags.Report(Active->PointOfInstantiation,
1222                    diag::note_constraint_substitution_here)
1223           << Active->InstantiationRange;
1224       break;
1225     case CodeSynthesisContext::ConstraintNormalization:
1226       Diags.Report(Active->PointOfInstantiation,
1227                    diag::note_constraint_normalization_here)
1228           << cast<NamedDecl>(Active->Entity)->getName()
1229           << Active->InstantiationRange;
1230       break;
1231     case CodeSynthesisContext::ParameterMappingSubstitution:
1232       Diags.Report(Active->PointOfInstantiation,
1233                    diag::note_parameter_mapping_substitution_here)
1234           << Active->InstantiationRange;
1235       break;
1236     case CodeSynthesisContext::BuildingDeductionGuides:
1237       Diags.Report(Active->PointOfInstantiation,
1238                    diag::note_building_deduction_guide_here);
1239       break;
1240     case CodeSynthesisContext::TypeAliasTemplateInstantiation:
1241       Diags.Report(Active->PointOfInstantiation,
1242                    diag::note_template_type_alias_instantiation_here)
1243           << cast<TypeAliasTemplateDecl>(Active->Entity)
1244           << Active->InstantiationRange;
1245       break;
1246     }
1247   }
1248 }
1249 
isSFINAEContext() const1250 std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1251   if (InNonInstantiationSFINAEContext)
1252     return std::optional<TemplateDeductionInfo *>(nullptr);
1253 
1254   for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
1255          Active = CodeSynthesisContexts.rbegin(),
1256          ActiveEnd = CodeSynthesisContexts.rend();
1257        Active != ActiveEnd;
1258        ++Active)
1259   {
1260     switch (Active->Kind) {
1261     case CodeSynthesisContext::TypeAliasTemplateInstantiation:
1262       // An instantiation of an alias template may or may not be a SFINAE
1263       // context, depending on what else is on the stack.
1264       if (isa<TypeAliasTemplateDecl>(Active->Entity))
1265         break;
1266       [[fallthrough]];
1267     case CodeSynthesisContext::TemplateInstantiation:
1268     case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
1269     case CodeSynthesisContext::ExceptionSpecInstantiation:
1270     case CodeSynthesisContext::ConstraintsCheck:
1271     case CodeSynthesisContext::ParameterMappingSubstitution:
1272     case CodeSynthesisContext::ConstraintNormalization:
1273     case CodeSynthesisContext::NestedRequirementConstraintsCheck:
1274       // This is a template instantiation, so there is no SFINAE.
1275       return std::nullopt;
1276     case CodeSynthesisContext::LambdaExpressionSubstitution:
1277       // [temp.deduct]p9
1278       // A lambda-expression appearing in a function type or a template
1279       // parameter is not considered part of the immediate context for the
1280       // purposes of template argument deduction.
1281       // CWG2672: A lambda-expression body is never in the immediate context.
1282       return std::nullopt;
1283 
1284     case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
1285     case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
1286     case CodeSynthesisContext::DefaultTemplateArgumentChecking:
1287     case CodeSynthesisContext::RewritingOperatorAsSpaceship:
1288       // A default template argument instantiation and substitution into
1289       // template parameters with arguments for prior parameters may or may
1290       // not be a SFINAE context; look further up the stack.
1291       break;
1292 
1293     case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
1294     case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
1295       // We're either substituting explicitly-specified template arguments,
1296       // deduced template arguments. SFINAE applies unless we are in a lambda
1297       // body, see [temp.deduct]p9.
1298     case CodeSynthesisContext::ConstraintSubstitution:
1299     case CodeSynthesisContext::RequirementInstantiation:
1300     case CodeSynthesisContext::RequirementParameterInstantiation:
1301       // SFINAE always applies in a constraint expression or a requirement
1302       // in a requires expression.
1303       assert(Active->DeductionInfo && "Missing deduction info pointer");
1304       return Active->DeductionInfo;
1305 
1306     case CodeSynthesisContext::DeclaringSpecialMember:
1307     case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
1308     case CodeSynthesisContext::DefiningSynthesizedFunction:
1309     case CodeSynthesisContext::InitializingStructuredBinding:
1310     case CodeSynthesisContext::MarkingClassDllexported:
1311     case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
1312     case CodeSynthesisContext::BuildingDeductionGuides:
1313       // This happens in a context unrelated to template instantiation, so
1314       // there is no SFINAE.
1315       return std::nullopt;
1316 
1317     case CodeSynthesisContext::ExceptionSpecEvaluation:
1318       // FIXME: This should not be treated as a SFINAE context, because
1319       // we will cache an incorrect exception specification. However, clang
1320       // bootstrap relies this! See PR31692.
1321       break;
1322 
1323     case CodeSynthesisContext::Memoization:
1324       break;
1325     }
1326 
1327     // The inner context was transparent for SFINAE. If it occurred within a
1328     // non-instantiation SFINAE context, then SFINAE applies.
1329     if (Active->SavedInNonInstantiationSFINAEContext)
1330       return std::optional<TemplateDeductionInfo *>(nullptr);
1331   }
1332 
1333   return std::nullopt;
1334 }
1335 
1336 //===----------------------------------------------------------------------===/
1337 // Template Instantiation for Types
1338 //===----------------------------------------------------------------------===/
1339 namespace {
1340   class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1341     const MultiLevelTemplateArgumentList &TemplateArgs;
1342     SourceLocation Loc;
1343     DeclarationName Entity;
1344     // Whether to evaluate the C++20 constraints or simply substitute into them.
1345     bool EvaluateConstraints = true;
1346 
1347   public:
1348     typedef TreeTransform<TemplateInstantiator> inherited;
1349 
TemplateInstantiator(Sema & SemaRef,const MultiLevelTemplateArgumentList & TemplateArgs,SourceLocation Loc,DeclarationName Entity)1350     TemplateInstantiator(Sema &SemaRef,
1351                          const MultiLevelTemplateArgumentList &TemplateArgs,
1352                          SourceLocation Loc, DeclarationName Entity)
1353         : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1354           Entity(Entity) {}
1355 
setEvaluateConstraints(bool B)1356     void setEvaluateConstraints(bool B) {
1357       EvaluateConstraints = B;
1358     }
getEvaluateConstraints()1359     bool getEvaluateConstraints() {
1360       return EvaluateConstraints;
1361     }
1362 
1363     /// Determine whether the given type \p T has already been
1364     /// transformed.
1365     ///
1366     /// For the purposes of template instantiation, a type has already been
1367     /// transformed if it is NULL or if it is not dependent.
1368     bool AlreadyTransformed(QualType T);
1369 
1370     /// Returns the location of the entity being instantiated, if known.
getBaseLocation()1371     SourceLocation getBaseLocation() { return Loc; }
1372 
1373     /// Returns the name of the entity being instantiated, if any.
getBaseEntity()1374     DeclarationName getBaseEntity() { return Entity; }
1375 
1376     /// Sets the "base" location and entity when that
1377     /// information is known based on another transformation.
setBase(SourceLocation Loc,DeclarationName Entity)1378     void setBase(SourceLocation Loc, DeclarationName Entity) {
1379       this->Loc = Loc;
1380       this->Entity = Entity;
1381     }
1382 
TransformTemplateDepth(unsigned Depth)1383     unsigned TransformTemplateDepth(unsigned Depth) {
1384       return TemplateArgs.getNewDepth(Depth);
1385     }
1386 
getPackIndex(TemplateArgument Pack)1387     std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1388       int Index = getSema().ArgumentPackSubstitutionIndex;
1389       if (Index == -1)
1390         return std::nullopt;
1391       return Pack.pack_size() - 1 - Index;
1392     }
1393 
TryExpandParameterPacks(SourceLocation EllipsisLoc,SourceRange PatternRange,ArrayRef<UnexpandedParameterPack> Unexpanded,bool & ShouldExpand,bool & RetainExpansion,std::optional<unsigned> & NumExpansions)1394     bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1395                                  SourceRange PatternRange,
1396                                  ArrayRef<UnexpandedParameterPack> Unexpanded,
1397                                  bool &ShouldExpand, bool &RetainExpansion,
1398                                  std::optional<unsigned> &NumExpansions) {
1399       return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1400                                                        PatternRange, Unexpanded,
1401                                                        TemplateArgs,
1402                                                        ShouldExpand,
1403                                                        RetainExpansion,
1404                                                        NumExpansions);
1405     }
1406 
ExpandingFunctionParameterPack(ParmVarDecl * Pack)1407     void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1408       SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
1409     }
1410 
ForgetPartiallySubstitutedPack()1411     TemplateArgument ForgetPartiallySubstitutedPack() {
1412       TemplateArgument Result;
1413       if (NamedDecl *PartialPack
1414             = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
1415         MultiLevelTemplateArgumentList &TemplateArgs
1416           = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1417         unsigned Depth, Index;
1418         std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1419         if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1420           Result = TemplateArgs(Depth, Index);
1421           TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1422         }
1423       }
1424 
1425       return Result;
1426     }
1427 
RememberPartiallySubstitutedPack(TemplateArgument Arg)1428     void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1429       if (Arg.isNull())
1430         return;
1431 
1432       if (NamedDecl *PartialPack
1433             = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
1434         MultiLevelTemplateArgumentList &TemplateArgs
1435         = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1436         unsigned Depth, Index;
1437         std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1438         TemplateArgs.setArgument(Depth, Index, Arg);
1439       }
1440     }
1441 
1442     /// Transform the given declaration by instantiating a reference to
1443     /// this declaration.
1444     Decl *TransformDecl(SourceLocation Loc, Decl *D);
1445 
transformAttrs(Decl * Old,Decl * New)1446     void transformAttrs(Decl *Old, Decl *New) {
1447       SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1448     }
1449 
transformedLocalDecl(Decl * Old,ArrayRef<Decl * > NewDecls)1450     void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1451       if (Old->isParameterPack()) {
1452         SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
1453         for (auto *New : NewDecls)
1454           SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
1455               Old, cast<VarDecl>(New));
1456         return;
1457       }
1458 
1459       assert(NewDecls.size() == 1 &&
1460              "should only have multiple expansions for a pack");
1461       Decl *New = NewDecls.front();
1462 
1463       // If we've instantiated the call operator of a lambda or the call
1464       // operator template of a generic lambda, update the "instantiation of"
1465       // information.
1466       auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1467       if (NewMD && isLambdaCallOperator(NewMD)) {
1468         auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1469         if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1470           NewTD->setInstantiatedFromMemberTemplate(
1471               OldMD->getDescribedFunctionTemplate());
1472         else
1473           NewMD->setInstantiationOfMemberFunction(OldMD,
1474                                                   TSK_ImplicitInstantiation);
1475       }
1476 
1477       SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
1478 
1479       // We recreated a local declaration, but not by instantiating it. There
1480       // may be pending dependent diagnostics to produce.
1481       if (auto *DC = dyn_cast<DeclContext>(Old);
1482           DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1483         SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1484     }
1485 
1486     /// Transform the definition of the given declaration by
1487     /// instantiating it.
1488     Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1489 
1490     /// Transform the first qualifier within a scope by instantiating the
1491     /// declaration.
1492     NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1493 
1494     bool TransformExceptionSpec(SourceLocation Loc,
1495                                 FunctionProtoType::ExceptionSpecInfo &ESI,
1496                                 SmallVectorImpl<QualType> &Exceptions,
1497                                 bool &Changed);
1498 
1499     /// Rebuild the exception declaration and register the declaration
1500     /// as an instantiated local.
1501     VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1502                                   TypeSourceInfo *Declarator,
1503                                   SourceLocation StartLoc,
1504                                   SourceLocation NameLoc,
1505                                   IdentifierInfo *Name);
1506 
1507     /// Rebuild the Objective-C exception declaration and register the
1508     /// declaration as an instantiated local.
1509     VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1510                                       TypeSourceInfo *TSInfo, QualType T);
1511 
1512     /// Check for tag mismatches when instantiating an
1513     /// elaborated type.
1514     QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1515                                    ElaboratedTypeKeyword Keyword,
1516                                    NestedNameSpecifierLoc QualifierLoc,
1517                                    QualType T);
1518 
1519     TemplateName
1520     TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1521                           SourceLocation NameLoc,
1522                           QualType ObjectType = QualType(),
1523                           NamedDecl *FirstQualifierInScope = nullptr,
1524                           bool AllowInjectedClassName = false);
1525 
1526     const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1527     const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1528     const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1529                                                   const Stmt *InstS,
1530                                                   const NoInlineAttr *A);
1531     const AlwaysInlineAttr *
1532     TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1533                                   const AlwaysInlineAttr *A);
1534     const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1535     ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1536     ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1537     ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1538 
1539     ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1540                                             NonTypeTemplateParmDecl *D);
1541     ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1542                                            SubstNonTypeTemplateParmPackExpr *E);
1543     ExprResult TransformSubstNonTypeTemplateParmExpr(
1544                                            SubstNonTypeTemplateParmExpr *E);
1545 
1546     /// Rebuild a DeclRefExpr for a VarDecl reference.
1547     ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1548 
1549     /// Transform a reference to a function or init-capture parameter pack.
1550     ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1551 
1552     /// Transform a FunctionParmPackExpr which was built when we couldn't
1553     /// expand a function parameter pack reference which refers to an expanded
1554     /// pack.
1555     ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1556 
TransformFunctionProtoType(TypeLocBuilder & TLB,FunctionProtoTypeLoc TL)1557     QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1558                                         FunctionProtoTypeLoc TL) {
1559       // Call the base version; it will forward to our overridden version below.
1560       return inherited::TransformFunctionProtoType(TLB, TL);
1561     }
1562 
TransformInjectedClassNameType(TypeLocBuilder & TLB,InjectedClassNameTypeLoc TL)1563     QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1564                                             InjectedClassNameTypeLoc TL) {
1565       auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1566       // Special case for transforming a deduction guide, we return a
1567       // transformed TemplateSpecializationType.
1568       if (Type.isNull() &&
1569           SemaRef.CodeSynthesisContexts.back().Kind ==
1570               Sema::CodeSynthesisContext::BuildingDeductionGuides) {
1571         // Return a TemplateSpecializationType for transforming a deduction
1572         // guide.
1573         if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1574           auto Type =
1575               inherited::TransformType(ICT->getInjectedSpecializationType());
1576           TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1577           return Type;
1578         }
1579       }
1580       return Type;
1581     }
1582     // Override the default version to handle a rewrite-template-arg-pack case
1583     // for building a deduction guide.
TransformTemplateArgument(const TemplateArgumentLoc & Input,TemplateArgumentLoc & Output,bool Uneval=false)1584     bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1585                                    TemplateArgumentLoc &Output,
1586                                    bool Uneval = false) {
1587       const TemplateArgument &Arg = Input.getArgument();
1588       std::vector<TemplateArgument> TArgs;
1589       switch (Arg.getKind()) {
1590       case TemplateArgument::Pack:
1591         // Literally rewrite the template argument pack, instead of unpacking
1592         // it.
1593         for (auto &pack : Arg.getPackAsArray()) {
1594           TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1595               pack, QualType(), SourceLocation{});
1596           TemplateArgumentLoc Output;
1597           if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1598             return true; // fails
1599           TArgs.push_back(Output.getArgument());
1600         }
1601         Output = SemaRef.getTrivialTemplateArgumentLoc(
1602             TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1603             QualType(), SourceLocation{});
1604         return false;
1605       default:
1606         break;
1607       }
1608       return inherited::TransformTemplateArgument(Input, Output, Uneval);
1609     }
1610 
1611     template<typename Fn>
1612     QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1613                                         FunctionProtoTypeLoc TL,
1614                                         CXXRecordDecl *ThisContext,
1615                                         Qualifiers ThisTypeQuals,
1616                                         Fn TransformExceptionSpec);
1617 
1618     ParmVarDecl *
1619     TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1620                                std::optional<unsigned> NumExpansions,
1621                                bool ExpectParameterPack);
1622 
1623     using inherited::TransformTemplateTypeParmType;
1624     /// Transforms a template type parameter type by performing
1625     /// substitution of the corresponding template type argument.
1626     QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1627                                            TemplateTypeParmTypeLoc TL,
1628                                            bool SuppressObjCLifetime);
1629 
1630     QualType BuildSubstTemplateTypeParmType(
1631         TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1632         Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1633         TemplateArgument Arg, SourceLocation NameLoc);
1634 
1635     /// Transforms an already-substituted template type parameter pack
1636     /// into either itself (if we aren't substituting into its pack expansion)
1637     /// or the appropriate substituted argument.
1638     using inherited::TransformSubstTemplateTypeParmPackType;
1639     QualType
1640     TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1641                                            SubstTemplateTypeParmPackTypeLoc TL,
1642                                            bool SuppressObjCLifetime);
1643 
1644     CXXRecordDecl::LambdaDependencyKind
ComputeLambdaDependency(LambdaScopeInfo * LSI)1645     ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1646       if (auto TypeAlias =
1647               TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1648                   getSema());
1649           TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1650                            LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1651         unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1652         if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1653           return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1654         for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1655           if (TA.isDependent())
1656             return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1657       }
1658       return inherited::ComputeLambdaDependency(LSI);
1659     }
1660 
TransformLambdaExpr(LambdaExpr * E)1661     ExprResult TransformLambdaExpr(LambdaExpr *E) {
1662       LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1663       Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1664 
1665       ExprResult Result = inherited::TransformLambdaExpr(E);
1666       if (Result.isInvalid())
1667         return Result;
1668 
1669       CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
1670       for (ParmVarDecl *PVD : MD->parameters()) {
1671         assert(PVD && "null in a parameter list");
1672         if (!PVD->hasDefaultArg())
1673           continue;
1674         Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1675         // FIXME: Obtain the source location for the '=' token.
1676         SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1677         if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1678           // If substitution fails, the default argument is set to a
1679           // RecoveryExpr that wraps the uninstantiated default argument so
1680           // that downstream diagnostics are omitted.
1681           ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1682               UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1683               { UninstExpr }, UninstExpr->getType());
1684           if (ErrorResult.isUsable())
1685             PVD->setDefaultArg(ErrorResult.get());
1686         }
1687       }
1688 
1689       return Result;
1690     }
1691 
TransformLambdaBody(LambdaExpr * E,Stmt * Body)1692     StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1693       // Currently, we instantiate the body when instantiating the lambda
1694       // expression. However, `EvaluateConstraints` is disabled during the
1695       // instantiation of the lambda expression, causing the instantiation
1696       // failure of the return type requirement in the body. If p0588r1 is fully
1697       // implemented, the body will be lazily instantiated, and this problem
1698       // will not occur. Here, `EvaluateConstraints` is temporarily set to
1699       // `true` to temporarily fix this issue.
1700       // FIXME: This temporary fix can be removed after fully implementing
1701       // p0588r1.
1702       bool Prev = EvaluateConstraints;
1703       EvaluateConstraints = true;
1704       StmtResult Stmt = inherited::TransformLambdaBody(E, Body);
1705       EvaluateConstraints = Prev;
1706       return Stmt;
1707     }
1708 
TransformRequiresExpr(RequiresExpr * E)1709     ExprResult TransformRequiresExpr(RequiresExpr *E) {
1710       LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1711       ExprResult TransReq = inherited::TransformRequiresExpr(E);
1712       if (TransReq.isInvalid())
1713         return TransReq;
1714       assert(TransReq.get() != E &&
1715              "Do not change value of isSatisfied for the existing expression. "
1716              "Create a new expression instead.");
1717       if (E->getBody()->isDependentContext()) {
1718         Sema::SFINAETrap Trap(SemaRef);
1719         // We recreate the RequiresExpr body, but not by instantiating it.
1720         // Produce pending diagnostics for dependent access check.
1721         SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1722         // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1723         if (Trap.hasErrorOccurred())
1724           TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1725       }
1726       return TransReq;
1727     }
1728 
TransformRequiresExprRequirements(ArrayRef<concepts::Requirement * > Reqs,SmallVectorImpl<concepts::Requirement * > & Transformed)1729     bool TransformRequiresExprRequirements(
1730         ArrayRef<concepts::Requirement *> Reqs,
1731         SmallVectorImpl<concepts::Requirement *> &Transformed) {
1732       bool SatisfactionDetermined = false;
1733       for (concepts::Requirement *Req : Reqs) {
1734         concepts::Requirement *TransReq = nullptr;
1735         if (!SatisfactionDetermined) {
1736           if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1737             TransReq = TransformTypeRequirement(TypeReq);
1738           else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1739             TransReq = TransformExprRequirement(ExprReq);
1740           else
1741             TransReq = TransformNestedRequirement(
1742                 cast<concepts::NestedRequirement>(Req));
1743           if (!TransReq)
1744             return true;
1745           if (!TransReq->isDependent() && !TransReq->isSatisfied())
1746             // [expr.prim.req]p6
1747             //   [...]  The substitution and semantic constraint checking
1748             //   proceeds in lexical order and stops when a condition that
1749             //   determines the result of the requires-expression is
1750             //   encountered. [..]
1751             SatisfactionDetermined = true;
1752         } else
1753           TransReq = Req;
1754         Transformed.push_back(TransReq);
1755       }
1756       return false;
1757     }
1758 
TransformTemplateParameterList(TemplateParameterList * OrigTPL)1759     TemplateParameterList *TransformTemplateParameterList(
1760                               TemplateParameterList *OrigTPL)  {
1761       if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1762 
1763       DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1764       TemplateDeclInstantiator  DeclInstantiator(getSema(),
1765                         /* DeclContext *Owner */ Owner, TemplateArgs);
1766       DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1767       return DeclInstantiator.SubstTemplateParams(OrigTPL);
1768     }
1769 
1770     concepts::TypeRequirement *
1771     TransformTypeRequirement(concepts::TypeRequirement *Req);
1772     concepts::ExprRequirement *
1773     TransformExprRequirement(concepts::ExprRequirement *Req);
1774     concepts::NestedRequirement *
1775     TransformNestedRequirement(concepts::NestedRequirement *Req);
1776     ExprResult TransformRequiresTypeParams(
1777         SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1778         RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1779         SmallVectorImpl<QualType> &PTypes,
1780         SmallVectorImpl<ParmVarDecl *> &TransParams,
1781         Sema::ExtParameterInfoBuilder &PInfos);
1782 
1783   private:
1784     ExprResult
1785     transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1786                                     const NonTypeTemplateParmDecl *parm,
1787                                     SourceLocation loc, TemplateArgument arg,
1788                                     std::optional<unsigned> PackIndex);
1789   };
1790 }
1791 
AlreadyTransformed(QualType T)1792 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1793   if (T.isNull())
1794     return true;
1795 
1796   if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
1797     return false;
1798 
1799   getSema().MarkDeclarationsReferencedInType(Loc, T);
1800   return true;
1801 }
1802 
1803 static TemplateArgument
getPackSubstitutedTemplateArgument(Sema & S,TemplateArgument Arg)1804 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1805   assert(S.ArgumentPackSubstitutionIndex >= 0);
1806   assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1807   Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1808   if (Arg.isPackExpansion())
1809     Arg = Arg.getPackExpansionPattern();
1810   return Arg;
1811 }
1812 
TransformDecl(SourceLocation Loc,Decl * D)1813 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1814   if (!D)
1815     return nullptr;
1816 
1817   if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1818     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1819       // If the corresponding template argument is NULL or non-existent, it's
1820       // because we are performing instantiation from explicitly-specified
1821       // template arguments in a function template, but there were some
1822       // arguments left unspecified.
1823       if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1824                                             TTP->getPosition()))
1825         return D;
1826 
1827       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1828 
1829       if (TTP->isParameterPack()) {
1830         assert(Arg.getKind() == TemplateArgument::Pack &&
1831                "Missing argument pack");
1832         Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1833       }
1834 
1835       TemplateName Template = Arg.getAsTemplate();
1836       assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1837              "Wrong kind of template template argument");
1838       return Template.getAsTemplateDecl();
1839     }
1840 
1841     // Fall through to find the instantiated declaration for this template
1842     // template parameter.
1843   }
1844 
1845   return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1846 }
1847 
TransformDefinition(SourceLocation Loc,Decl * D)1848 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1849   Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1850   if (!Inst)
1851     return nullptr;
1852 
1853   getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1854   return Inst;
1855 }
1856 
TransformExceptionSpec(SourceLocation Loc,FunctionProtoType::ExceptionSpecInfo & ESI,SmallVectorImpl<QualType> & Exceptions,bool & Changed)1857 bool TemplateInstantiator::TransformExceptionSpec(
1858     SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
1859     SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1860   if (ESI.Type == EST_Uninstantiated) {
1861     ESI.instantiate();
1862     Changed = true;
1863   }
1864   return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1865 }
1866 
1867 NamedDecl *
TransformFirstQualifierInScope(NamedDecl * D,SourceLocation Loc)1868 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1869                                                      SourceLocation Loc) {
1870   // If the first part of the nested-name-specifier was a template type
1871   // parameter, instantiate that type parameter down to a tag type.
1872   if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1873     const TemplateTypeParmType *TTP
1874       = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1875 
1876     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1877       // FIXME: This needs testing w/ member access expressions.
1878       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1879 
1880       if (TTP->isParameterPack()) {
1881         assert(Arg.getKind() == TemplateArgument::Pack &&
1882                "Missing argument pack");
1883 
1884         if (getSema().ArgumentPackSubstitutionIndex == -1)
1885           return nullptr;
1886 
1887         Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1888       }
1889 
1890       QualType T = Arg.getAsType();
1891       if (T.isNull())
1892         return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1893 
1894       if (const TagType *Tag = T->getAs<TagType>())
1895         return Tag->getDecl();
1896 
1897       // The resulting type is not a tag; complain.
1898       getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1899       return nullptr;
1900     }
1901   }
1902 
1903   return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1904 }
1905 
1906 VarDecl *
RebuildExceptionDecl(VarDecl * ExceptionDecl,TypeSourceInfo * Declarator,SourceLocation StartLoc,SourceLocation NameLoc,IdentifierInfo * Name)1907 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1908                                            TypeSourceInfo *Declarator,
1909                                            SourceLocation StartLoc,
1910                                            SourceLocation NameLoc,
1911                                            IdentifierInfo *Name) {
1912   VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1913                                                  StartLoc, NameLoc, Name);
1914   if (Var)
1915     getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1916   return Var;
1917 }
1918 
RebuildObjCExceptionDecl(VarDecl * ExceptionDecl,TypeSourceInfo * TSInfo,QualType T)1919 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1920                                                         TypeSourceInfo *TSInfo,
1921                                                         QualType T) {
1922   VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1923   if (Var)
1924     getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1925   return Var;
1926 }
1927 
1928 QualType
RebuildElaboratedType(SourceLocation KeywordLoc,ElaboratedTypeKeyword Keyword,NestedNameSpecifierLoc QualifierLoc,QualType T)1929 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1930                                             ElaboratedTypeKeyword Keyword,
1931                                             NestedNameSpecifierLoc QualifierLoc,
1932                                             QualType T) {
1933   if (const TagType *TT = T->getAs<TagType>()) {
1934     TagDecl* TD = TT->getDecl();
1935 
1936     SourceLocation TagLocation = KeywordLoc;
1937 
1938     IdentifierInfo *Id = TD->getIdentifier();
1939 
1940     // TODO: should we even warn on struct/class mismatches for this?  Seems
1941     // like it's likely to produce a lot of spurious errors.
1942     if (Id && Keyword != ElaboratedTypeKeyword::None &&
1943         Keyword != ElaboratedTypeKeyword::Typename) {
1944       TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1945       if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1946                                                 TagLocation, Id)) {
1947         SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1948           << Id
1949           << FixItHint::CreateReplacement(SourceRange(TagLocation),
1950                                           TD->getKindName());
1951         SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1952       }
1953     }
1954   }
1955 
1956   return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1957 }
1958 
TransformTemplateName(CXXScopeSpec & SS,TemplateName Name,SourceLocation NameLoc,QualType ObjectType,NamedDecl * FirstQualifierInScope,bool AllowInjectedClassName)1959 TemplateName TemplateInstantiator::TransformTemplateName(
1960     CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1961     QualType ObjectType, NamedDecl *FirstQualifierInScope,
1962     bool AllowInjectedClassName) {
1963   if (TemplateTemplateParmDecl *TTP
1964        = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1965     if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1966       // If the corresponding template argument is NULL or non-existent, it's
1967       // because we are performing instantiation from explicitly-specified
1968       // template arguments in a function template, but there were some
1969       // arguments left unspecified.
1970       if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1971                                             TTP->getPosition()))
1972         return Name;
1973 
1974       TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1975 
1976       if (TemplateArgs.isRewrite()) {
1977         // We're rewriting the template parameter as a reference to another
1978         // template parameter.
1979         if (Arg.getKind() == TemplateArgument::Pack) {
1980           assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1981                  "unexpected pack arguments in template rewrite");
1982           Arg = Arg.pack_begin()->getPackExpansionPattern();
1983         }
1984         assert(Arg.getKind() == TemplateArgument::Template &&
1985                "unexpected nontype template argument kind in template rewrite");
1986         return Arg.getAsTemplate();
1987       }
1988 
1989       auto [AssociatedDecl, Final] =
1990           TemplateArgs.getAssociatedDecl(TTP->getDepth());
1991       std::optional<unsigned> PackIndex;
1992       if (TTP->isParameterPack()) {
1993         assert(Arg.getKind() == TemplateArgument::Pack &&
1994                "Missing argument pack");
1995 
1996         if (getSema().ArgumentPackSubstitutionIndex == -1) {
1997           // We have the template argument pack to substitute, but we're not
1998           // actually expanding the enclosing pack expansion yet. So, just
1999           // keep the entire argument pack.
2000           return getSema().Context.getSubstTemplateTemplateParmPack(
2001               Arg, AssociatedDecl, TTP->getIndex(), Final);
2002         }
2003 
2004         PackIndex = getPackIndex(Arg);
2005         Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2006       }
2007 
2008       TemplateName Template = Arg.getAsTemplate();
2009       assert(!Template.isNull() && "Null template template argument");
2010 
2011       if (Final)
2012         return Template;
2013       return getSema().Context.getSubstTemplateTemplateParm(
2014           Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2015     }
2016   }
2017 
2018   if (SubstTemplateTemplateParmPackStorage *SubstPack
2019       = Name.getAsSubstTemplateTemplateParmPack()) {
2020     if (getSema().ArgumentPackSubstitutionIndex == -1)
2021       return Name;
2022 
2023     TemplateArgument Pack = SubstPack->getArgumentPack();
2024     TemplateName Template =
2025         getPackSubstitutedTemplateArgument(getSema(), Pack).getAsTemplate();
2026     if (SubstPack->getFinal())
2027       return Template;
2028     return getSema().Context.getSubstTemplateTemplateParm(
2029         Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2030         getPackIndex(Pack));
2031   }
2032 
2033   return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2034                                           FirstQualifierInScope,
2035                                           AllowInjectedClassName);
2036 }
2037 
2038 ExprResult
TransformPredefinedExpr(PredefinedExpr * E)2039 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2040   if (!E->isTypeDependent())
2041     return E;
2042 
2043   return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2044 }
2045 
2046 ExprResult
TransformTemplateParmRefExpr(DeclRefExpr * E,NonTypeTemplateParmDecl * NTTP)2047 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2048                                                NonTypeTemplateParmDecl *NTTP) {
2049   // If the corresponding template argument is NULL or non-existent, it's
2050   // because we are performing instantiation from explicitly-specified
2051   // template arguments in a function template, but there were some
2052   // arguments left unspecified.
2053   if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2054                                         NTTP->getPosition()))
2055     return E;
2056 
2057   TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2058 
2059   if (TemplateArgs.isRewrite()) {
2060     // We're rewriting the template parameter as a reference to another
2061     // template parameter.
2062     if (Arg.getKind() == TemplateArgument::Pack) {
2063       assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2064              "unexpected pack arguments in template rewrite");
2065       Arg = Arg.pack_begin()->getPackExpansionPattern();
2066     }
2067     assert(Arg.getKind() == TemplateArgument::Expression &&
2068            "unexpected nontype template argument kind in template rewrite");
2069     // FIXME: This can lead to the same subexpression appearing multiple times
2070     // in a complete expression.
2071     return Arg.getAsExpr();
2072   }
2073 
2074   auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2075   std::optional<unsigned> PackIndex;
2076   if (NTTP->isParameterPack()) {
2077     assert(Arg.getKind() == TemplateArgument::Pack &&
2078            "Missing argument pack");
2079 
2080     if (getSema().ArgumentPackSubstitutionIndex == -1) {
2081       // We have an argument pack, but we can't select a particular argument
2082       // out of it yet. Therefore, we'll build an expression to hold on to that
2083       // argument pack.
2084       QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2085                                               E->getLocation(),
2086                                               NTTP->getDeclName());
2087       if (TargetType.isNull())
2088         return ExprError();
2089 
2090       QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2091       if (TargetType->isRecordType())
2092         ExprType.addConst();
2093       // FIXME: Pass in Final.
2094       return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2095           ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2096           E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2097     }
2098     PackIndex = getPackIndex(Arg);
2099     Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2100   }
2101   // FIXME: Don't put subst node on Final replacement.
2102   return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2103                                          Arg, PackIndex);
2104 }
2105 
2106 const CXXAssumeAttr *
TransformCXXAssumeAttr(const CXXAssumeAttr * AA)2107 TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2108   ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2109   if (!Res.isUsable())
2110     return AA;
2111 
2112   Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2113                                      AA->getRange());
2114   if (!Res.isUsable())
2115     return AA;
2116 
2117   return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2118                                        AA->getRange());
2119 }
2120 
2121 const LoopHintAttr *
TransformLoopHintAttr(const LoopHintAttr * LH)2122 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2123   Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2124 
2125   if (TransformedExpr == LH->getValue())
2126     return LH;
2127 
2128   // Generate error if there is a problem with the value.
2129   if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2130                                   LH->getSemanticSpelling() ==
2131                                       LoopHintAttr::Pragma_unroll))
2132     return LH;
2133 
2134   LoopHintAttr::OptionType Option = LH->getOption();
2135   LoopHintAttr::LoopHintState State = LH->getState();
2136 
2137   llvm::APSInt ValueAPS =
2138       TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2139   // The values of 0 and 1 block any unrolling of the loop.
2140   if (ValueAPS.isZero() || ValueAPS.isOne()) {
2141     Option = LoopHintAttr::Unroll;
2142     State = LoopHintAttr::Disable;
2143   }
2144 
2145   // Create new LoopHintValueAttr with integral expression in place of the
2146   // non-type template parameter.
2147   return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2148                                       TransformedExpr, *LH);
2149 }
TransformStmtNoInlineAttr(const Stmt * OrigS,const Stmt * InstS,const NoInlineAttr * A)2150 const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2151     const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2152   if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2153     return nullptr;
2154 
2155   return A;
2156 }
TransformStmtAlwaysInlineAttr(const Stmt * OrigS,const Stmt * InstS,const AlwaysInlineAttr * A)2157 const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2158     const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2159   if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2160     return nullptr;
2161 
2162   return A;
2163 }
2164 
2165 const CodeAlignAttr *
TransformCodeAlignAttr(const CodeAlignAttr * CA)2166 TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2167   Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2168   return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2169 }
2170 
transformNonTypeTemplateParmRef(Decl * AssociatedDecl,const NonTypeTemplateParmDecl * parm,SourceLocation loc,TemplateArgument arg,std::optional<unsigned> PackIndex)2171 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2172     Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2173     SourceLocation loc, TemplateArgument arg,
2174     std::optional<unsigned> PackIndex) {
2175   ExprResult result;
2176 
2177   // Determine the substituted parameter type. We can usually infer this from
2178   // the template argument, but not always.
2179   auto SubstParamType = [&] {
2180     QualType T;
2181     if (parm->isExpandedParameterPack())
2182       T = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
2183     else
2184       T = parm->getType();
2185     if (parm->isParameterPack() && isa<PackExpansionType>(T))
2186       T = cast<PackExpansionType>(T)->getPattern();
2187     return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2188   };
2189 
2190   bool refParam = false;
2191 
2192   // The template argument itself might be an expression, in which case we just
2193   // return that expression. This happens when substituting into an alias
2194   // template.
2195   if (arg.getKind() == TemplateArgument::Expression) {
2196     Expr *argExpr = arg.getAsExpr();
2197     result = argExpr;
2198     if (argExpr->isLValue()) {
2199       if (argExpr->getType()->isRecordType()) {
2200         // Check whether the parameter was actually a reference.
2201         QualType paramType = SubstParamType();
2202         if (paramType.isNull())
2203           return ExprError();
2204         refParam = paramType->isReferenceType();
2205       } else {
2206         refParam = true;
2207       }
2208     }
2209   } else if (arg.getKind() == TemplateArgument::Declaration ||
2210              arg.getKind() == TemplateArgument::NullPtr) {
2211     if (arg.getKind() == TemplateArgument::Declaration) {
2212       ValueDecl *VD = arg.getAsDecl();
2213 
2214       // Find the instantiation of the template argument.  This is
2215       // required for nested templates.
2216       VD = cast_or_null<ValueDecl>(
2217              getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2218       if (!VD)
2219         return ExprError();
2220     }
2221 
2222     QualType paramType = arg.getNonTypeTemplateArgumentType();
2223     assert(!paramType.isNull() && "type substitution failed for param type");
2224     assert(!paramType->isDependentType() && "param type still dependent");
2225     result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2226     refParam = paramType->isReferenceType();
2227   } else {
2228     QualType paramType = arg.getNonTypeTemplateArgumentType();
2229     result = SemaRef.BuildExpressionFromNonTypeTemplateArgument(arg, loc);
2230     refParam = paramType->isReferenceType();
2231     assert(result.isInvalid() ||
2232            SemaRef.Context.hasSameType(result.get()->getType(),
2233                                        paramType.getNonReferenceType()));
2234   }
2235 
2236   if (result.isInvalid())
2237     return ExprError();
2238 
2239   Expr *resultExpr = result.get();
2240   // FIXME: Don't put subst node on final replacement.
2241   return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
2242       resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2243       AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2244 }
2245 
2246 ExprResult
TransformSubstNonTypeTemplateParmPackExpr(SubstNonTypeTemplateParmPackExpr * E)2247 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2248                                           SubstNonTypeTemplateParmPackExpr *E) {
2249   if (getSema().ArgumentPackSubstitutionIndex == -1) {
2250     // We aren't expanding the parameter pack, so just return ourselves.
2251     return E;
2252   }
2253 
2254   TemplateArgument Pack = E->getArgumentPack();
2255   TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack);
2256   // FIXME: Don't put subst node on final replacement.
2257   return transformNonTypeTemplateParmRef(
2258       E->getAssociatedDecl(), E->getParameterPack(),
2259       E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2260 }
2261 
2262 ExprResult
TransformSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr * E)2263 TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2264                                           SubstNonTypeTemplateParmExpr *E) {
2265   ExprResult SubstReplacement = E->getReplacement();
2266   if (!isa<ConstantExpr>(SubstReplacement.get()))
2267     SubstReplacement = TransformExpr(E->getReplacement());
2268   if (SubstReplacement.isInvalid())
2269     return true;
2270   QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2271   if (SubstType.isNull())
2272     return true;
2273   // The type may have been previously dependent and not now, which means we
2274   // might have to implicit cast the argument to the new type, for example:
2275   // template<auto T, decltype(T) U>
2276   // concept C = sizeof(U) == 4;
2277   // void foo() requires C<2, 'a'> { }
2278   // When normalizing foo(), we first form the normalized constraints of C:
2279   // AtomicExpr(sizeof(U) == 4,
2280   //            U=SubstNonTypeTemplateParmExpr(Param=U,
2281   //                                           Expr=DeclRef(U),
2282   //                                           Type=decltype(T)))
2283   // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2284   // produce:
2285   // AtomicExpr(sizeof(U) == 4,
2286   //            U=SubstNonTypeTemplateParmExpr(Param=U,
2287   //                                           Expr=ImpCast(
2288   //                                               decltype(2),
2289   //                                               SubstNTTPE(Param=U, Expr='a',
2290   //                                                          Type=char)),
2291   //                                           Type=decltype(2)))
2292   // The call to CheckTemplateArgument here produces the ImpCast.
2293   TemplateArgument SugaredConverted, CanonicalConverted;
2294   if (SemaRef
2295           .CheckTemplateArgument(E->getParameter(), SubstType,
2296                                  SubstReplacement.get(), SugaredConverted,
2297                                  CanonicalConverted, Sema::CTAK_Specified)
2298           .isInvalid())
2299     return true;
2300   return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2301                                          E->getParameter(), E->getExprLoc(),
2302                                          SugaredConverted, E->getPackIndex());
2303 }
2304 
RebuildVarDeclRefExpr(VarDecl * PD,SourceLocation Loc)2305 ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2306                                                        SourceLocation Loc) {
2307   DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2308   return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2309 }
2310 
2311 ExprResult
TransformFunctionParmPackExpr(FunctionParmPackExpr * E)2312 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2313   if (getSema().ArgumentPackSubstitutionIndex != -1) {
2314     // We can expand this parameter pack now.
2315     VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
2316     VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2317     if (!VD)
2318       return ExprError();
2319     return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2320   }
2321 
2322   QualType T = TransformType(E->getType());
2323   if (T.isNull())
2324     return ExprError();
2325 
2326   // Transform each of the parameter expansions into the corresponding
2327   // parameters in the instantiation of the function decl.
2328   SmallVector<VarDecl *, 8> Vars;
2329   Vars.reserve(E->getNumExpansions());
2330   for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2331        I != End; ++I) {
2332     VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2333     if (!D)
2334       return ExprError();
2335     Vars.push_back(D);
2336   }
2337 
2338   auto *PackExpr =
2339       FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
2340                                    E->getParameterPackLocation(), Vars);
2341   getSema().MarkFunctionParmPackReferenced(PackExpr);
2342   return PackExpr;
2343 }
2344 
2345 ExprResult
TransformFunctionParmPackRefExpr(DeclRefExpr * E,VarDecl * PD)2346 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2347                                                        VarDecl *PD) {
2348   typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2349   llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2350     = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2351   assert(Found && "no instantiation for parameter pack");
2352 
2353   Decl *TransformedDecl;
2354   if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2355     // If this is a reference to a function parameter pack which we can
2356     // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2357     if (getSema().ArgumentPackSubstitutionIndex == -1) {
2358       QualType T = TransformType(E->getType());
2359       if (T.isNull())
2360         return ExprError();
2361       auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2362                                                     E->getExprLoc(), *Pack);
2363       getSema().MarkFunctionParmPackReferenced(PackExpr);
2364       return PackExpr;
2365     }
2366 
2367     TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2368   } else {
2369     TransformedDecl = Found->get<Decl*>();
2370   }
2371 
2372   // We have either an unexpanded pack or a specific expansion.
2373   return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2374 }
2375 
2376 ExprResult
TransformDeclRefExpr(DeclRefExpr * E)2377 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2378   NamedDecl *D = E->getDecl();
2379 
2380   // Handle references to non-type template parameters and non-type template
2381   // parameter packs.
2382   if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2383     if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2384       return TransformTemplateParmRefExpr(E, NTTP);
2385 
2386     // We have a non-type template parameter that isn't fully substituted;
2387     // FindInstantiatedDecl will find it in the local instantiation scope.
2388   }
2389 
2390   // Handle references to function parameter packs.
2391   if (VarDecl *PD = dyn_cast<VarDecl>(D))
2392     if (PD->isParameterPack())
2393       return TransformFunctionParmPackRefExpr(E, PD);
2394 
2395   return inherited::TransformDeclRefExpr(E);
2396 }
2397 
TransformCXXDefaultArgExpr(CXXDefaultArgExpr * E)2398 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2399     CXXDefaultArgExpr *E) {
2400   assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2401              getDescribedFunctionTemplate() &&
2402          "Default arg expressions are never formed in dependent cases.");
2403   return SemaRef.BuildCXXDefaultArgExpr(
2404       E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2405       E->getParam());
2406 }
2407 
2408 template<typename Fn>
TransformFunctionProtoType(TypeLocBuilder & TLB,FunctionProtoTypeLoc TL,CXXRecordDecl * ThisContext,Qualifiers ThisTypeQuals,Fn TransformExceptionSpec)2409 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2410                                  FunctionProtoTypeLoc TL,
2411                                  CXXRecordDecl *ThisContext,
2412                                  Qualifiers ThisTypeQuals,
2413                                  Fn TransformExceptionSpec) {
2414   // We need a local instantiation scope for this function prototype.
2415   LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2416   return inherited::TransformFunctionProtoType(
2417       TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2418 }
2419 
TransformFunctionTypeParam(ParmVarDecl * OldParm,int indexAdjustment,std::optional<unsigned> NumExpansions,bool ExpectParameterPack)2420 ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2421     ParmVarDecl *OldParm, int indexAdjustment,
2422     std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2423   auto NewParm = SemaRef.SubstParmVarDecl(
2424       OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2425       ExpectParameterPack, EvaluateConstraints);
2426   if (NewParm && SemaRef.getLangOpts().OpenCL)
2427     SemaRef.deduceOpenCLAddressSpace(NewParm);
2428   return NewParm;
2429 }
2430 
BuildSubstTemplateTypeParmType(TypeLocBuilder & TLB,bool SuppressObjCLifetime,bool Final,Decl * AssociatedDecl,unsigned Index,std::optional<unsigned> PackIndex,TemplateArgument Arg,SourceLocation NameLoc)2431 QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2432     TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2433     Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2434     TemplateArgument Arg, SourceLocation NameLoc) {
2435   QualType Replacement = Arg.getAsType();
2436 
2437   // If the template parameter had ObjC lifetime qualifiers,
2438   // then any such qualifiers on the replacement type are ignored.
2439   if (SuppressObjCLifetime) {
2440     Qualifiers RQs;
2441     RQs = Replacement.getQualifiers();
2442     RQs.removeObjCLifetime();
2443     Replacement =
2444         SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2445   }
2446 
2447   if (Final) {
2448     TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2449     return Replacement;
2450   }
2451   // TODO: only do this uniquing once, at the start of instantiation.
2452   QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2453       Replacement, AssociatedDecl, Index, PackIndex);
2454   SubstTemplateTypeParmTypeLoc NewTL =
2455       TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2456   NewTL.setNameLoc(NameLoc);
2457   return Result;
2458 }
2459 
2460 QualType
TransformTemplateTypeParmType(TypeLocBuilder & TLB,TemplateTypeParmTypeLoc TL,bool SuppressObjCLifetime)2461 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2462                                                     TemplateTypeParmTypeLoc TL,
2463                                                     bool SuppressObjCLifetime) {
2464   const TemplateTypeParmType *T = TL.getTypePtr();
2465   if (T->getDepth() < TemplateArgs.getNumLevels()) {
2466     // Replace the template type parameter with its corresponding
2467     // template argument.
2468 
2469     // If the corresponding template argument is NULL or doesn't exist, it's
2470     // because we are performing instantiation from explicitly-specified
2471     // template arguments in a function template class, but there were some
2472     // arguments left unspecified.
2473     if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2474       TemplateTypeParmTypeLoc NewTL
2475         = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2476       NewTL.setNameLoc(TL.getNameLoc());
2477       return TL.getType();
2478     }
2479 
2480     TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2481 
2482     if (TemplateArgs.isRewrite()) {
2483       // We're rewriting the template parameter as a reference to another
2484       // template parameter.
2485       if (Arg.getKind() == TemplateArgument::Pack) {
2486         assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2487                "unexpected pack arguments in template rewrite");
2488         Arg = Arg.pack_begin()->getPackExpansionPattern();
2489       }
2490       assert(Arg.getKind() == TemplateArgument::Type &&
2491              "unexpected nontype template argument kind in template rewrite");
2492       QualType NewT = Arg.getAsType();
2493       TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2494       return NewT;
2495     }
2496 
2497     auto [AssociatedDecl, Final] =
2498         TemplateArgs.getAssociatedDecl(T->getDepth());
2499     std::optional<unsigned> PackIndex;
2500     if (T->isParameterPack()) {
2501       assert(Arg.getKind() == TemplateArgument::Pack &&
2502              "Missing argument pack");
2503 
2504       if (getSema().ArgumentPackSubstitutionIndex == -1) {
2505         // We have the template argument pack, but we're not expanding the
2506         // enclosing pack expansion yet. Just save the template argument
2507         // pack for later substitution.
2508         QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2509             AssociatedDecl, T->getIndex(), Final, Arg);
2510         SubstTemplateTypeParmPackTypeLoc NewTL
2511           = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2512         NewTL.setNameLoc(TL.getNameLoc());
2513         return Result;
2514       }
2515 
2516       // PackIndex starts from last element.
2517       PackIndex = getPackIndex(Arg);
2518       Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2519     }
2520 
2521     assert(Arg.getKind() == TemplateArgument::Type &&
2522            "Template argument kind mismatch");
2523 
2524     return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2525                                           AssociatedDecl, T->getIndex(),
2526                                           PackIndex, Arg, TL.getNameLoc());
2527   }
2528 
2529   // The template type parameter comes from an inner template (e.g.,
2530   // the template parameter list of a member template inside the
2531   // template we are instantiating). Create a new template type
2532   // parameter with the template "level" reduced by one.
2533   TemplateTypeParmDecl *NewTTPDecl = nullptr;
2534   if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2535     NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2536         TransformDecl(TL.getNameLoc(), OldTTPDecl));
2537   QualType Result = getSema().Context.getTemplateTypeParmType(
2538       T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2539       T->isParameterPack(), NewTTPDecl);
2540   TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2541   NewTL.setNameLoc(TL.getNameLoc());
2542   return Result;
2543 }
2544 
TransformSubstTemplateTypeParmPackType(TypeLocBuilder & TLB,SubstTemplateTypeParmPackTypeLoc TL,bool SuppressObjCLifetime)2545 QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2546     TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2547     bool SuppressObjCLifetime) {
2548   const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2549 
2550   Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2551 
2552   if (getSema().ArgumentPackSubstitutionIndex == -1) {
2553     // We aren't expanding the parameter pack, so just return ourselves.
2554     QualType Result = TL.getType();
2555     if (NewReplaced != T->getAssociatedDecl())
2556       Result = getSema().Context.getSubstTemplateTypeParmPackType(
2557           NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2558     SubstTemplateTypeParmPackTypeLoc NewTL =
2559         TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2560     NewTL.setNameLoc(TL.getNameLoc());
2561     return Result;
2562   }
2563 
2564   TemplateArgument Pack = T->getArgumentPack();
2565   TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack);
2566   return BuildSubstTemplateTypeParmType(
2567       TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2568       getPackIndex(Pack), Arg, TL.getNameLoc());
2569 }
2570 
2571 static concepts::Requirement::SubstitutionDiagnostic *
createSubstDiag(Sema & S,TemplateDeductionInfo & Info,concepts::EntityPrinter Printer)2572 createSubstDiag(Sema &S, TemplateDeductionInfo &Info,
2573                 concepts::EntityPrinter Printer) {
2574   SmallString<128> Message;
2575   SourceLocation ErrorLoc;
2576   if (Info.hasSFINAEDiagnostic()) {
2577     PartialDiagnosticAt PDA(SourceLocation(),
2578                             PartialDiagnostic::NullDiagnostic{});
2579     Info.takeSFINAEDiagnostic(PDA);
2580     PDA.second.EmitToString(S.getDiagnostics(), Message);
2581     ErrorLoc = PDA.first;
2582   } else {
2583     ErrorLoc = Info.getLocation();
2584   }
2585   SmallString<128> Entity;
2586   llvm::raw_svector_ostream OS(Entity);
2587   Printer(OS);
2588   const ASTContext &C = S.Context;
2589   return new (C) concepts::Requirement::SubstitutionDiagnostic{
2590       C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2591 }
2592 
2593 concepts::Requirement::SubstitutionDiagnostic *
createSubstDiagAt(Sema & S,SourceLocation Location,EntityPrinter Printer)2594 concepts::createSubstDiagAt(Sema &S, SourceLocation Location,
2595                             EntityPrinter Printer) {
2596   SmallString<128> Entity;
2597   llvm::raw_svector_ostream OS(Entity);
2598   Printer(OS);
2599   const ASTContext &C = S.Context;
2600   return new (C) concepts::Requirement::SubstitutionDiagnostic{
2601       /*SubstitutedEntity=*/C.backupStr(Entity),
2602       /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2603 }
2604 
TransformRequiresTypeParams(SourceLocation KWLoc,SourceLocation RBraceLoc,const RequiresExpr * RE,RequiresExprBodyDecl * Body,ArrayRef<ParmVarDecl * > Params,SmallVectorImpl<QualType> & PTypes,SmallVectorImpl<ParmVarDecl * > & TransParams,Sema::ExtParameterInfoBuilder & PInfos)2605 ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2606     SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2607     RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
2608     SmallVectorImpl<QualType> &PTypes,
2609     SmallVectorImpl<ParmVarDecl *> &TransParams,
2610     Sema::ExtParameterInfoBuilder &PInfos) {
2611 
2612   TemplateDeductionInfo Info(KWLoc);
2613   Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2614                                        RE, Info,
2615                                        SourceRange{KWLoc, RBraceLoc});
2616   Sema::SFINAETrap Trap(SemaRef);
2617 
2618   unsigned ErrorIdx;
2619   if (getDerived().TransformFunctionTypeParams(
2620           KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2621           &TransParams, PInfos, &ErrorIdx) ||
2622       Trap.hasErrorOccurred()) {
2623     SmallVector<concepts::Requirement *, 4> TransReqs;
2624     ParmVarDecl *FailedDecl = Params[ErrorIdx];
2625     // Add a 'failed' Requirement to contain the error that caused the failure
2626     // here.
2627     TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2628         SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2629     return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2630                                             TransParams, RE->getRParenLoc(),
2631                                             TransReqs, RBraceLoc);
2632   }
2633 
2634   return ExprResult{};
2635 }
2636 
2637 concepts::TypeRequirement *
TransformTypeRequirement(concepts::TypeRequirement * Req)2638 TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2639   if (!Req->isDependent() && !AlwaysRebuild())
2640     return Req;
2641   if (Req->isSubstitutionFailure()) {
2642     if (AlwaysRebuild())
2643       return RebuildTypeRequirement(
2644               Req->getSubstitutionDiagnostic());
2645     return Req;
2646   }
2647 
2648   Sema::SFINAETrap Trap(SemaRef);
2649   TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2650   Sema::InstantiatingTemplate TypeInst(SemaRef,
2651       Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2652       Req->getType()->getTypeLoc().getSourceRange());
2653   if (TypeInst.isInvalid())
2654     return nullptr;
2655   TypeSourceInfo *TransType = TransformType(Req->getType());
2656   if (!TransType || Trap.hasErrorOccurred())
2657     return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2658         [&] (llvm::raw_ostream& OS) {
2659             Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2660         }));
2661   return RebuildTypeRequirement(TransType);
2662 }
2663 
2664 concepts::ExprRequirement *
TransformExprRequirement(concepts::ExprRequirement * Req)2665 TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2666   if (!Req->isDependent() && !AlwaysRebuild())
2667     return Req;
2668 
2669   Sema::SFINAETrap Trap(SemaRef);
2670 
2671   llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2672       TransExpr;
2673   if (Req->isExprSubstitutionFailure())
2674     TransExpr = Req->getExprSubstitutionDiagnostic();
2675   else {
2676     Expr *E = Req->getExpr();
2677     TemplateDeductionInfo Info(E->getBeginLoc());
2678     Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2679                                          E->getSourceRange());
2680     if (ExprInst.isInvalid())
2681       return nullptr;
2682     ExprResult TransExprRes = TransformExpr(E);
2683     if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2684         TransExprRes.get()->hasPlaceholderType())
2685       TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2686     if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2687       TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2688         E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2689       });
2690     else
2691       TransExpr = TransExprRes.get();
2692   }
2693 
2694   std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2695   const auto &RetReq = Req->getReturnTypeRequirement();
2696   if (RetReq.isEmpty())
2697     TransRetReq.emplace();
2698   else if (RetReq.isSubstitutionFailure())
2699     TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2700   else if (RetReq.isTypeConstraint()) {
2701     TemplateParameterList *OrigTPL =
2702         RetReq.getTypeConstraintTemplateParameterList();
2703     TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2704     Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2705                                         Req, Info, OrigTPL->getSourceRange());
2706     if (TPLInst.isInvalid())
2707       return nullptr;
2708     TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2709     if (!TPL || Trap.hasErrorOccurred())
2710       TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2711           [&] (llvm::raw_ostream& OS) {
2712               RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2713                   ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2714           }));
2715     else {
2716       TPLInst.Clear();
2717       TransRetReq.emplace(TPL);
2718     }
2719   }
2720   assert(TransRetReq && "All code paths leading here must set TransRetReq");
2721   if (Expr *E = TransExpr.dyn_cast<Expr *>())
2722     return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2723                                   std::move(*TransRetReq));
2724   return RebuildExprRequirement(
2725       TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
2726       Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2727 }
2728 
2729 concepts::NestedRequirement *
TransformNestedRequirement(concepts::NestedRequirement * Req)2730 TemplateInstantiator::TransformNestedRequirement(
2731     concepts::NestedRequirement *Req) {
2732   if (!Req->isDependent() && !AlwaysRebuild())
2733     return Req;
2734   if (Req->hasInvalidConstraint()) {
2735     if (AlwaysRebuild())
2736       return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2737                                       Req->getConstraintSatisfaction());
2738     return Req;
2739   }
2740   Sema::InstantiatingTemplate ReqInst(SemaRef,
2741       Req->getConstraintExpr()->getBeginLoc(), Req,
2742       Sema::InstantiatingTemplate::ConstraintsCheck{},
2743       Req->getConstraintExpr()->getSourceRange());
2744   if (!getEvaluateConstraints()) {
2745     ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2746     if (TransConstraint.isInvalid() || !TransConstraint.get())
2747       return nullptr;
2748     if (TransConstraint.get()->isInstantiationDependent())
2749       return new (SemaRef.Context)
2750           concepts::NestedRequirement(TransConstraint.get());
2751     ConstraintSatisfaction Satisfaction;
2752     return new (SemaRef.Context) concepts::NestedRequirement(
2753         SemaRef.Context, TransConstraint.get(), Satisfaction);
2754   }
2755 
2756   ExprResult TransConstraint;
2757   ConstraintSatisfaction Satisfaction;
2758   TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc());
2759   {
2760     EnterExpressionEvaluationContext ContextRAII(
2761         SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2762     Sema::SFINAETrap Trap(SemaRef);
2763     Sema::InstantiatingTemplate ConstrInst(SemaRef,
2764         Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2765         Req->getConstraintExpr()->getSourceRange());
2766     if (ConstrInst.isInvalid())
2767       return nullptr;
2768     llvm::SmallVector<Expr *> Result;
2769     if (!SemaRef.CheckConstraintSatisfaction(
2770             nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2771             Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2772         !Result.empty())
2773       TransConstraint = Result[0];
2774     assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2775                                        "by CheckConstraintSatisfaction.");
2776   }
2777   ASTContext &C = SemaRef.Context;
2778   if (TransConstraint.isUsable() &&
2779       TransConstraint.get()->isInstantiationDependent())
2780     return new (C) concepts::NestedRequirement(TransConstraint.get());
2781   if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2782       Satisfaction.HasSubstitutionFailure()) {
2783     SmallString<128> Entity;
2784     llvm::raw_svector_ostream OS(Entity);
2785     Req->getConstraintExpr()->printPretty(OS, nullptr,
2786                                           SemaRef.getPrintingPolicy());
2787     return new (C) concepts::NestedRequirement(
2788         SemaRef.Context, C.backupStr(Entity), Satisfaction);
2789   }
2790   return new (C)
2791       concepts::NestedRequirement(C, TransConstraint.get(), Satisfaction);
2792 }
2793 
SubstType(TypeSourceInfo * T,const MultiLevelTemplateArgumentList & Args,SourceLocation Loc,DeclarationName Entity,bool AllowDeducedTST)2794 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
2795                                 const MultiLevelTemplateArgumentList &Args,
2796                                 SourceLocation Loc,
2797                                 DeclarationName Entity,
2798                                 bool AllowDeducedTST) {
2799   assert(!CodeSynthesisContexts.empty() &&
2800          "Cannot perform an instantiation without some context on the "
2801          "instantiation stack");
2802 
2803   if (!T->getType()->isInstantiationDependentType() &&
2804       !T->getType()->isVariablyModifiedType())
2805     return T;
2806 
2807   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2808   return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2809                          : Instantiator.TransformType(T);
2810 }
2811 
SubstType(TypeLoc TL,const MultiLevelTemplateArgumentList & Args,SourceLocation Loc,DeclarationName Entity)2812 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
2813                                 const MultiLevelTemplateArgumentList &Args,
2814                                 SourceLocation Loc,
2815                                 DeclarationName Entity) {
2816   assert(!CodeSynthesisContexts.empty() &&
2817          "Cannot perform an instantiation without some context on the "
2818          "instantiation stack");
2819 
2820   if (TL.getType().isNull())
2821     return nullptr;
2822 
2823   if (!TL.getType()->isInstantiationDependentType() &&
2824       !TL.getType()->isVariablyModifiedType()) {
2825     // FIXME: Make a copy of the TypeLoc data here, so that we can
2826     // return a new TypeSourceInfo. Inefficient!
2827     TypeLocBuilder TLB;
2828     TLB.pushFullCopy(TL);
2829     return TLB.getTypeSourceInfo(Context, TL.getType());
2830   }
2831 
2832   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2833   TypeLocBuilder TLB;
2834   TLB.reserve(TL.getFullDataSize());
2835   QualType Result = Instantiator.TransformType(TLB, TL);
2836   if (Result.isNull())
2837     return nullptr;
2838 
2839   return TLB.getTypeSourceInfo(Context, Result);
2840 }
2841 
2842 /// Deprecated form of the above.
SubstType(QualType T,const MultiLevelTemplateArgumentList & TemplateArgs,SourceLocation Loc,DeclarationName Entity)2843 QualType Sema::SubstType(QualType T,
2844                          const MultiLevelTemplateArgumentList &TemplateArgs,
2845                          SourceLocation Loc, DeclarationName Entity) {
2846   assert(!CodeSynthesisContexts.empty() &&
2847          "Cannot perform an instantiation without some context on the "
2848          "instantiation stack");
2849 
2850   // If T is not a dependent type or a variably-modified type, there
2851   // is nothing to do.
2852   if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2853     return T;
2854 
2855   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2856   return Instantiator.TransformType(T);
2857 }
2858 
NeedsInstantiationAsFunctionType(TypeSourceInfo * T)2859 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
2860   if (T->getType()->isInstantiationDependentType() ||
2861       T->getType()->isVariablyModifiedType())
2862     return true;
2863 
2864   TypeLoc TL = T->getTypeLoc().IgnoreParens();
2865   if (!TL.getAs<FunctionProtoTypeLoc>())
2866     return false;
2867 
2868   FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
2869   for (ParmVarDecl *P : FP.getParams()) {
2870     // This must be synthesized from a typedef.
2871     if (!P) continue;
2872 
2873     // If there are any parameters, a new TypeSourceInfo that refers to the
2874     // instantiated parameters must be built.
2875     return true;
2876   }
2877 
2878   return false;
2879 }
2880 
SubstFunctionDeclType(TypeSourceInfo * T,const MultiLevelTemplateArgumentList & Args,SourceLocation Loc,DeclarationName Entity,CXXRecordDecl * ThisContext,Qualifiers ThisTypeQuals,bool EvaluateConstraints)2881 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
2882                                 const MultiLevelTemplateArgumentList &Args,
2883                                 SourceLocation Loc,
2884                                 DeclarationName Entity,
2885                                 CXXRecordDecl *ThisContext,
2886                                 Qualifiers ThisTypeQuals,
2887                                 bool EvaluateConstraints) {
2888   assert(!CodeSynthesisContexts.empty() &&
2889          "Cannot perform an instantiation without some context on the "
2890          "instantiation stack");
2891 
2892   if (!NeedsInstantiationAsFunctionType(T))
2893     return T;
2894 
2895   TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2896   Instantiator.setEvaluateConstraints(EvaluateConstraints);
2897 
2898   TypeLocBuilder TLB;
2899 
2900   TypeLoc TL = T->getTypeLoc();
2901   TLB.reserve(TL.getFullDataSize());
2902 
2903   QualType Result;
2904 
2905   if (FunctionProtoTypeLoc Proto =
2906           TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
2907     // Instantiate the type, other than its exception specification. The
2908     // exception specification is instantiated in InitFunctionInstantiation
2909     // once we've built the FunctionDecl.
2910     // FIXME: Set the exception specification to EST_Uninstantiated here,
2911     // instead of rebuilding the function type again later.
2912     Result = Instantiator.TransformFunctionProtoType(
2913         TLB, Proto, ThisContext, ThisTypeQuals,
2914         [](FunctionProtoType::ExceptionSpecInfo &ESI,
2915            bool &Changed) { return false; });
2916   } else {
2917     Result = Instantiator.TransformType(TLB, TL);
2918   }
2919   // When there are errors resolving types, clang may use IntTy as a fallback,
2920   // breaking our assumption that function declarations have function types.
2921   if (Result.isNull() || !Result->isFunctionType())
2922     return nullptr;
2923 
2924   return TLB.getTypeSourceInfo(Context, Result);
2925 }
2926 
SubstExceptionSpec(SourceLocation Loc,FunctionProtoType::ExceptionSpecInfo & ESI,SmallVectorImpl<QualType> & ExceptionStorage,const MultiLevelTemplateArgumentList & Args)2927 bool Sema::SubstExceptionSpec(SourceLocation Loc,
2928                               FunctionProtoType::ExceptionSpecInfo &ESI,
2929                               SmallVectorImpl<QualType> &ExceptionStorage,
2930                               const MultiLevelTemplateArgumentList &Args) {
2931   bool Changed = false;
2932   TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2933   return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2934                                              Changed);
2935 }
2936 
SubstExceptionSpec(FunctionDecl * New,const FunctionProtoType * Proto,const MultiLevelTemplateArgumentList & Args)2937 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
2938                               const MultiLevelTemplateArgumentList &Args) {
2939   FunctionProtoType::ExceptionSpecInfo ESI =
2940       Proto->getExtProtoInfo().ExceptionSpec;
2941 
2942   SmallVector<QualType, 4> ExceptionStorage;
2943   if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2944                          ESI, ExceptionStorage, Args))
2945     // On error, recover by dropping the exception specification.
2946     ESI.Type = EST_None;
2947 
2948   UpdateExceptionSpec(New, ESI);
2949 }
2950 
2951 namespace {
2952 
2953   struct GetContainedInventedTypeParmVisitor :
2954     public TypeVisitor<GetContainedInventedTypeParmVisitor,
2955                        TemplateTypeParmDecl *> {
2956     using TypeVisitor<GetContainedInventedTypeParmVisitor,
2957                       TemplateTypeParmDecl *>::Visit;
2958 
Visit__anondb690eb50911::GetContainedInventedTypeParmVisitor2959     TemplateTypeParmDecl *Visit(QualType T) {
2960       if (T.isNull())
2961         return nullptr;
2962       return Visit(T.getTypePtr());
2963     }
2964     // The deduced type itself.
VisitTemplateTypeParmType__anondb690eb50911::GetContainedInventedTypeParmVisitor2965     TemplateTypeParmDecl *VisitTemplateTypeParmType(
2966         const TemplateTypeParmType *T) {
2967       if (!T->getDecl() || !T->getDecl()->isImplicit())
2968         return nullptr;
2969       return T->getDecl();
2970     }
2971 
2972     // Only these types can contain 'auto' types, and subsequently be replaced
2973     // by references to invented parameters.
2974 
VisitElaboratedType__anondb690eb50911::GetContainedInventedTypeParmVisitor2975     TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2976       return Visit(T->getNamedType());
2977     }
2978 
VisitPointerType__anondb690eb50911::GetContainedInventedTypeParmVisitor2979     TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2980       return Visit(T->getPointeeType());
2981     }
2982 
VisitBlockPointerType__anondb690eb50911::GetContainedInventedTypeParmVisitor2983     TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2984       return Visit(T->getPointeeType());
2985     }
2986 
VisitReferenceType__anondb690eb50911::GetContainedInventedTypeParmVisitor2987     TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2988       return Visit(T->getPointeeTypeAsWritten());
2989     }
2990 
VisitMemberPointerType__anondb690eb50911::GetContainedInventedTypeParmVisitor2991     TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2992       return Visit(T->getPointeeType());
2993     }
2994 
VisitArrayType__anondb690eb50911::GetContainedInventedTypeParmVisitor2995     TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2996       return Visit(T->getElementType());
2997     }
2998 
VisitDependentSizedExtVectorType__anondb690eb50911::GetContainedInventedTypeParmVisitor2999     TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3000       const DependentSizedExtVectorType *T) {
3001       return Visit(T->getElementType());
3002     }
3003 
VisitVectorType__anondb690eb50911::GetContainedInventedTypeParmVisitor3004     TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3005       return Visit(T->getElementType());
3006     }
3007 
VisitFunctionProtoType__anondb690eb50911::GetContainedInventedTypeParmVisitor3008     TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3009       return VisitFunctionType(T);
3010     }
3011 
VisitFunctionType__anondb690eb50911::GetContainedInventedTypeParmVisitor3012     TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3013       return Visit(T->getReturnType());
3014     }
3015 
VisitParenType__anondb690eb50911::GetContainedInventedTypeParmVisitor3016     TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3017       return Visit(T->getInnerType());
3018     }
3019 
VisitAttributedType__anondb690eb50911::GetContainedInventedTypeParmVisitor3020     TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3021       return Visit(T->getModifiedType());
3022     }
3023 
VisitMacroQualifiedType__anondb690eb50911::GetContainedInventedTypeParmVisitor3024     TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3025       return Visit(T->getUnderlyingType());
3026     }
3027 
VisitAdjustedType__anondb690eb50911::GetContainedInventedTypeParmVisitor3028     TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3029       return Visit(T->getOriginalType());
3030     }
3031 
VisitPackExpansionType__anondb690eb50911::GetContainedInventedTypeParmVisitor3032     TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3033       return Visit(T->getPattern());
3034     }
3035   };
3036 
3037 } // namespace
3038 
SubstTypeConstraint(TemplateTypeParmDecl * Inst,const TypeConstraint * TC,const MultiLevelTemplateArgumentList & TemplateArgs,bool EvaluateConstraints)3039 bool Sema::SubstTypeConstraint(
3040     TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3041     const MultiLevelTemplateArgumentList &TemplateArgs,
3042     bool EvaluateConstraints) {
3043   const ASTTemplateArgumentListInfo *TemplArgInfo =
3044       TC->getTemplateArgsAsWritten();
3045 
3046   if (!EvaluateConstraints) {
3047       Inst->setTypeConstraint(TC->getConceptReference(),
3048                               TC->getImmediatelyDeclaredConstraint());
3049       return false;
3050   }
3051 
3052   TemplateArgumentListInfo InstArgs;
3053 
3054   if (TemplArgInfo) {
3055     InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3056     InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3057     if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3058                                InstArgs))
3059       return true;
3060   }
3061   return AttachTypeConstraint(
3062       TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
3063       TC->getNamedConcept(),
3064       /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3065       Inst->isParameterPack()
3066           ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3067                 ->getEllipsisLoc()
3068           : SourceLocation());
3069 }
3070 
SubstParmVarDecl(ParmVarDecl * OldParm,const MultiLevelTemplateArgumentList & TemplateArgs,int indexAdjustment,std::optional<unsigned> NumExpansions,bool ExpectParameterPack,bool EvaluateConstraint)3071 ParmVarDecl *Sema::SubstParmVarDecl(
3072     ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3073     int indexAdjustment, std::optional<unsigned> NumExpansions,
3074     bool ExpectParameterPack, bool EvaluateConstraint) {
3075   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3076   TypeSourceInfo *NewDI = nullptr;
3077 
3078   TypeLoc OldTL = OldDI->getTypeLoc();
3079   if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3080 
3081     // We have a function parameter pack. Substitute into the pattern of the
3082     // expansion.
3083     NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3084                       OldParm->getLocation(), OldParm->getDeclName());
3085     if (!NewDI)
3086       return nullptr;
3087 
3088     if (NewDI->getType()->containsUnexpandedParameterPack()) {
3089       // We still have unexpanded parameter packs, which means that
3090       // our function parameter is still a function parameter pack.
3091       // Therefore, make its type a pack expansion type.
3092       NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3093                                  NumExpansions);
3094     } else if (ExpectParameterPack) {
3095       // We expected to get a parameter pack but didn't (because the type
3096       // itself is not a pack expansion type), so complain. This can occur when
3097       // the substitution goes through an alias template that "loses" the
3098       // pack expansion.
3099       Diag(OldParm->getLocation(),
3100            diag::err_function_parameter_pack_without_parameter_packs)
3101         << NewDI->getType();
3102       return nullptr;
3103     }
3104   } else {
3105     NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3106                       OldParm->getDeclName());
3107   }
3108 
3109   if (!NewDI)
3110     return nullptr;
3111 
3112   if (NewDI->getType()->isVoidType()) {
3113     Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3114     return nullptr;
3115   }
3116 
3117   // In abbreviated templates, TemplateTypeParmDecls with possible
3118   // TypeConstraints are created when the parameter list is originally parsed.
3119   // The TypeConstraints can therefore reference other functions parameters in
3120   // the abbreviated function template, which is why we must instantiate them
3121   // here, when the instantiated versions of those referenced parameters are in
3122   // scope.
3123   if (TemplateTypeParmDecl *TTP =
3124           GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3125     if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3126       auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3127           FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3128       // We will first get here when instantiating the abbreviated function
3129       // template's described function, but we might also get here later.
3130       // Make sure we do not instantiate the TypeConstraint more than once.
3131       if (Inst && !Inst->getTypeConstraint()) {
3132         if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3133           return nullptr;
3134       }
3135     }
3136   }
3137 
3138   ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
3139                                         OldParm->getInnerLocStart(),
3140                                         OldParm->getLocation(),
3141                                         OldParm->getIdentifier(),
3142                                         NewDI->getType(), NewDI,
3143                                         OldParm->getStorageClass());
3144   if (!NewParm)
3145     return nullptr;
3146 
3147   // Mark the (new) default argument as uninstantiated (if any).
3148   if (OldParm->hasUninstantiatedDefaultArg()) {
3149     Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3150     NewParm->setUninstantiatedDefaultArg(Arg);
3151   } else if (OldParm->hasUnparsedDefaultArg()) {
3152     NewParm->setUnparsedDefaultArg();
3153     UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3154   } else if (Expr *Arg = OldParm->getDefaultArg()) {
3155     // Default arguments cannot be substituted until the declaration context
3156     // for the associated function or lambda capture class is available.
3157     // This is necessary for cases like the following where construction of
3158     // the lambda capture class for the outer lambda is dependent on the
3159     // parameter types but where the default argument is dependent on the
3160     // outer lambda's declaration context.
3161     //   template <typename T>
3162     //   auto f() {
3163     //     return [](T = []{ return T{}; }()) { return 0; };
3164     //   }
3165     NewParm->setUninstantiatedDefaultArg(Arg);
3166   }
3167 
3168   NewParm->setExplicitObjectParameterLoc(
3169       OldParm->getExplicitObjectParamThisLoc());
3170   NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
3171 
3172   if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3173     // Add the new parameter to the instantiated parameter pack.
3174     CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
3175   } else {
3176     // Introduce an Old -> New mapping
3177     CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
3178   }
3179 
3180   // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3181   // can be anything, is this right ?
3182   NewParm->setDeclContext(CurContext);
3183 
3184   NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3185                         OldParm->getFunctionScopeIndex() + indexAdjustment);
3186 
3187   InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3188 
3189   return NewParm;
3190 }
3191 
SubstParmTypes(SourceLocation Loc,ArrayRef<ParmVarDecl * > Params,const FunctionProtoType::ExtParameterInfo * ExtParamInfos,const MultiLevelTemplateArgumentList & TemplateArgs,SmallVectorImpl<QualType> & ParamTypes,SmallVectorImpl<ParmVarDecl * > * OutParams,ExtParameterInfoBuilder & ParamInfos)3192 bool Sema::SubstParmTypes(
3193     SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
3194     const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3195     const MultiLevelTemplateArgumentList &TemplateArgs,
3196     SmallVectorImpl<QualType> &ParamTypes,
3197     SmallVectorImpl<ParmVarDecl *> *OutParams,
3198     ExtParameterInfoBuilder &ParamInfos) {
3199   assert(!CodeSynthesisContexts.empty() &&
3200          "Cannot perform an instantiation without some context on the "
3201          "instantiation stack");
3202 
3203   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3204                                     DeclarationName());
3205   return Instantiator.TransformFunctionTypeParams(
3206       Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3207 }
3208 
SubstDefaultArgument(SourceLocation Loc,ParmVarDecl * Param,const MultiLevelTemplateArgumentList & TemplateArgs,bool ForCallExpr)3209 bool Sema::SubstDefaultArgument(
3210     SourceLocation Loc,
3211     ParmVarDecl *Param,
3212     const MultiLevelTemplateArgumentList &TemplateArgs,
3213     bool ForCallExpr) {
3214   FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3215   Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3216 
3217   EnterExpressionEvaluationContext EvalContext(
3218       *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
3219 
3220   InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3221   if (Inst.isInvalid())
3222     return true;
3223   if (Inst.isAlreadyInstantiating()) {
3224     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3225     Param->setInvalidDecl();
3226     return true;
3227   }
3228 
3229   ExprResult Result;
3230   {
3231     // C++ [dcl.fct.default]p5:
3232     //   The names in the [default argument] expression are bound, and
3233     //   the semantic constraints are checked, at the point where the
3234     //   default argument expression appears.
3235     ContextRAII SavedContext(*this, FD);
3236     std::unique_ptr<LocalInstantiationScope> LIS;
3237 
3238     if (ForCallExpr) {
3239       // When instantiating a default argument due to use in a call expression,
3240       // an instantiation scope that includes the parameters of the callee is
3241       // required to satisfy references from the default argument. For example:
3242       //   template<typename T> void f(T a, int = decltype(a)());
3243       //   void g() { f(0); }
3244       LIS = std::make_unique<LocalInstantiationScope>(*this);
3245       FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern(
3246           /*ForDefinition*/ false);
3247       if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3248         return true;
3249     }
3250 
3251     runWithSufficientStackSpace(Loc, [&] {
3252       Result = SubstInitializer(PatternExpr, TemplateArgs,
3253                                 /*DirectInit*/ false);
3254     });
3255   }
3256   if (Result.isInvalid())
3257     return true;
3258 
3259   if (ForCallExpr) {
3260     // Check the expression as an initializer for the parameter.
3261     InitializedEntity Entity
3262       = InitializedEntity::InitializeParameter(Context, Param);
3263     InitializationKind Kind = InitializationKind::CreateCopy(
3264         Param->getLocation(),
3265         /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3266     Expr *ResultE = Result.getAs<Expr>();
3267 
3268     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3269     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3270     if (Result.isInvalid())
3271       return true;
3272 
3273     Result =
3274         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
3275                             /*DiscardedValue*/ false);
3276   } else {
3277     // FIXME: Obtain the source location for the '=' token.
3278     SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3279     Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3280   }
3281   if (Result.isInvalid())
3282       return true;
3283 
3284   // Remember the instantiated default argument.
3285   Param->setDefaultArg(Result.getAs<Expr>());
3286 
3287   return false;
3288 }
3289 
3290 bool
SubstBaseSpecifiers(CXXRecordDecl * Instantiation,CXXRecordDecl * Pattern,const MultiLevelTemplateArgumentList & TemplateArgs)3291 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
3292                           CXXRecordDecl *Pattern,
3293                           const MultiLevelTemplateArgumentList &TemplateArgs) {
3294   bool Invalid = false;
3295   SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3296   for (const auto &Base : Pattern->bases()) {
3297     if (!Base.getType()->isDependentType()) {
3298       if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3299         if (RD->isInvalidDecl())
3300           Instantiation->setInvalidDecl();
3301       }
3302       InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3303       continue;
3304     }
3305 
3306     SourceLocation EllipsisLoc;
3307     TypeSourceInfo *BaseTypeLoc;
3308     if (Base.isPackExpansion()) {
3309       // This is a pack expansion. See whether we should expand it now, or
3310       // wait until later.
3311       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3312       collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3313                                       Unexpanded);
3314       bool ShouldExpand = false;
3315       bool RetainExpansion = false;
3316       std::optional<unsigned> NumExpansions;
3317       if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3318                                           Base.getSourceRange(),
3319                                           Unexpanded,
3320                                           TemplateArgs, ShouldExpand,
3321                                           RetainExpansion,
3322                                           NumExpansions)) {
3323         Invalid = true;
3324         continue;
3325       }
3326 
3327       // If we should expand this pack expansion now, do so.
3328       if (ShouldExpand) {
3329         for (unsigned I = 0; I != *NumExpansions; ++I) {
3330             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3331 
3332           TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3333                                                   TemplateArgs,
3334                                               Base.getSourceRange().getBegin(),
3335                                                   DeclarationName());
3336           if (!BaseTypeLoc) {
3337             Invalid = true;
3338             continue;
3339           }
3340 
3341           if (CXXBaseSpecifier *InstantiatedBase
3342                 = CheckBaseSpecifier(Instantiation,
3343                                      Base.getSourceRange(),
3344                                      Base.isVirtual(),
3345                                      Base.getAccessSpecifierAsWritten(),
3346                                      BaseTypeLoc,
3347                                      SourceLocation()))
3348             InstantiatedBases.push_back(InstantiatedBase);
3349           else
3350             Invalid = true;
3351         }
3352 
3353         continue;
3354       }
3355 
3356       // The resulting base specifier will (still) be a pack expansion.
3357       EllipsisLoc = Base.getEllipsisLoc();
3358       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3359       BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3360                               TemplateArgs,
3361                               Base.getSourceRange().getBegin(),
3362                               DeclarationName());
3363     } else {
3364       BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3365                               TemplateArgs,
3366                               Base.getSourceRange().getBegin(),
3367                               DeclarationName());
3368     }
3369 
3370     if (!BaseTypeLoc) {
3371       Invalid = true;
3372       continue;
3373     }
3374 
3375     if (CXXBaseSpecifier *InstantiatedBase
3376           = CheckBaseSpecifier(Instantiation,
3377                                Base.getSourceRange(),
3378                                Base.isVirtual(),
3379                                Base.getAccessSpecifierAsWritten(),
3380                                BaseTypeLoc,
3381                                EllipsisLoc))
3382       InstantiatedBases.push_back(InstantiatedBase);
3383     else
3384       Invalid = true;
3385   }
3386 
3387   if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3388     Invalid = true;
3389 
3390   return Invalid;
3391 }
3392 
3393 // Defined via #include from SemaTemplateInstantiateDecl.cpp
3394 namespace clang {
3395   namespace sema {
3396     Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
3397                             const MultiLevelTemplateArgumentList &TemplateArgs);
3398     Attr *instantiateTemplateAttributeForDecl(
3399         const Attr *At, ASTContext &C, Sema &S,
3400         const MultiLevelTemplateArgumentList &TemplateArgs);
3401   }
3402 }
3403 
3404 bool
InstantiateClass(SourceLocation PointOfInstantiation,CXXRecordDecl * Instantiation,CXXRecordDecl * Pattern,const MultiLevelTemplateArgumentList & TemplateArgs,TemplateSpecializationKind TSK,bool Complain)3405 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3406                        CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3407                        const MultiLevelTemplateArgumentList &TemplateArgs,
3408                        TemplateSpecializationKind TSK,
3409                        bool Complain) {
3410   CXXRecordDecl *PatternDef
3411     = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3412   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3413                                 Instantiation->getInstantiatedFromMemberClass(),
3414                                      Pattern, PatternDef, TSK, Complain))
3415     return true;
3416 
3417   llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3418     llvm::TimeTraceMetadata M;
3419     llvm::raw_string_ostream OS(M.Detail);
3420     Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3421                                         /*Qualified=*/true);
3422     if (llvm::isTimeTraceVerbose()) {
3423       auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3424       M.File = SourceMgr.getFilename(Loc);
3425       M.Line = SourceMgr.getExpansionLineNumber(Loc);
3426     }
3427     return M;
3428   });
3429 
3430   Pattern = PatternDef;
3431 
3432   // Record the point of instantiation.
3433   if (MemberSpecializationInfo *MSInfo
3434         = Instantiation->getMemberSpecializationInfo()) {
3435     MSInfo->setTemplateSpecializationKind(TSK);
3436     MSInfo->setPointOfInstantiation(PointOfInstantiation);
3437   } else if (ClassTemplateSpecializationDecl *Spec
3438         = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3439     Spec->setTemplateSpecializationKind(TSK);
3440     Spec->setPointOfInstantiation(PointOfInstantiation);
3441   }
3442 
3443   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3444   if (Inst.isInvalid())
3445     return true;
3446   assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3447   PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3448                                       "instantiating class definition");
3449 
3450   // Enter the scope of this instantiation. We don't use
3451   // PushDeclContext because we don't have a scope.
3452   ContextRAII SavedContext(*this, Instantiation);
3453   EnterExpressionEvaluationContext EvalContext(
3454       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3455 
3456   // If this is an instantiation of a local class, merge this local
3457   // instantiation scope with the enclosing scope. Otherwise, every
3458   // instantiation of a class has its own local instantiation scope.
3459   bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3460   LocalInstantiationScope Scope(*this, MergeWithParentScope);
3461 
3462   // Some class state isn't processed immediately but delayed till class
3463   // instantiation completes. We may not be ready to handle any delayed state
3464   // already on the stack as it might correspond to a different class, so save
3465   // it now and put it back later.
3466   SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3467 
3468   // Pull attributes from the pattern onto the instantiation.
3469   InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3470 
3471   // Start the definition of this instantiation.
3472   Instantiation->startDefinition();
3473 
3474   // The instantiation is visible here, even if it was first declared in an
3475   // unimported module.
3476   Instantiation->setVisibleDespiteOwningModule();
3477 
3478   // FIXME: This loses the as-written tag kind for an explicit instantiation.
3479   Instantiation->setTagKind(Pattern->getTagKind());
3480 
3481   // Do substitution on the base class specifiers.
3482   if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3483     Instantiation->setInvalidDecl();
3484 
3485   TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3486   Instantiator.setEvaluateConstraints(false);
3487   SmallVector<Decl*, 4> Fields;
3488   // Delay instantiation of late parsed attributes.
3489   LateInstantiatedAttrVec LateAttrs;
3490   Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3491 
3492   bool MightHaveConstexprVirtualFunctions = false;
3493   for (auto *Member : Pattern->decls()) {
3494     // Don't instantiate members not belonging in this semantic context.
3495     // e.g. for:
3496     // @code
3497     //    template <int i> class A {
3498     //      class B *g;
3499     //    };
3500     // @endcode
3501     // 'class B' has the template as lexical context but semantically it is
3502     // introduced in namespace scope.
3503     if (Member->getDeclContext() != Pattern)
3504       continue;
3505 
3506     // BlockDecls can appear in a default-member-initializer. They must be the
3507     // child of a BlockExpr, so we only know how to instantiate them from there.
3508     // Similarly, lambda closure types are recreated when instantiating the
3509     // corresponding LambdaExpr.
3510     if (isa<BlockDecl>(Member) ||
3511         (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3512       continue;
3513 
3514     if (Member->isInvalidDecl()) {
3515       Instantiation->setInvalidDecl();
3516       continue;
3517     }
3518 
3519     Decl *NewMember = Instantiator.Visit(Member);
3520     if (NewMember) {
3521       if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3522         Fields.push_back(Field);
3523       } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3524         // C++11 [temp.inst]p1: The implicit instantiation of a class template
3525         // specialization causes the implicit instantiation of the definitions
3526         // of unscoped member enumerations.
3527         // Record a point of instantiation for this implicit instantiation.
3528         if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3529             Enum->isCompleteDefinition()) {
3530           MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3531           assert(MSInfo && "no spec info for member enum specialization");
3532           MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
3533           MSInfo->setPointOfInstantiation(PointOfInstantiation);
3534         }
3535       } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3536         if (SA->isFailed()) {
3537           // A static_assert failed. Bail out; instantiating this
3538           // class is probably not meaningful.
3539           Instantiation->setInvalidDecl();
3540           break;
3541         }
3542       } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3543         if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3544             (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3545           MightHaveConstexprVirtualFunctions = true;
3546       }
3547 
3548       if (NewMember->isInvalidDecl())
3549         Instantiation->setInvalidDecl();
3550     } else {
3551       // FIXME: Eventually, a NULL return will mean that one of the
3552       // instantiations was a semantic disaster, and we'll want to mark the
3553       // declaration invalid.
3554       // For now, we expect to skip some members that we can't yet handle.
3555     }
3556   }
3557 
3558   // Finish checking fields.
3559   ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3560               SourceLocation(), SourceLocation(), ParsedAttributesView());
3561   CheckCompletedCXXClass(nullptr, Instantiation);
3562 
3563   // Default arguments are parsed, if not instantiated. We can go instantiate
3564   // default arg exprs for default constructors if necessary now. Unless we're
3565   // parsing a class, in which case wait until that's finished.
3566   if (ParsingClassDepth == 0)
3567     ActOnFinishCXXNonNestedClass();
3568 
3569   // Instantiate late parsed attributes, and attach them to their decls.
3570   // See Sema::InstantiateAttrs
3571   for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3572        E = LateAttrs.end(); I != E; ++I) {
3573     assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3574     CurrentInstantiationScope = I->Scope;
3575 
3576     // Allow 'this' within late-parsed attributes.
3577     auto *ND = cast<NamedDecl>(I->NewDecl);
3578     auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3579     CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3580                                ND->isCXXInstanceMember());
3581 
3582     Attr *NewAttr =
3583       instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3584     if (NewAttr)
3585       I->NewDecl->addAttr(NewAttr);
3586     LocalInstantiationScope::deleteScopes(I->Scope,
3587                                           Instantiator.getStartingScope());
3588   }
3589   Instantiator.disableLateAttributeInstantiation();
3590   LateAttrs.clear();
3591 
3592   ActOnFinishDelayedMemberInitializers(Instantiation);
3593 
3594   // FIXME: We should do something similar for explicit instantiations so they
3595   // end up in the right module.
3596   if (TSK == TSK_ImplicitInstantiation) {
3597     Instantiation->setLocation(Pattern->getLocation());
3598     Instantiation->setLocStart(Pattern->getInnerLocStart());
3599     Instantiation->setBraceRange(Pattern->getBraceRange());
3600   }
3601 
3602   if (!Instantiation->isInvalidDecl()) {
3603     // Perform any dependent diagnostics from the pattern.
3604     if (Pattern->isDependentContext())
3605       PerformDependentDiagnostics(Pattern, TemplateArgs);
3606 
3607     // Instantiate any out-of-line class template partial
3608     // specializations now.
3609     for (TemplateDeclInstantiator::delayed_partial_spec_iterator
3610               P = Instantiator.delayed_partial_spec_begin(),
3611            PEnd = Instantiator.delayed_partial_spec_end();
3612          P != PEnd; ++P) {
3613       if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3614               P->first, P->second)) {
3615         Instantiation->setInvalidDecl();
3616         break;
3617       }
3618     }
3619 
3620     // Instantiate any out-of-line variable template partial
3621     // specializations now.
3622     for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
3623               P = Instantiator.delayed_var_partial_spec_begin(),
3624            PEnd = Instantiator.delayed_var_partial_spec_end();
3625          P != PEnd; ++P) {
3626       if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3627               P->first, P->second)) {
3628         Instantiation->setInvalidDecl();
3629         break;
3630       }
3631     }
3632   }
3633 
3634   // Exit the scope of this instantiation.
3635   SavedContext.pop();
3636 
3637   if (!Instantiation->isInvalidDecl()) {
3638     // Always emit the vtable for an explicit instantiation definition
3639     // of a polymorphic class template specialization. Otherwise, eagerly
3640     // instantiate only constexpr virtual functions in preparation for their use
3641     // in constant evaluation.
3642     if (TSK == TSK_ExplicitInstantiationDefinition)
3643       MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3644     else if (MightHaveConstexprVirtualFunctions)
3645       MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3646                                    /*ConstexprOnly*/ true);
3647   }
3648 
3649   Consumer.HandleTagDeclDefinition(Instantiation);
3650 
3651   return Instantiation->isInvalidDecl();
3652 }
3653 
InstantiateEnum(SourceLocation PointOfInstantiation,EnumDecl * Instantiation,EnumDecl * Pattern,const MultiLevelTemplateArgumentList & TemplateArgs,TemplateSpecializationKind TSK)3654 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3655                            EnumDecl *Instantiation, EnumDecl *Pattern,
3656                            const MultiLevelTemplateArgumentList &TemplateArgs,
3657                            TemplateSpecializationKind TSK) {
3658   EnumDecl *PatternDef = Pattern->getDefinition();
3659   if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3660                                  Instantiation->getInstantiatedFromMemberEnum(),
3661                                      Pattern, PatternDef, TSK,/*Complain*/true))
3662     return true;
3663   Pattern = PatternDef;
3664 
3665   // Record the point of instantiation.
3666   if (MemberSpecializationInfo *MSInfo
3667         = Instantiation->getMemberSpecializationInfo()) {
3668     MSInfo->setTemplateSpecializationKind(TSK);
3669     MSInfo->setPointOfInstantiation(PointOfInstantiation);
3670   }
3671 
3672   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3673   if (Inst.isInvalid())
3674     return true;
3675   if (Inst.isAlreadyInstantiating())
3676     return false;
3677   PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3678                                       "instantiating enum definition");
3679 
3680   // The instantiation is visible here, even if it was first declared in an
3681   // unimported module.
3682   Instantiation->setVisibleDespiteOwningModule();
3683 
3684   // Enter the scope of this instantiation. We don't use
3685   // PushDeclContext because we don't have a scope.
3686   ContextRAII SavedContext(*this, Instantiation);
3687   EnterExpressionEvaluationContext EvalContext(
3688       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3689 
3690   LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3691 
3692   // Pull attributes from the pattern onto the instantiation.
3693   InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3694 
3695   TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3696   Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3697 
3698   // Exit the scope of this instantiation.
3699   SavedContext.pop();
3700 
3701   return Instantiation->isInvalidDecl();
3702 }
3703 
InstantiateInClassInitializer(SourceLocation PointOfInstantiation,FieldDecl * Instantiation,FieldDecl * Pattern,const MultiLevelTemplateArgumentList & TemplateArgs)3704 bool Sema::InstantiateInClassInitializer(
3705     SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3706     FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3707   // If there is no initializer, we don't need to do anything.
3708   if (!Pattern->hasInClassInitializer())
3709     return false;
3710 
3711   assert(Instantiation->getInClassInitStyle() ==
3712              Pattern->getInClassInitStyle() &&
3713          "pattern and instantiation disagree about init style");
3714 
3715   // Error out if we haven't parsed the initializer of the pattern yet because
3716   // we are waiting for the closing brace of the outer class.
3717   Expr *OldInit = Pattern->getInClassInitializer();
3718   if (!OldInit) {
3719     RecordDecl *PatternRD = Pattern->getParent();
3720     RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3721     Diag(PointOfInstantiation,
3722          diag::err_default_member_initializer_not_yet_parsed)
3723         << OutermostClass << Pattern;
3724     Diag(Pattern->getEndLoc(),
3725          diag::note_default_member_initializer_not_yet_parsed);
3726     Instantiation->setInvalidDecl();
3727     return true;
3728   }
3729 
3730   InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3731   if (Inst.isInvalid())
3732     return true;
3733   if (Inst.isAlreadyInstantiating()) {
3734     // Error out if we hit an instantiation cycle for this initializer.
3735     Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3736       << Instantiation;
3737     return true;
3738   }
3739   PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3740                                       "instantiating default member init");
3741 
3742   // Enter the scope of this instantiation. We don't use PushDeclContext because
3743   // we don't have a scope.
3744   ContextRAII SavedContext(*this, Instantiation->getParent());
3745   EnterExpressionEvaluationContext EvalContext(
3746       *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3747   ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3748       PointOfInstantiation, Instantiation, CurContext};
3749 
3750   LocalInstantiationScope Scope(*this, true);
3751 
3752   // Instantiate the initializer.
3753   ActOnStartCXXInClassMemberInitializer();
3754   CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3755 
3756   ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3757                                         /*CXXDirectInit=*/false);
3758   Expr *Init = NewInit.get();
3759   assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3760   ActOnFinishCXXInClassMemberInitializer(
3761       Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3762 
3763   if (auto *L = getASTMutationListener())
3764     L->DefaultMemberInitializerInstantiated(Instantiation);
3765 
3766   // Return true if the in-class initializer is still missing.
3767   return !Instantiation->getInClassInitializer();
3768 }
3769 
3770 namespace {
3771   /// A partial specialization whose template arguments have matched
3772   /// a given template-id.
3773   struct PartialSpecMatchResult {
3774     ClassTemplatePartialSpecializationDecl *Partial;
3775     TemplateArgumentList *Args;
3776   };
3777 }
3778 
usesPartialOrExplicitSpecialization(SourceLocation Loc,ClassTemplateSpecializationDecl * ClassTemplateSpec)3779 bool Sema::usesPartialOrExplicitSpecialization(
3780     SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3781   if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3782       TSK_ExplicitSpecialization)
3783     return true;
3784 
3785   SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3786   ClassTemplateSpec->getSpecializedTemplate()
3787                    ->getPartialSpecializations(PartialSpecs);
3788   for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3789     TemplateDeductionInfo Info(Loc);
3790     if (DeduceTemplateArguments(PartialSpecs[I],
3791                                 ClassTemplateSpec->getTemplateArgs().asArray(),
3792                                 Info) == TemplateDeductionResult::Success)
3793       return true;
3794   }
3795 
3796   return false;
3797 }
3798 
3799 /// Get the instantiation pattern to use to instantiate the definition of a
3800 /// given ClassTemplateSpecializationDecl (either the pattern of the primary
3801 /// template or of a partial specialization).
3802 static ActionResult<CXXRecordDecl *>
getPatternForClassTemplateSpecialization(Sema & S,SourceLocation PointOfInstantiation,ClassTemplateSpecializationDecl * ClassTemplateSpec,TemplateSpecializationKind TSK)3803 getPatternForClassTemplateSpecialization(
3804     Sema &S, SourceLocation PointOfInstantiation,
3805     ClassTemplateSpecializationDecl *ClassTemplateSpec,
3806     TemplateSpecializationKind TSK) {
3807   Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3808   if (Inst.isInvalid())
3809     return {/*Invalid=*/true};
3810   if (Inst.isAlreadyInstantiating())
3811     return {/*Invalid=*/false};
3812 
3813   llvm::PointerUnion<ClassTemplateDecl *,
3814                      ClassTemplatePartialSpecializationDecl *>
3815       Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3816   if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3817     // Find best matching specialization.
3818     ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3819 
3820     // C++ [temp.class.spec.match]p1:
3821     //   When a class template is used in a context that requires an
3822     //   instantiation of the class, it is necessary to determine
3823     //   whether the instantiation is to be generated using the primary
3824     //   template or one of the partial specializations. This is done by
3825     //   matching the template arguments of the class template
3826     //   specialization with the template argument lists of the partial
3827     //   specializations.
3828     typedef PartialSpecMatchResult MatchResult;
3829     SmallVector<MatchResult, 4> Matched;
3830     SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3831     Template->getPartialSpecializations(PartialSpecs);
3832     TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3833     for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3834       ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3835       TemplateDeductionInfo Info(FailedCandidates.getLocation());
3836       if (TemplateDeductionResult Result = S.DeduceTemplateArguments(
3837               Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3838           Result != TemplateDeductionResult::Success) {
3839         // Store the failed-deduction information for use in diagnostics, later.
3840         // TODO: Actually use the failed-deduction info?
3841         FailedCandidates.addCandidate().set(
3842             DeclAccessPair::make(Template, AS_public), Partial,
3843             MakeDeductionFailureInfo(S.Context, Result, Info));
3844         (void)Result;
3845       } else {
3846         Matched.push_back(PartialSpecMatchResult());
3847         Matched.back().Partial = Partial;
3848         Matched.back().Args = Info.takeCanonical();
3849       }
3850     }
3851 
3852     // If we're dealing with a member template where the template parameters
3853     // have been instantiated, this provides the original template parameters
3854     // from which the member template's parameters were instantiated.
3855 
3856     if (Matched.size() >= 1) {
3857       SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3858       if (Matched.size() == 1) {
3859         //   -- If exactly one matching specialization is found, the
3860         //      instantiation is generated from that specialization.
3861         // We don't need to do anything for this.
3862       } else {
3863         //   -- If more than one matching specialization is found, the
3864         //      partial order rules (14.5.4.2) are used to determine
3865         //      whether one of the specializations is more specialized
3866         //      than the others. If none of the specializations is more
3867         //      specialized than all of the other matching
3868         //      specializations, then the use of the class template is
3869         //      ambiguous and the program is ill-formed.
3870         for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
3871                                                  PEnd = Matched.end();
3872              P != PEnd; ++P) {
3873           if (S.getMoreSpecializedPartialSpecialization(
3874                   P->Partial, Best->Partial, PointOfInstantiation) ==
3875               P->Partial)
3876             Best = P;
3877         }
3878 
3879         // Determine if the best partial specialization is more specialized than
3880         // the others.
3881         bool Ambiguous = false;
3882         for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3883                                                  PEnd = Matched.end();
3884              P != PEnd; ++P) {
3885           if (P != Best && S.getMoreSpecializedPartialSpecialization(
3886                                P->Partial, Best->Partial,
3887                                PointOfInstantiation) != Best->Partial) {
3888             Ambiguous = true;
3889             break;
3890           }
3891         }
3892 
3893         if (Ambiguous) {
3894           // Partial ordering did not produce a clear winner. Complain.
3895           Inst.Clear();
3896           ClassTemplateSpec->setInvalidDecl();
3897           S.Diag(PointOfInstantiation,
3898                  diag::err_partial_spec_ordering_ambiguous)
3899               << ClassTemplateSpec;
3900 
3901           // Print the matching partial specializations.
3902           for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3903                                                    PEnd = Matched.end();
3904                P != PEnd; ++P)
3905             S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3906                 << S.getTemplateArgumentBindingsText(
3907                        P->Partial->getTemplateParameters(), *P->Args);
3908 
3909           return {/*Invalid=*/true};
3910         }
3911       }
3912 
3913       ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3914     } else {
3915       //   -- If no matches are found, the instantiation is generated
3916       //      from the primary template.
3917     }
3918   }
3919 
3920   CXXRecordDecl *Pattern = nullptr;
3921   Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3922   if (auto *PartialSpec =
3923           Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3924     // Instantiate using the best class template partial specialization.
3925     while (PartialSpec->getInstantiatedFromMember()) {
3926       // If we've found an explicit specialization of this class template,
3927       // stop here and use that as the pattern.
3928       if (PartialSpec->isMemberSpecialization())
3929         break;
3930 
3931       PartialSpec = PartialSpec->getInstantiatedFromMember();
3932     }
3933     Pattern = PartialSpec;
3934   } else {
3935     ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3936     while (Template->getInstantiatedFromMemberTemplate()) {
3937       // If we've found an explicit specialization of this class template,
3938       // stop here and use that as the pattern.
3939       if (Template->isMemberSpecialization())
3940         break;
3941 
3942       Template = Template->getInstantiatedFromMemberTemplate();
3943     }
3944     Pattern = Template->getTemplatedDecl();
3945   }
3946 
3947   return Pattern;
3948 }
3949 
InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,ClassTemplateSpecializationDecl * ClassTemplateSpec,TemplateSpecializationKind TSK,bool Complain)3950 bool Sema::InstantiateClassTemplateSpecialization(
3951     SourceLocation PointOfInstantiation,
3952     ClassTemplateSpecializationDecl *ClassTemplateSpec,
3953     TemplateSpecializationKind TSK, bool Complain) {
3954   // Perform the actual instantiation on the canonical declaration.
3955   ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3956       ClassTemplateSpec->getCanonicalDecl());
3957   if (ClassTemplateSpec->isInvalidDecl())
3958     return true;
3959 
3960   ActionResult<CXXRecordDecl *> Pattern =
3961       getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
3962                                                ClassTemplateSpec, TSK);
3963   if (!Pattern.isUsable())
3964     return Pattern.isInvalid();
3965 
3966   return InstantiateClass(
3967       PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
3968       getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
3969 }
3970 
3971 void
InstantiateClassMembers(SourceLocation PointOfInstantiation,CXXRecordDecl * Instantiation,const MultiLevelTemplateArgumentList & TemplateArgs,TemplateSpecializationKind TSK)3972 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
3973                               CXXRecordDecl *Instantiation,
3974                         const MultiLevelTemplateArgumentList &TemplateArgs,
3975                               TemplateSpecializationKind TSK) {
3976   // FIXME: We need to notify the ASTMutationListener that we did all of these
3977   // things, in case we have an explicit instantiation definition in a PCM, a
3978   // module, or preamble, and the declaration is in an imported AST.
3979   assert(
3980       (TSK == TSK_ExplicitInstantiationDefinition ||
3981        TSK == TSK_ExplicitInstantiationDeclaration ||
3982        (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
3983       "Unexpected template specialization kind!");
3984   for (auto *D : Instantiation->decls()) {
3985     bool SuppressNew = false;
3986     if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3987       if (FunctionDecl *Pattern =
3988               Function->getInstantiatedFromMemberFunction()) {
3989 
3990         if (Function->isIneligibleOrNotSelected())
3991           continue;
3992 
3993         if (Function->getTrailingRequiresClause()) {
3994           ConstraintSatisfaction Satisfaction;
3995           if (CheckFunctionConstraints(Function, Satisfaction) ||
3996               !Satisfaction.IsSatisfied) {
3997             continue;
3998           }
3999         }
4000 
4001         if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4002           continue;
4003 
4004         MemberSpecializationInfo *MSInfo =
4005             Function->getMemberSpecializationInfo();
4006         assert(MSInfo && "No member specialization information?");
4007         if (MSInfo->getTemplateSpecializationKind()
4008                                                  == TSK_ExplicitSpecialization)
4009           continue;
4010 
4011         if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4012                                                    Function,
4013                                         MSInfo->getTemplateSpecializationKind(),
4014                                               MSInfo->getPointOfInstantiation(),
4015                                                    SuppressNew) ||
4016             SuppressNew)
4017           continue;
4018 
4019         // C++11 [temp.explicit]p8:
4020         //   An explicit instantiation definition that names a class template
4021         //   specialization explicitly instantiates the class template
4022         //   specialization and is only an explicit instantiation definition
4023         //   of members whose definition is visible at the point of
4024         //   instantiation.
4025         if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4026           continue;
4027 
4028         Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4029 
4030         if (Function->isDefined()) {
4031           // Let the ASTConsumer know that this function has been explicitly
4032           // instantiated now, and its linkage might have changed.
4033           Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
4034         } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4035           InstantiateFunctionDefinition(PointOfInstantiation, Function);
4036         } else if (TSK == TSK_ImplicitInstantiation) {
4037           PendingLocalImplicitInstantiations.push_back(
4038               std::make_pair(Function, PointOfInstantiation));
4039         }
4040       }
4041     } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4042       if (isa<VarTemplateSpecializationDecl>(Var))
4043         continue;
4044 
4045       if (Var->isStaticDataMember()) {
4046         if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4047           continue;
4048 
4049         MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4050         assert(MSInfo && "No member specialization information?");
4051         if (MSInfo->getTemplateSpecializationKind()
4052                                                  == TSK_ExplicitSpecialization)
4053           continue;
4054 
4055         if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4056                                                    Var,
4057                                         MSInfo->getTemplateSpecializationKind(),
4058                                               MSInfo->getPointOfInstantiation(),
4059                                                    SuppressNew) ||
4060             SuppressNew)
4061           continue;
4062 
4063         if (TSK == TSK_ExplicitInstantiationDefinition) {
4064           // C++0x [temp.explicit]p8:
4065           //   An explicit instantiation definition that names a class template
4066           //   specialization explicitly instantiates the class template
4067           //   specialization and is only an explicit instantiation definition
4068           //   of members whose definition is visible at the point of
4069           //   instantiation.
4070           if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
4071             continue;
4072 
4073           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4074           InstantiateVariableDefinition(PointOfInstantiation, Var);
4075         } else {
4076           Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4077         }
4078       }
4079     } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4080       if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4081         continue;
4082 
4083       // Always skip the injected-class-name, along with any
4084       // redeclarations of nested classes, since both would cause us
4085       // to try to instantiate the members of a class twice.
4086       // Skip closure types; they'll get instantiated when we instantiate
4087       // the corresponding lambda-expression.
4088       if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4089           Record->isLambda())
4090         continue;
4091 
4092       MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4093       assert(MSInfo && "No member specialization information?");
4094 
4095       if (MSInfo->getTemplateSpecializationKind()
4096                                                 == TSK_ExplicitSpecialization)
4097         continue;
4098 
4099       if (Context.getTargetInfo().getTriple().isOSWindows() &&
4100           TSK == TSK_ExplicitInstantiationDeclaration) {
4101         // On Windows, explicit instantiation decl of the outer class doesn't
4102         // affect the inner class. Typically extern template declarations are
4103         // used in combination with dll import/export annotations, but those
4104         // are not propagated from the outer class templates to inner classes.
4105         // Therefore, do not instantiate inner classes on this platform, so
4106         // that users don't end up with undefined symbols during linking.
4107         continue;
4108       }
4109 
4110       if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4111                                                  Record,
4112                                         MSInfo->getTemplateSpecializationKind(),
4113                                               MSInfo->getPointOfInstantiation(),
4114                                                  SuppressNew) ||
4115           SuppressNew)
4116         continue;
4117 
4118       CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4119       assert(Pattern && "Missing instantiated-from-template information");
4120 
4121       if (!Record->getDefinition()) {
4122         if (!Pattern->getDefinition()) {
4123           // C++0x [temp.explicit]p8:
4124           //   An explicit instantiation definition that names a class template
4125           //   specialization explicitly instantiates the class template
4126           //   specialization and is only an explicit instantiation definition
4127           //   of members whose definition is visible at the point of
4128           //   instantiation.
4129           if (TSK == TSK_ExplicitInstantiationDeclaration) {
4130             MSInfo->setTemplateSpecializationKind(TSK);
4131             MSInfo->setPointOfInstantiation(PointOfInstantiation);
4132           }
4133 
4134           continue;
4135         }
4136 
4137         InstantiateClass(PointOfInstantiation, Record, Pattern,
4138                          TemplateArgs,
4139                          TSK);
4140       } else {
4141         if (TSK == TSK_ExplicitInstantiationDefinition &&
4142             Record->getTemplateSpecializationKind() ==
4143                 TSK_ExplicitInstantiationDeclaration) {
4144           Record->setTemplateSpecializationKind(TSK);
4145           MarkVTableUsed(PointOfInstantiation, Record, true);
4146         }
4147       }
4148 
4149       Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4150       if (Pattern)
4151         InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4152                                 TSK);
4153     } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4154       MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4155       assert(MSInfo && "No member specialization information?");
4156 
4157       if (MSInfo->getTemplateSpecializationKind()
4158             == TSK_ExplicitSpecialization)
4159         continue;
4160 
4161       if (CheckSpecializationInstantiationRedecl(
4162             PointOfInstantiation, TSK, Enum,
4163             MSInfo->getTemplateSpecializationKind(),
4164             MSInfo->getPointOfInstantiation(), SuppressNew) ||
4165           SuppressNew)
4166         continue;
4167 
4168       if (Enum->getDefinition())
4169         continue;
4170 
4171       EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4172       assert(Pattern && "Missing instantiated-from-template information");
4173 
4174       if (TSK == TSK_ExplicitInstantiationDefinition) {
4175         if (!Pattern->getDefinition())
4176           continue;
4177 
4178         InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4179       } else {
4180         MSInfo->setTemplateSpecializationKind(TSK);
4181         MSInfo->setPointOfInstantiation(PointOfInstantiation);
4182       }
4183     } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4184       // No need to instantiate in-class initializers during explicit
4185       // instantiation.
4186       if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4187         CXXRecordDecl *ClassPattern =
4188             Instantiation->getTemplateInstantiationPattern();
4189         DeclContext::lookup_result Lookup =
4190             ClassPattern->lookup(Field->getDeclName());
4191         FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4192         assert(Pattern);
4193         InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4194                                       TemplateArgs);
4195       }
4196     }
4197   }
4198 }
4199 
4200 void
InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation,ClassTemplateSpecializationDecl * ClassTemplateSpec,TemplateSpecializationKind TSK)4201 Sema::InstantiateClassTemplateSpecializationMembers(
4202                                            SourceLocation PointOfInstantiation,
4203                             ClassTemplateSpecializationDecl *ClassTemplateSpec,
4204                                                TemplateSpecializationKind TSK) {
4205   // C++0x [temp.explicit]p7:
4206   //   An explicit instantiation that names a class template
4207   //   specialization is an explicit instantion of the same kind
4208   //   (declaration or definition) of each of its members (not
4209   //   including members inherited from base classes) that has not
4210   //   been previously explicitly specialized in the translation unit
4211   //   containing the explicit instantiation, except as described
4212   //   below.
4213   InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4214                           getTemplateInstantiationArgs(ClassTemplateSpec),
4215                           TSK);
4216 }
4217 
4218 StmtResult
SubstStmt(Stmt * S,const MultiLevelTemplateArgumentList & TemplateArgs)4219 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
4220   if (!S)
4221     return S;
4222 
4223   TemplateInstantiator Instantiator(*this, TemplateArgs,
4224                                     SourceLocation(),
4225                                     DeclarationName());
4226   return Instantiator.TransformStmt(S);
4227 }
4228 
SubstTemplateArgument(const TemplateArgumentLoc & Input,const MultiLevelTemplateArgumentList & TemplateArgs,TemplateArgumentLoc & Output,SourceLocation Loc,const DeclarationName & Entity)4229 bool Sema::SubstTemplateArgument(
4230     const TemplateArgumentLoc &Input,
4231     const MultiLevelTemplateArgumentList &TemplateArgs,
4232     TemplateArgumentLoc &Output, SourceLocation Loc,
4233     const DeclarationName &Entity) {
4234   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4235   return Instantiator.TransformTemplateArgument(Input, Output);
4236 }
4237 
SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,const MultiLevelTemplateArgumentList & TemplateArgs,TemplateArgumentListInfo & Out)4238 bool Sema::SubstTemplateArguments(
4239     ArrayRef<TemplateArgumentLoc> Args,
4240     const MultiLevelTemplateArgumentList &TemplateArgs,
4241     TemplateArgumentListInfo &Out) {
4242   TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4243                                     DeclarationName());
4244   return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4245 }
4246 
4247 ExprResult
SubstExpr(Expr * E,const MultiLevelTemplateArgumentList & TemplateArgs)4248 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4249   if (!E)
4250     return E;
4251 
4252   TemplateInstantiator Instantiator(*this, TemplateArgs,
4253                                     SourceLocation(),
4254                                     DeclarationName());
4255   return Instantiator.TransformExpr(E);
4256 }
4257 
4258 ExprResult
SubstConstraintExpr(Expr * E,const MultiLevelTemplateArgumentList & TemplateArgs)4259 Sema::SubstConstraintExpr(Expr *E,
4260                           const MultiLevelTemplateArgumentList &TemplateArgs) {
4261   // FIXME: should call SubstExpr directly if this function is equivalent or
4262   //        should it be different?
4263   return SubstExpr(E, TemplateArgs);
4264 }
4265 
SubstConstraintExprWithoutSatisfaction(Expr * E,const MultiLevelTemplateArgumentList & TemplateArgs)4266 ExprResult Sema::SubstConstraintExprWithoutSatisfaction(
4267     Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4268   if (!E)
4269     return E;
4270 
4271   TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4272                                     DeclarationName());
4273   Instantiator.setEvaluateConstraints(false);
4274   return Instantiator.TransformExpr(E);
4275 }
4276 
SubstInitializer(Expr * Init,const MultiLevelTemplateArgumentList & TemplateArgs,bool CXXDirectInit)4277 ExprResult Sema::SubstInitializer(Expr *Init,
4278                           const MultiLevelTemplateArgumentList &TemplateArgs,
4279                           bool CXXDirectInit) {
4280   TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4281                                     DeclarationName());
4282   return Instantiator.TransformInitializer(Init, CXXDirectInit);
4283 }
4284 
SubstExprs(ArrayRef<Expr * > Exprs,bool IsCall,const MultiLevelTemplateArgumentList & TemplateArgs,SmallVectorImpl<Expr * > & Outputs)4285 bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4286                       const MultiLevelTemplateArgumentList &TemplateArgs,
4287                       SmallVectorImpl<Expr *> &Outputs) {
4288   if (Exprs.empty())
4289     return false;
4290 
4291   TemplateInstantiator Instantiator(*this, TemplateArgs,
4292                                     SourceLocation(),
4293                                     DeclarationName());
4294   return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4295                                      IsCall, Outputs);
4296 }
4297 
4298 NestedNameSpecifierLoc
SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,const MultiLevelTemplateArgumentList & TemplateArgs)4299 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
4300                         const MultiLevelTemplateArgumentList &TemplateArgs) {
4301   if (!NNS)
4302     return NestedNameSpecifierLoc();
4303 
4304   TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4305                                     DeclarationName());
4306   return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4307 }
4308 
4309 DeclarationNameInfo
SubstDeclarationNameInfo(const DeclarationNameInfo & NameInfo,const MultiLevelTemplateArgumentList & TemplateArgs)4310 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
4311                          const MultiLevelTemplateArgumentList &TemplateArgs) {
4312   TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4313                                     NameInfo.getName());
4314   return Instantiator.TransformDeclarationNameInfo(NameInfo);
4315 }
4316 
4317 TemplateName
SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,TemplateName Name,SourceLocation Loc,const MultiLevelTemplateArgumentList & TemplateArgs)4318 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
4319                         TemplateName Name, SourceLocation Loc,
4320                         const MultiLevelTemplateArgumentList &TemplateArgs) {
4321   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4322                                     DeclarationName());
4323   CXXScopeSpec SS;
4324   SS.Adopt(QualifierLoc);
4325   return Instantiator.TransformTemplateName(SS, Name, Loc);
4326 }
4327 
getCanonicalParmVarDecl(const Decl * D)4328 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4329   // When storing ParmVarDecls in the local instantiation scope, we always
4330   // want to use the ParmVarDecl from the canonical function declaration,
4331   // since the map is then valid for any redeclaration or definition of that
4332   // function.
4333   if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4334     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4335       unsigned i = PV->getFunctionScopeIndex();
4336       // This parameter might be from a freestanding function type within the
4337       // function and isn't necessarily referring to one of FD's parameters.
4338       if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4339         return FD->getCanonicalDecl()->getParamDecl(i);
4340     }
4341   }
4342   return D;
4343 }
4344 
4345 
4346 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
findInstantiationOf(const Decl * D)4347 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
4348   D = getCanonicalParmVarDecl(D);
4349   for (LocalInstantiationScope *Current = this; Current;
4350        Current = Current->Outer) {
4351 
4352     // Check if we found something within this scope.
4353     const Decl *CheckD = D;
4354     do {
4355       LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4356       if (Found != Current->LocalDecls.end())
4357         return &Found->second;
4358 
4359       // If this is a tag declaration, it's possible that we need to look for
4360       // a previous declaration.
4361       if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4362         CheckD = Tag->getPreviousDecl();
4363       else
4364         CheckD = nullptr;
4365     } while (CheckD);
4366 
4367     // If we aren't combined with our outer scope, we're done.
4368     if (!Current->CombineWithOuterScope)
4369       break;
4370   }
4371 
4372   // If we're performing a partial substitution during template argument
4373   // deduction, we may not have values for template parameters yet.
4374   if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4375       isa<TemplateTemplateParmDecl>(D))
4376     return nullptr;
4377 
4378   // Local types referenced prior to definition may require instantiation.
4379   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4380     if (RD->isLocalClass())
4381       return nullptr;
4382 
4383   // Enumeration types referenced prior to definition may appear as a result of
4384   // error recovery.
4385   if (isa<EnumDecl>(D))
4386     return nullptr;
4387 
4388   // Materialized typedefs/type alias for implicit deduction guides may require
4389   // instantiation.
4390   if (isa<TypedefNameDecl>(D) &&
4391       isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4392     return nullptr;
4393 
4394   // If we didn't find the decl, then we either have a sema bug, or we have a
4395   // forward reference to a label declaration.  Return null to indicate that
4396   // we have an uninstantiated label.
4397   assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4398   return nullptr;
4399 }
4400 
InstantiatedLocal(const Decl * D,Decl * Inst)4401 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
4402   D = getCanonicalParmVarDecl(D);
4403   llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4404   if (Stored.isNull()) {
4405 #ifndef NDEBUG
4406     // It should not be present in any surrounding scope either.
4407     LocalInstantiationScope *Current = this;
4408     while (Current->CombineWithOuterScope && Current->Outer) {
4409       Current = Current->Outer;
4410       assert(!Current->LocalDecls.contains(D) &&
4411              "Instantiated local in inner and outer scopes");
4412     }
4413 #endif
4414     Stored = Inst;
4415   } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4416     Pack->push_back(cast<VarDecl>(Inst));
4417   } else {
4418     assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
4419   }
4420 }
4421 
InstantiatedLocalPackArg(const Decl * D,VarDecl * Inst)4422 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
4423                                                        VarDecl *Inst) {
4424   D = getCanonicalParmVarDecl(D);
4425   DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4426   Pack->push_back(Inst);
4427 }
4428 
MakeInstantiatedLocalArgPack(const Decl * D)4429 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
4430 #ifndef NDEBUG
4431   // This should be the first time we've been told about this decl.
4432   for (LocalInstantiationScope *Current = this;
4433        Current && Current->CombineWithOuterScope; Current = Current->Outer)
4434     assert(!Current->LocalDecls.contains(D) &&
4435            "Creating local pack after instantiation of local");
4436 #endif
4437 
4438   D = getCanonicalParmVarDecl(D);
4439   llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4440   DeclArgumentPack *Pack = new DeclArgumentPack;
4441   Stored = Pack;
4442   ArgumentPacks.push_back(Pack);
4443 }
4444 
isLocalPackExpansion(const Decl * D)4445 bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {
4446   for (DeclArgumentPack *Pack : ArgumentPacks)
4447     if (llvm::is_contained(*Pack, D))
4448       return true;
4449   return false;
4450 }
4451 
SetPartiallySubstitutedPack(NamedDecl * Pack,const TemplateArgument * ExplicitArgs,unsigned NumExplicitArgs)4452 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
4453                                           const TemplateArgument *ExplicitArgs,
4454                                                     unsigned NumExplicitArgs) {
4455   assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4456          "Already have a partially-substituted pack");
4457   assert((!PartiallySubstitutedPack
4458           || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4459          "Wrong number of arguments in partially-substituted pack");
4460   PartiallySubstitutedPack = Pack;
4461   ArgsInPartiallySubstitutedPack = ExplicitArgs;
4462   NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4463 }
4464 
getPartiallySubstitutedPack(const TemplateArgument ** ExplicitArgs,unsigned * NumExplicitArgs) const4465 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
4466                                          const TemplateArgument **ExplicitArgs,
4467                                               unsigned *NumExplicitArgs) const {
4468   if (ExplicitArgs)
4469     *ExplicitArgs = nullptr;
4470   if (NumExplicitArgs)
4471     *NumExplicitArgs = 0;
4472 
4473   for (const LocalInstantiationScope *Current = this; Current;
4474        Current = Current->Outer) {
4475     if (Current->PartiallySubstitutedPack) {
4476       if (ExplicitArgs)
4477         *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4478       if (NumExplicitArgs)
4479         *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4480 
4481       return Current->PartiallySubstitutedPack;
4482     }
4483 
4484     if (!Current->CombineWithOuterScope)
4485       break;
4486   }
4487 
4488   return nullptr;
4489 }
4490