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