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