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