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