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