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