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