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