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