blob: 42344e487ce514f8fad619d95c24c06df43833fc [file] [log] [blame]
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001//===------- 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
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregord6ff3322009-08-04 16:50:30 +000014#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
Faisal Vali2cba1332013-10-23 06:44:28 +000017#include "clang/AST/ASTLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/Basic/LangOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000022#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000023#include "clang/Sema/Lookup.h"
John McCallde6836a2010-08-24 07:21:54 +000024#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000025#include "clang/Sema/TemplateDeduction.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000026
27using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000028using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000029
Douglas Gregor4ea568f2009-03-10 18:03:33 +000030//===----------------------------------------------------------------------===/
31// Template Instantiation Support
32//===----------------------------------------------------------------------===/
33
Douglas Gregor01afeef2009-08-28 20:31:08 +000034/// \brief Retrieve the template argument list(s) that should be used to
35/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000036///
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.
Douglas Gregor8c702532010-02-05 07:33:43 +000041///
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.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000046///
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.
Douglas Gregora654dd82009-08-28 17:37:35 +000051MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000052Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000053 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000054 bool RelativeToPrimary,
55 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000056 // Accumulate the set of template argument lists in this structure.
57 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000059 if (Innermost)
60 Result.addOuterTemplateArguments(Innermost);
61
Douglas Gregora654dd82009-08-28 17:37:35 +000062 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000063 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000064 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000065
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?");
Richard Smithbeef3452014-01-16 23:39:20 +000079 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 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000091 }
92
Douglas Gregor55462622011-06-15 14:20:42 +000093 // 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)
Richard Smith841d8b22013-05-17 03:04:50 +0000103 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000104 return Result;
105 }
106 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000107 }
108
John McCall970d5302009-08-29 03:16:09 +0000109 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000110 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +0000111 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +0000112 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
113 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000114 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
115 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000116 break;
Mike Stump11289f42009-09-09 15:08:12 +0000117
Douglas Gregora654dd82009-08-28 17:37:35 +0000118 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000119
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;
Mike Stump11289f42009-09-09 15:08:12 +0000125 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000126 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000127 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000128 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000129 (Function->getTemplateSpecializationKind() ==
130 TSK_ExplicitSpecialization &&
131 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000132 break;
133
Douglas Gregora654dd82009-08-28 17:37:35 +0000134 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000135 = Function->getTemplateSpecializationArgs()) {
136 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000137 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000138
Douglas Gregorcf915552009-10-13 16:30:37 +0000139 // 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;
Faisal Vali2cba1332013-10-23 06:44:28 +0000144
145 // If this function is a generic lambda specialization, we are done.
146 if (isGenericLambdaCallOperatorSpecialization(Function))
147 break;
148
Douglas Gregor43669f82011-03-05 17:54:25 +0000149 } else if (FunctionTemplateDecl *FunTmpl
150 = Function->getDescribedFunctionTemplate()) {
151 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000152 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000153 }
154
John McCall970d5302009-08-29 03:16:09 +0000155 // If this is a friend declaration and it declares an entity at
156 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000157 // instead of its semantic parent, unless of course the pattern we're
158 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000159 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000160 Function->getDeclContext()->isFileContext() &&
161 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000162 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000163 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000164 continue;
165 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000166 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
167 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
168 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000169 const TemplateSpecializationType *TST =
170 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
171 Result.addOuterTemplateArguments(
172 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000173 if (ClassTemplate->isMemberSpecialization())
174 break;
175 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000176 }
John McCall970d5302009-08-29 03:16:09 +0000177
178 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000179 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000180 }
Mike Stump11289f42009-09-09 15:08:12 +0000181
Douglas Gregora654dd82009-08-28 17:37:35 +0000182 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000183}
184
Douglas Gregor84d49a22009-11-11 21:54:23 +0000185bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
186 switch (Kind) {
187 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000188 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000189 case DefaultTemplateArgumentInstantiation:
190 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000191 case ExplicitTemplateArgumentSubstitution:
192 case DeducedTemplateArgumentSubstitution:
193 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000194 return true;
195
Douglas Gregor84d49a22009-11-11 21:54:23 +0000196 case DefaultTemplateArgumentChecking:
197 return false;
198 }
David Blaikie8a40f702012-01-17 06:56:22 +0000199
200 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000201}
202
Benjamin Kramer7761a042015-03-06 16:36:50 +0000203Sema::InstantiatingTemplate::InstantiatingTemplate(
204 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000205 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
206 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000207 sema::TemplateDeductionInfo *DeductionInfo)
208 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
209 SemaRef.InNonInstantiationSFINAEContext) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000210 // 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 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000216 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
Benjamin Kramer7761a042015-03-06 16:36:50 +0000234Sema::InstantiatingTemplate::InstantiatingTemplate(
235 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
236 SourceRange InstantiationRange)
237 : InstantiatingTemplate(SemaRef,
238 ActiveTemplateInstantiation::TemplateInstantiation,
239 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000240
Benjamin Kramer7761a042015-03-06 16:36:50 +0000241Sema::InstantiatingTemplate::InstantiatingTemplate(
242 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
243 ExceptionSpecification, SourceRange InstantiationRange)
244 : InstantiatingTemplate(
245 SemaRef, ActiveTemplateInstantiation::ExceptionSpecInstantiation,
246 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000247
Benjamin Kramer7761a042015-03-06 16:36:50 +0000248Sema::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) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000256
Benjamin Kramer7761a042015-03-06 16:36:50 +0000257Sema::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) {}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000266
Benjamin Kramer7761a042015-03-06 16:36:50 +0000267Sema::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) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000277
Larisse Voufo39a1e502013-08-06 01:03:05 +0000278Sema::InstantiatingTemplate::InstantiatingTemplate(
279 Sema &SemaRef, SourceLocation PointOfInstantiation,
280 VarTemplatePartialSpecializationDecl *PartialSpec,
281 ArrayRef<TemplateArgument> TemplateArgs,
282 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000283 : InstantiatingTemplate(
284 SemaRef,
285 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
286 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
287 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000288
Benjamin Kramer7761a042015-03-06 16:36:50 +0000289Sema::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) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000297
Benjamin Kramer7761a042015-03-06 16:36:50 +0000298Sema::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) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000307
Benjamin Kramer7761a042015-03-06 16:36:50 +0000308Sema::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) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000317
Benjamin Kramer7761a042015-03-06 16:36:50 +0000318Sema::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) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000326
Douglas Gregor85673582009-05-18 17:01:57 +0000327void Sema::InstantiatingTemplate::Clear() {
328 if (!Invalid) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000329 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
330 assert(SemaRef.NonInstantiationEntries > 0);
331 --SemaRef.NonInstantiationEntries;
332 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000333 SemaRef.InNonInstantiationSFINAEContext
334 = SavedInNonInstantiationSFINAEContext;
Richard Smith0e5d7b82013-07-25 23:08:39 +0000335
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
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000347 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000348 Invalid = true;
349 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000350}
351
Douglas Gregor79cf6032009-03-10 20:44:00 +0000352bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
353 SourceLocation PointOfInstantiation,
354 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000355 assert(SemaRef.NonInstantiationEntries <=
356 SemaRef.ActiveTemplateInstantiations.size());
357 if ((SemaRef.ActiveTemplateInstantiations.size() -
358 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000359 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000360 return false;
361
Mike Stump11289f42009-09-09 15:08:12 +0000362 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000363 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000364 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000365 << InstantiationRange;
366 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000367 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000368 return true;
369}
370
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000371/// \brief Prints the current instantiation stack through a series of
372/// notes.
373void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000374 // 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
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000382 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000383 unsigned InstantiationIdx = 0;
Craig Topper2341c0d2013-07-04 03:08:24 +0000384 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000385 Active = ActiveTemplateInstantiations.rbegin(),
386 ActiveEnd = ActiveTemplateInstantiations.rend();
387 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000388 ++Active, ++InstantiationIdx) {
389 // Skip this instantiation?
390 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
391 if (InstantiationIdx == SkipStart) {
392 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000393 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000394 diag::note_instantiation_contexts_suppressed)
395 << unsigned(ActiveTemplateInstantiations.size() - Limit);
396 }
397 continue;
398 }
399
Douglas Gregor79cf6032009-03-10 20:44:00 +0000400 switch (Active->Kind) {
401 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000402 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000403 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;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000407 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000408 << Context.getTypeDeclType(Record)
409 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000410 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000411 unsigned DiagID;
412 if (Function->getPrimaryTemplate())
413 DiagID = diag::note_function_template_spec_here;
414 else
415 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000416 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000417 << Function
418 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000419 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000420 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000421 VD->isStaticDataMember()?
422 diag::note_template_static_data_member_def_here
423 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000424 << VD
425 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000426 } 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;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000431 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
432 Diags.Report(Active->PointOfInstantiation,
433 diag::note_template_nsdmi_here)
434 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000435 } else {
436 Diags.Report(Active->PointOfInstantiation,
437 diag::note_template_type_alias_instantiation_here)
438 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000439 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000440 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000441 break;
442 }
443
444 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000445 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000446 SmallVector<char, 128> TemplateArgsStr;
447 llvm::raw_svector_ostream OS(TemplateArgsStr);
448 Template->printName(OS);
449 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump11289f42009-09-09 15:08:12 +0000450 Active->TemplateArgs,
Douglas Gregor7de59662009-05-29 20:38:28 +0000451 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000452 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000453 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000454 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000455 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000456 << Active->InstantiationRange;
457 break;
458 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000459
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000460 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000461 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000462 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000463 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000464 << FnTmpl
465 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
466 Active->TemplateArgs,
467 Active->NumTemplateArgs)
468 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000469 break;
470 }
Mike Stump11289f42009-09-09 15:08:12 +0000471
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000472 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000473 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
474 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000475 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000476 diag::note_partial_spec_deduct_instantiation_here)
477 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000478 << getTemplateArgumentBindingsText(
479 PartialSpec->getTemplateParameters(),
480 Active->TemplateArgs,
481 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000482 << Active->InstantiationRange;
483 } else {
484 FunctionTemplateDecl *FnTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000485 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000486 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000487 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000488 << FnTmpl
489 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
490 Active->TemplateArgs,
491 Active->NumTemplateArgs)
492 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000493 }
494 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000495
Anders Carlsson657bad42009-09-05 05:14:19 +0000496 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000497 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000498 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000499
Benjamin Kramer9170e912013-02-22 15:46:01 +0000500 SmallVector<char, 128> TemplateArgsStr;
501 llvm::raw_svector_ostream OS(TemplateArgsStr);
502 FD->printName(OS);
503 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump11289f42009-09-09 15:08:12 +0000504 Active->TemplateArgs,
Anders Carlsson657bad42009-09-05 05:14:19 +0000505 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000506 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000507 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000508 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000509 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000510 << Active->InstantiationRange;
511 break;
512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Douglas Gregore62e6a02009-11-11 19:13:48 +0000514 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000515 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000516 std::string Name;
517 if (!Parm->getName().empty())
518 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000519
520 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000521 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
522 TemplateParams = Template->getTemplateParameters();
523 else
524 TemplateParams =
525 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
526 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000527 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000528 diag::note_prior_template_arg_substitution)
529 << isa<TemplateTemplateParmDecl>(Parm)
530 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000531 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000532 Active->TemplateArgs,
533 Active->NumTemplateArgs)
534 << Active->InstantiationRange;
535 break;
536 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000537
538 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000539 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000540 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
541 TemplateParams = Template->getTemplateParameters();
542 else
543 TemplateParams =
544 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
545 ->getTemplateParameters();
546
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000547 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000548 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000549 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000550 Active->TemplateArgs,
551 Active->NumTemplateArgs)
552 << Active->InstantiationRange;
553 break;
554 }
Richard Smithf623c962012-04-17 00:58:00 +0000555
556 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
557 Diags.Report(Active->PointOfInstantiation,
558 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000559 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000560 << Active->InstantiationRange;
561 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000562 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000563 }
564}
565
David Blaikie05785d12013-02-20 22:23:23 +0000566Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000567 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000568 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000569
Craig Topper2341c0d2013-07-04 03:08:24 +0000570 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor33834512009-06-14 07:33:30 +0000571 Active = ActiveTemplateInstantiations.rbegin(),
572 ActiveEnd = ActiveTemplateInstantiations.rend();
573 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000574 ++Active)
575 {
Douglas Gregor33834512009-06-14 07:33:30 +0000576 switch(Active->Kind) {
Douglas Gregoredb76852011-01-27 22:31:44 +0000577 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000578 // An instantiation of an alias template may or may not be a SFINAE
579 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000580 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000581 break;
582 // Fall through.
583 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000584 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000585 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000586 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000587
Douglas Gregor33834512009-06-14 07:33:30 +0000588 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000589 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000590 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000591 // 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.
Douglas Gregor33834512009-06-14 07:33:30 +0000594 break;
Mike Stump11289f42009-09-09 15:08:12 +0000595
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000596 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
597 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
598 // We're either substitution explicitly-specified template arguments
599 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000600 assert(Active->DeductionInfo && "Missing deduction info pointer");
601 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000602 }
603 }
604
David Blaikie7a30dc52013-02-21 01:47:18 +0000605 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000606}
607
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000608/// \brief Retrieve the depth and index of a parameter pack.
609static std::pair<unsigned, unsigned>
610getDepthAndIndex(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
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000621//===----------------------------------------------------------------------===/
622// Template Instantiation for Types
623//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000624namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000625 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000626 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000627 SourceLocation Loc;
628 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000629
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000630 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000631 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000632
633 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000634 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000635 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000636 DeclarationName Entity)
637 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000638 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000639
Mike Stump11289f42009-09-09 15:08:12 +0000640 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000641 /// 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.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000645 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000646
Douglas Gregord6ff3322009-08-04 16:50:30 +0000647 /// \brief Returns the location of the entity being instantiated, if known.
648 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000649
Douglas Gregord6ff3322009-08-04 16:50:30 +0000650 /// \brief Returns the name of the entity being instantiated, if any.
651 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000652
Douglas Gregoref6ab412009-10-27 06:26:26 +0000653 /// \brief Sets the "base" location and entity when that
654 /// information is known based on another transformation.
655 void setBase(SourceLocation Loc, DeclarationName Entity) {
656 this->Loc = Loc;
657 this->Entity = Entity;
658 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000659
660 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
661 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000662 ArrayRef<UnexpandedParameterPack> Unexpanded,
663 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000664 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000665 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
666 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000667 TemplateArgs,
668 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000669 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000670 NumExpansions);
671 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000672
Douglas Gregorf3010112011-01-07 16:43:16 +0000673 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
674 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
675 }
676
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000677 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;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000684 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000685 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
686 Result = TemplateArgs(Depth, Index);
687 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
688 }
689 }
690
691 return Result;
692 }
693
694 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
695 if (Arg.isNull())
696 return;
697
698 if (NamedDecl *PartialPack
699 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
700 MultiLevelTemplateArgumentList &TemplateArgs
701 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
702 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000703 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000704 TemplateArgs.setArgument(Depth, Index, Arg);
705 }
706 }
707
Douglas Gregord6ff3322009-08-04 16:50:30 +0000708 /// \brief Transform the given declaration by instantiating a reference to
709 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000710 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000711
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000712 void transformAttrs(Decl *Old, Decl *New) {
713 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
714 }
715
716 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000717 // 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
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000731 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000732
733 // We recreated a local declaration, but not by instantiating it. There
734 // may be pending dependent diagnostics to produce.
735 if (auto *DC = dyn_cast<DeclContext>(Old))
736 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000737 }
738
Mike Stump11289f42009-09-09 15:08:12 +0000739 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000740 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000741 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000742
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000743 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000744 /// declaration.
745 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
746
Douglas Gregorebe10102009-08-20 07:17:43 +0000747 /// \brief Rebuild the exception declaration and register the declaration
748 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000749 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000750 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000751 SourceLocation StartLoc,
752 SourceLocation NameLoc,
753 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000754
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000755 /// \brief Rebuild the Objective-C exception declaration and register the
756 /// declaration as an instantiated local.
757 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
758 TypeSourceInfo *TSInfo, QualType T);
759
John McCall7f41d982009-09-11 04:59:25 +0000760 /// \brief Check for tag mismatches when instantiating an
761 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000762 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
763 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000764 NestedNameSpecifierLoc QualifierLoc,
765 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000766
Craig Topperc3ec1492014-05-26 06:22:03 +0000767 TemplateName
768 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
769 SourceLocation NameLoc,
770 QualType ObjectType = QualType(),
771 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregor9db53502011-03-02 18:07:45 +0000772
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000773 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
774
John McCalldadc5752010-08-24 06:29:42 +0000775 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
776 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
777 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000778
John McCalldadc5752010-08-24 06:29:42 +0000779 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000780 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000781 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
782 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000783
784 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
785 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
786
787 /// \brief Transform a reference to a function parameter pack.
788 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
789 ParmVarDecl *PD);
790
791 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
792 /// expand a function parameter pack reference which refers to an expanded
793 /// pack.
794 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
795
Hans Wennborge113c202014-09-18 16:01:32 +0000796 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000797 FunctionProtoTypeLoc TL) {
798 // Call the base version; it will forward to our overridden version below.
799 return inherited::TransformFunctionProtoType(TLB, TL);
800 }
801
802 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000803 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
804 FunctionProtoTypeLoc TL,
805 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000806 unsigned ThisTypeQuals,
807 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000808
Douglas Gregor715e4612011-01-14 22:40:04 +0000809 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000810 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000811 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000812 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000813
Mike Stump11289f42009-09-09 15:08:12 +0000814 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000815 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000816 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000817 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000818
Douglas Gregorada4b792011-01-14 02:55:32 +0000819 /// \brief Transforms an already-substituted template type parameter pack
820 /// into either itself (if we aren't substituting into its pack expansion)
821 /// or the appropriate substituted argument.
822 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
823 SubstTemplateTypeParmPackTypeLoc TL);
824
Richard Smith2589b9802012-07-25 03:56:55 +0000825 ExprResult TransformLambdaExpr(LambdaExpr *E) {
826 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
827 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
828 }
829
David Majnemerb1004102014-03-02 18:46:05 +0000830 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000831 TemplateParameterList *OrigTPL) {
832 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
833
834 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
835 TemplateDeclInstantiator DeclInstantiator(getSema(),
836 /* DeclContext *Owner */ Owner, TemplateArgs);
837 return DeclInstantiator.SubstTemplateParams(OrigTPL);
838 }
John McCall7c454bb2011-07-15 05:09:51 +0000839 private:
840 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
841 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000842 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000843 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000844}
Douglas Gregor04318252009-07-06 15:59:29 +0000845
Douglas Gregor5597ab42010-05-07 23:12:07 +0000846bool TemplateInstantiator::AlreadyTransformed(QualType T) {
847 if (T.isNull())
848 return true;
849
Douglas Gregor678d76c2011-07-01 01:22:09 +0000850 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000851 return false;
852
853 getSema().MarkDeclarationsReferencedInType(Loc, T);
854 return true;
855}
856
Eli Friedman8917ad52013-07-19 19:40:38 +0000857static TemplateArgument
858getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
859 assert(S.ArgumentPackSubstitutionIndex >= 0);
860 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
861 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
862 if (Arg.isPackExpansion())
863 Arg = Arg.getPackExpansionPattern();
864 return Arg;
865}
866
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000867Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000868 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000869 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000870
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000871 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000872 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000873 // If the corresponding template argument is NULL or non-existent, it's
874 // because we are performing instantiation from explicitly-specified
875 // template arguments in a function template, but there were some
876 // arguments left unspecified.
877 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
878 TTP->getPosition()))
879 return D;
880
Douglas Gregorf5500772011-01-05 15:48:55 +0000881 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
882
883 if (TTP->isParameterPack()) {
884 assert(Arg.getKind() == TemplateArgument::Pack &&
885 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000886 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000887 }
888
889 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000890 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000891 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000892 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000893 }
Mike Stump11289f42009-09-09 15:08:12 +0000894
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000895 // Fall through to find the instantiated declaration for this template
896 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000897 }
Mike Stump11289f42009-09-09 15:08:12 +0000898
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000899 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000900}
901
Douglas Gregor25289362010-03-01 17:25:41 +0000902Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000903 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000904 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000905 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000906
Douglas Gregorebe10102009-08-20 07:17:43 +0000907 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
908 return Inst;
909}
910
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000911NamedDecl *
912TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
913 SourceLocation Loc) {
914 // If the first part of the nested-name-specifier was a template type
915 // parameter, instantiate that type parameter down to a tag type.
916 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
917 const TemplateTypeParmType *TTP
918 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000919
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000920 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000921 // FIXME: This needs testing w/ member access expressions.
922 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
923
924 if (TTP->isParameterPack()) {
925 assert(Arg.getKind() == TemplateArgument::Pack &&
926 "Missing argument pack");
927
Douglas Gregore1d60df2011-01-14 23:41:42 +0000928 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +0000929 return nullptr;
930
Eli Friedman8917ad52013-07-19 19:40:38 +0000931 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000932 }
933
934 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000935 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000936 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000937
938 if (const TagType *Tag = T->getAs<TagType>())
939 return Tag->getDecl();
940
941 // The resulting type is not a tag; complain.
942 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +0000943 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000944 }
945 }
946
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000947 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000948}
949
Douglas Gregorebe10102009-08-20 07:17:43 +0000950VarDecl *
951TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000952 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000953 SourceLocation StartLoc,
954 SourceLocation NameLoc,
955 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000956 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000957 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000958 if (Var)
959 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
960 return Var;
961}
962
963VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
964 TypeSourceInfo *TSInfo,
965 QualType T) {
966 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
967 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000968 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
969 return Var;
970}
971
John McCall7f41d982009-09-11 04:59:25 +0000972QualType
John McCall954b5de2010-11-04 19:04:38 +0000973TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
974 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000975 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000976 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +0000977 if (const TagType *TT = T->getAs<TagType>()) {
978 TagDecl* TD = TT->getDecl();
979
John McCall954b5de2010-11-04 19:04:38 +0000980 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +0000981
John McCall7f41d982009-09-11 04:59:25 +0000982 IdentifierInfo *Id = TD->getIdentifier();
983
984 // TODO: should we even warn on struct/class mismatches for this? Seems
985 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +0000986 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000987 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +0000988 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +0000989 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000990 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
991 << Id
992 << FixItHint::CreateReplacement(SourceRange(TagLocation),
993 TD->getKindName());
994 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
995 }
John McCall7f41d982009-09-11 04:59:25 +0000996 }
997 }
998
John McCall954b5de2010-11-04 19:04:38 +0000999 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1000 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001001 QualifierLoc,
1002 T);
John McCall7f41d982009-09-11 04:59:25 +00001003}
1004
Douglas Gregor9db53502011-03-02 18:07:45 +00001005TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1006 TemplateName Name,
Nico Weberc153d242014-07-28 00:02:09 +00001007 SourceLocation NameLoc,
Douglas Gregor9db53502011-03-02 18:07:45 +00001008 QualType ObjectType,
1009 NamedDecl *FirstQualifierInScope) {
1010 if (TemplateTemplateParmDecl *TTP
1011 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1012 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1013 // If the corresponding template argument is NULL or non-existent, it's
1014 // because we are performing instantiation from explicitly-specified
1015 // template arguments in a function template, but there were some
1016 // arguments left unspecified.
1017 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1018 TTP->getPosition()))
1019 return Name;
1020
1021 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1022
1023 if (TTP->isParameterPack()) {
1024 assert(Arg.getKind() == TemplateArgument::Pack &&
1025 "Missing argument pack");
1026
1027 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1028 // We have the template argument pack to substitute, but we're not
1029 // actually expanding the enclosing pack expansion yet. So, just
1030 // keep the entire argument pack.
1031 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1032 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001033
1034 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001035 }
1036
1037 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001038 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001039
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001040 // We don't ever want to substitute for a qualified template name, since
1041 // the qualifier is handled separately. So, look through the qualified
1042 // template name to its underlying declaration.
1043 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1044 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001045
1046 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001047 return Template;
1048 }
1049 }
1050
1051 if (SubstTemplateTemplateParmPackStorage *SubstPack
1052 = Name.getAsSubstTemplateTemplateParmPack()) {
1053 if (getSema().ArgumentPackSubstitutionIndex == -1)
1054 return Name;
1055
Eli Friedman8917ad52013-07-19 19:40:38 +00001056 TemplateArgument Arg = SubstPack->getArgumentPack();
1057 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1058 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001059 }
1060
1061 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1062 FirstQualifierInScope);
1063}
1064
John McCalldadc5752010-08-24 06:29:42 +00001065ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001066TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001067 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001068 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001069
Wei Panc354d212013-09-16 13:57:27 +00001070 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001071}
1072
John McCalldadc5752010-08-24 06:29:42 +00001073ExprResult
John McCall13481c52010-02-06 08:42:39 +00001074TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001075 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001076 // If the corresponding template argument is NULL or non-existent, it's
1077 // because we are performing instantiation from explicitly-specified
1078 // template arguments in a function template, but there were some
1079 // arguments left unspecified.
1080 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1081 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001082 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001083
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001084 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1085 if (NTTP->isParameterPack()) {
1086 assert(Arg.getKind() == TemplateArgument::Pack &&
1087 "Missing argument pack");
1088
1089 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001090 // We have an argument pack, but we can't select a particular argument
1091 // out of it yet. Therefore, we'll build an expression to hold on to that
1092 // argument pack.
1093 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1094 E->getLocation(),
1095 NTTP->getDeclName());
1096 if (TargetType.isNull())
1097 return ExprError();
1098
1099 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1100 NTTP,
1101 E->getLocation(),
1102 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001103 }
1104
Eli Friedman8917ad52013-07-19 19:40:38 +00001105 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001106 }
Mike Stump11289f42009-09-09 15:08:12 +00001107
John McCall7c454bb2011-07-15 05:09:51 +00001108 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1109}
1110
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001111const LoopHintAttr *
1112TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1113 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1114
1115 if (TransformedExpr == LH->getValue())
1116 return LH;
1117
1118 // Generate error if there is a problem with the value.
1119 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1120 return LH;
1121
1122 // Create new LoopHintValueAttr with integral expression in place of the
1123 // non-type template parameter.
1124 return LoopHintAttr::CreateImplicit(
1125 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1126 LH->getState(), TransformedExpr, LH->getRange());
1127}
1128
John McCall7c454bb2011-07-15 05:09:51 +00001129ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1130 NonTypeTemplateParmDecl *parm,
1131 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001132 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001133 ExprResult result;
1134 QualType type;
1135
John McCall13481c52010-02-06 08:42:39 +00001136 // The template argument itself might be an expression, in which
1137 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001138 if (arg.getKind() == TemplateArgument::Expression) {
1139 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001140 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001141 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001142
Eli Friedmanb826a002012-09-26 02:36:12 +00001143 } else if (arg.getKind() == TemplateArgument::Declaration ||
1144 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001145 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001146 if (arg.getKind() == TemplateArgument::Declaration) {
1147 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001148
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001149 // Find the instantiation of the template argument. This is
1150 // required for nested templates.
1151 VD = cast_or_null<ValueDecl>(
1152 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1153 if (!VD)
1154 return ExprError();
1155 } else {
1156 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001157 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001158 }
1159
John McCall15dda372010-02-06 10:23:53 +00001160 // Derive the type we want the substituted decl to have. This had
1161 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001162 if (parm->isExpandedParameterPack()) {
1163 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1164 } else if (parm->isParameterPack() &&
1165 isa<PackExpansionType>(parm->getType())) {
1166 type = SemaRef.SubstType(
1167 cast<PackExpansionType>(parm->getType())->getPattern(),
1168 TemplateArgs, loc, parm->getDeclName());
1169 } else {
1170 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1171 loc, parm->getDeclName());
1172 }
1173 assert(!type.isNull() && "type substitution failed for param type");
1174 assert(!type->isDependentType() && "param type still dependent");
1175 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001176
John McCall7c454bb2011-07-15 05:09:51 +00001177 if (!result.isInvalid()) type = result.get()->getType();
1178 } else {
1179 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1180
1181 // Note that this type can be different from the type of 'result',
1182 // e.g. if it's an enum type.
1183 type = arg.getIntegralType();
1184 }
1185 if (result.isInvalid()) return ExprError();
1186
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001187 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001188 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1189 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001190}
1191
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001192ExprResult
1193TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1194 SubstNonTypeTemplateParmPackExpr *E) {
1195 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1196 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001197 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001198 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001199
1200 TemplateArgument Arg = E->getArgumentPack();
1201 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001202 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1203 E->getParameterPackLocation(),
1204 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001205}
John McCall13481c52010-02-06 08:42:39 +00001206
John McCalldadc5752010-08-24 06:29:42 +00001207ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001208TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1209 SourceLocation Loc) {
1210 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1211 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1212}
1213
1214ExprResult
1215TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1216 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1217 // We can expand this parameter pack now.
1218 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1219 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1220 if (!VD)
1221 return ExprError();
1222 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1223 }
1224
1225 QualType T = TransformType(E->getType());
1226 if (T.isNull())
1227 return ExprError();
1228
1229 // Transform each of the parameter expansions into the corresponding
1230 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001231 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001232 Parms.reserve(E->getNumExpansions());
1233 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1234 I != End; ++I) {
1235 ParmVarDecl *D =
1236 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1237 if (!D)
1238 return ExprError();
1239 Parms.push_back(D);
1240 }
1241
1242 return FunctionParmPackExpr::Create(getSema().Context, T,
1243 E->getParameterPack(),
1244 E->getParameterPackLocation(), Parms);
1245}
1246
1247ExprResult
1248TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1249 ParmVarDecl *PD) {
1250 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1251 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1252 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1253 assert(Found && "no instantiation for parameter pack");
1254
1255 Decl *TransformedDecl;
1256 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001257 // If this is a reference to a function parameter pack which we can
1258 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001259 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1260 QualType T = TransformType(E->getType());
1261 if (T.isNull())
1262 return ExprError();
1263 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1264 E->getExprLoc(), *Pack);
1265 }
1266
1267 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1268 } else {
1269 TransformedDecl = Found->get<Decl*>();
1270 }
1271
1272 // We have either an unexpanded pack or a specific expansion.
1273 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1274 E->getExprLoc());
1275}
1276
1277ExprResult
John McCall13481c52010-02-06 08:42:39 +00001278TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1279 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001280
1281 // Handle references to non-type template parameters and non-type template
1282 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001283 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1284 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1285 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001286
1287 // We have a non-type template parameter that isn't fully substituted;
1288 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001289 }
Mike Stump11289f42009-09-09 15:08:12 +00001290
Richard Smithb15fe3a2012-09-12 00:56:43 +00001291 // Handle references to function parameter packs.
1292 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1293 if (PD->isParameterPack())
1294 return TransformFunctionParmPackRefExpr(E, PD);
1295
John McCall47f29ea2009-12-08 09:21:05 +00001296 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001297}
1298
John McCalldadc5752010-08-24 06:29:42 +00001299ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001300 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001301 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1302 getDescribedFunctionTemplate() &&
1303 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001304 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1305 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1306 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001307}
1308
Richard Smith2e321552014-11-12 02:00:47 +00001309template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001310QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1311 FunctionProtoTypeLoc TL,
1312 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001313 unsigned ThisTypeQuals,
1314 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001315 // We need a local instantiation scope for this function prototype.
1316 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001317 return inherited::TransformFunctionProtoType(
1318 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001319}
1320
John McCall58f10c32010-03-11 09:03:00 +00001321ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001322TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001323 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001324 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001325 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001326 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001327 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001328}
1329
Mike Stump11289f42009-09-09 15:08:12 +00001330QualType
John McCall550e0c22009-10-21 00:40:46 +00001331TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001332 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001333 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001334 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001335 // Replace the template type parameter with its corresponding
1336 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001337
1338 // If the corresponding template argument is NULL or doesn't exist, it's
1339 // because we are performing instantiation from explicitly-specified
1340 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001341 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001342 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1343 TemplateTypeParmTypeLoc NewTL
1344 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1345 NewTL.setNameLoc(TL.getNameLoc());
1346 return TL.getType();
1347 }
Mike Stump11289f42009-09-09 15:08:12 +00001348
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001349 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1350
1351 if (T->isParameterPack()) {
1352 assert(Arg.getKind() == TemplateArgument::Pack &&
1353 "Missing argument pack");
1354
1355 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001356 // We have the template argument pack, but we're not expanding the
1357 // enclosing pack expansion yet. Just save the template argument
1358 // pack for later substitution.
1359 QualType Result
1360 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1361 SubstTemplateTypeParmPackTypeLoc NewTL
1362 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1363 NewTL.setNameLoc(TL.getNameLoc());
1364 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001365 }
1366
Eli Friedman8917ad52013-07-19 19:40:38 +00001367 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001368 }
1369
1370 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001371 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001372
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001373 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001374
1375 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001376 QualType Result
1377 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1378 SubstTemplateTypeParmTypeLoc NewTL
1379 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1380 NewTL.setNameLoc(TL.getNameLoc());
1381 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001382 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001383
1384 // The template type parameter comes from an inner template (e.g.,
1385 // the template parameter list of a member template inside the
1386 // template we are instantiating). Create a new template type
1387 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001388 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001389 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1390 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1391 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1392
John McCall550e0c22009-10-21 00:40:46 +00001393 QualType Result
1394 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1395 - TemplateArgs.getNumLevels(),
1396 T->getIndex(),
1397 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001398 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001399 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1400 NewTL.setNameLoc(TL.getNameLoc());
1401 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001402}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001403
Douglas Gregorada4b792011-01-14 02:55:32 +00001404QualType
1405TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1406 TypeLocBuilder &TLB,
1407 SubstTemplateTypeParmPackTypeLoc TL) {
1408 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1409 // We aren't expanding the parameter pack, so just return ourselves.
1410 SubstTemplateTypeParmPackTypeLoc NewTL
1411 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1412 NewTL.setNameLoc(TL.getNameLoc());
1413 return TL.getType();
1414 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001415
1416 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1417 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1418 QualType Result = Arg.getAsType();
1419
Douglas Gregorada4b792011-01-14 02:55:32 +00001420 Result = getSema().Context.getSubstTemplateTypeParmType(
1421 TL.getTypePtr()->getReplacedParameter(),
1422 Result);
1423 SubstTemplateTypeParmTypeLoc NewTL
1424 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1425 NewTL.setNameLoc(TL.getNameLoc());
1426 return Result;
1427}
1428
John McCall76d824f2009-08-25 22:02:44 +00001429/// \brief Perform substitution on the type T with a given set of template
1430/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001431///
1432/// This routine substitutes the given template arguments into the
1433/// type T and produces the instantiated type.
1434///
1435/// \param T the type into which the template arguments will be
1436/// substituted. If this type is not dependent, it will be returned
1437/// immediately.
1438///
James Dennett634962f2012-06-14 21:40:34 +00001439/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001440/// substituted for the top-level template parameters within T.
1441///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001442/// \param Loc the location in the source code where this substitution
1443/// is being performed. It will typically be the location of the
1444/// declarator (if we're instantiating the type of some declaration)
1445/// or the location of the type in the source code (if, e.g., we're
1446/// instantiating the type of a cast expression).
1447///
1448/// \param Entity the name of the entity associated with a declaration
1449/// being instantiated (if any). May be empty to indicate that there
1450/// is no such entity (if, e.g., this is a type that occurs as part of
1451/// a cast expression) or that the entity has no name (e.g., an
1452/// unnamed function parameter).
1453///
1454/// \returns If the instantiation succeeds, the instantiated
1455/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001456TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001457 const MultiLevelTemplateArgumentList &Args,
1458 SourceLocation Loc,
1459 DeclarationName Entity) {
1460 assert(!ActiveTemplateInstantiations.empty() &&
1461 "Cannot perform an instantiation without some context on the "
1462 "instantiation stack");
1463
Douglas Gregor678d76c2011-07-01 01:22:09 +00001464 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001465 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001466 return T;
1467
1468 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1469 return Instantiator.TransformType(T);
1470}
1471
Douglas Gregor5499af42011-01-05 23:12:31 +00001472TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1473 const MultiLevelTemplateArgumentList &Args,
1474 SourceLocation Loc,
1475 DeclarationName Entity) {
1476 assert(!ActiveTemplateInstantiations.empty() &&
1477 "Cannot perform an instantiation without some context on the "
1478 "instantiation stack");
1479
1480 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001481 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001482
Douglas Gregor678d76c2011-07-01 01:22:09 +00001483 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001484 !TL.getType()->isVariablyModifiedType()) {
1485 // FIXME: Make a copy of the TypeLoc data here, so that we can
1486 // return a new TypeSourceInfo. Inefficient!
1487 TypeLocBuilder TLB;
1488 TLB.pushFullCopy(TL);
1489 return TLB.getTypeSourceInfo(Context, TL.getType());
1490 }
1491
1492 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1493 TypeLocBuilder TLB;
1494 TLB.reserve(TL.getFullDataSize());
1495 QualType Result = Instantiator.TransformType(TLB, TL);
1496 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001497 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001498
1499 return TLB.getTypeSourceInfo(Context, Result);
1500}
1501
John McCall609459e2009-10-21 00:58:09 +00001502/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001503QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001504 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001505 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001506 assert(!ActiveTemplateInstantiations.empty() &&
1507 "Cannot perform an instantiation without some context on the "
1508 "instantiation stack");
1509
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001510 // If T is not a dependent type or a variably-modified type, there
1511 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001512 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001513 return T;
1514
Douglas Gregord6ff3322009-08-04 16:50:30 +00001515 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1516 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001517}
Douglas Gregor463421d2009-03-03 04:44:36 +00001518
John McCallb29f78f2010-04-09 17:38:44 +00001519static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001520 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001521 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001522 return true;
1523
Abramo Bagnara6d810632010-12-14 22:11:44 +00001524 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001525 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001526 return false;
1527
David Blaikie6adc78e2013-02-18 22:06:02 +00001528 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001529 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001530 // This must be synthesized from a typedef.
1531 if (!P) continue;
1532
Nico Weberc0973372016-02-01 22:31:51 +00001533 // If there are any parameters, a new TypeSourceInfo that refers to the
1534 // instantiated parameters must be built.
1535 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001536 }
1537
1538 return false;
1539}
1540
1541/// A form of SubstType intended specifically for instantiating the
1542/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001543/// instantiation of default-argument expressions and to avoid
1544/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001545TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1546 const MultiLevelTemplateArgumentList &Args,
1547 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001548 DeclarationName Entity,
1549 CXXRecordDecl *ThisContext,
1550 unsigned ThisTypeQuals) {
John McCallb29f78f2010-04-09 17:38:44 +00001551 assert(!ActiveTemplateInstantiations.empty() &&
1552 "Cannot perform an instantiation without some context on the "
1553 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001554
John McCallb29f78f2010-04-09 17:38:44 +00001555 if (!NeedsInstantiationAsFunctionType(T))
1556 return T;
1557
1558 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1559
1560 TypeLocBuilder TLB;
1561
1562 TypeLoc TL = T->getTypeLoc();
1563 TLB.reserve(TL.getFullDataSize());
1564
Douglas Gregor3024f072012-04-16 07:05:22 +00001565 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001566
Richard Smith2e321552014-11-12 02:00:47 +00001567 if (FunctionProtoTypeLoc Proto =
1568 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1569 // Instantiate the type, other than its exception specification. The
1570 // exception specification is instantiated in InitFunctionInstantiation
1571 // once we've built the FunctionDecl.
1572 // FIXME: Set the exception specification to EST_Uninstantiated here,
1573 // instead of rebuilding the function type again later.
1574 Result = Instantiator.TransformFunctionProtoType(
1575 TLB, Proto, ThisContext, ThisTypeQuals,
1576 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1577 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001578 } else {
1579 Result = Instantiator.TransformType(TLB, TL);
1580 }
John McCallb29f78f2010-04-09 17:38:44 +00001581 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001582 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001583
1584 return TLB.getTypeSourceInfo(Context, Result);
1585}
1586
Richard Smith2e321552014-11-12 02:00:47 +00001587void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1588 const MultiLevelTemplateArgumentList &Args) {
1589 FunctionProtoType::ExceptionSpecInfo ESI =
1590 Proto->getExtProtoInfo().ExceptionSpec;
1591 assert(ESI.Type != EST_Uninstantiated);
1592
1593 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1594 New->getDeclName());
1595
1596 SmallVector<QualType, 4> ExceptionStorage;
1597 bool Changed = false;
1598 if (Instantiator.TransformExceptionSpec(
1599 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1600 ExceptionStorage, Changed))
1601 // On error, recover by dropping the exception specification.
1602 ESI.Type = EST_None;
1603
1604 UpdateExceptionSpec(New, ESI);
1605}
1606
Douglas Gregor940bca72010-04-12 07:48:19 +00001607ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001608 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001609 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001610 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001611 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001612 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001613 TypeSourceInfo *NewDI = nullptr;
1614
Douglas Gregor5499af42011-01-05 23:12:31 +00001615 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001616 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1617
Douglas Gregor5499af42011-01-05 23:12:31 +00001618 // We have a function parameter pack. Substitute into the pattern of the
1619 // expansion.
1620 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1621 OldParm->getLocation(), OldParm->getDeclName());
1622 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001623 return nullptr;
1624
Douglas Gregor5499af42011-01-05 23:12:31 +00001625 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1626 // We still have unexpanded parameter packs, which means that
1627 // our function parameter is still a function parameter pack.
1628 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001629 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001630 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001631 } else if (ExpectParameterPack) {
1632 // We expected to get a parameter pack but didn't (because the type
1633 // itself is not a pack expansion type), so complain. This can occur when
1634 // the substitution goes through an alias template that "loses" the
1635 // pack expansion.
1636 Diag(OldParm->getLocation(),
1637 diag::err_function_parameter_pack_without_parameter_packs)
1638 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001639 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001640 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001641 } else {
1642 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1643 OldParm->getDeclName());
1644 }
1645
Douglas Gregor940bca72010-04-12 07:48:19 +00001646 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001647 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001648
1649 if (NewDI->getType()->isVoidType()) {
1650 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001651 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001652 }
1653
1654 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001655 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001656 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001657 OldParm->getIdentifier(),
1658 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001659 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001660 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001661 return nullptr;
1662
Douglas Gregor940bca72010-04-12 07:48:19 +00001663 // Mark the (new) default argument as uninstantiated (if any).
1664 if (OldParm->hasUninstantiatedDefaultArg()) {
1665 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1666 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001667 } else if (OldParm->hasUnparsedDefaultArg()) {
1668 NewParm->setUnparsedDefaultArg();
1669 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001670 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1671 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001672 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1673 // Instantiate default arguments for methods of local classes (DR1484)
1674 // and non-defining declarations.
1675 Sema::ContextRAII SavedContext(*this, OwningFunc);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001676 LocalInstantiationScope Local(*this);
1677 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001678 if (NewArg.isUsable()) {
1679 // It would be nice if we still had this.
1680 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1681 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1682 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001683 } else {
1684 // FIXME: if we non-lazily instantiated non-dependent default args for
1685 // non-dependent parameter types we could remove a bunch of duplicate
1686 // conversion warnings for such arguments.
1687 NewParm->setUninstantiatedDefaultArg(Arg);
1688 }
1689 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001690
1691 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001692
Douglas Gregorf3010112011-01-07 16:43:16 +00001693 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001694 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001695 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1696 } else {
1697 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001698 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001699 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001700
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001701 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1702 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001703 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001704
1705 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1706 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001707
1708 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1709
Douglas Gregor940bca72010-04-12 07:48:19 +00001710 return NewParm;
1711}
1712
Douglas Gregordd472162011-01-07 00:20:55 +00001713/// \brief Substitute the given template arguments into the given set of
1714/// parameters, producing the set of parameter types that would be generated
1715/// from such a substitution.
1716bool Sema::SubstParmTypes(SourceLocation Loc,
1717 ParmVarDecl **Params, unsigned NumParams,
John McCallc8e321d2016-03-01 02:09:25 +00001718 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
Douglas Gregordd472162011-01-07 00:20:55 +00001719 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001720 SmallVectorImpl<QualType> &ParamTypes,
John McCallc8e321d2016-03-01 02:09:25 +00001721 SmallVectorImpl<ParmVarDecl *> *OutParams,
1722 ExtParameterInfoBuilder &ParamInfos) {
Douglas Gregordd472162011-01-07 00:20:55 +00001723 assert(!ActiveTemplateInstantiations.empty() &&
1724 "Cannot perform an instantiation without some context on the "
1725 "instantiation stack");
1726
1727 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1728 DeclarationName());
Craig Topperc3ec1492014-05-26 06:22:03 +00001729 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams,
John McCallc8e321d2016-03-01 02:09:25 +00001730 nullptr, ExtParamInfos,
1731 ParamTypes, OutParams,
1732 ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001733}
1734
John McCall76d824f2009-08-25 22:02:44 +00001735/// \brief Perform substitution on the base class specifiers of the
1736/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001737///
1738/// Produces a diagnostic and returns true on error, returns false and
1739/// attaches the instantiated base classes to the class template
1740/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001741bool
John McCall76d824f2009-08-25 22:02:44 +00001742Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1743 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001744 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001745 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001746 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001747 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001748 if (!Base.getType()->isDependentType()) {
1749 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001750 if (RD->isInvalidDecl())
1751 Instantiation->setInvalidDecl();
1752 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001753 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001754 continue;
1755 }
1756
Douglas Gregor752a5952011-01-03 22:36:02 +00001757 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001758 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001759 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001760 // This is a pack expansion. See whether we should expand it now, or
1761 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001762 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001763 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001764 Unexpanded);
1765 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001766 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001767 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001768 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1769 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001770 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001771 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001772 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001773 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001774 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001775 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001776 }
1777
1778 // If we should expand this pack expansion now, do so.
1779 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001780 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001781 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1782
Aaron Ballman574705e2014-03-13 15:41:46 +00001783 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001784 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001785 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001786 DeclarationName());
1787 if (!BaseTypeLoc) {
1788 Invalid = true;
1789 continue;
1790 }
1791
1792 if (CXXBaseSpecifier *InstantiatedBase
1793 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001794 Base.getSourceRange(),
1795 Base.isVirtual(),
1796 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001797 BaseTypeLoc,
1798 SourceLocation()))
1799 InstantiatedBases.push_back(InstantiatedBase);
1800 else
1801 Invalid = true;
1802 }
1803
1804 continue;
1805 }
1806
1807 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001808 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001809 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001810 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001811 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001812 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001813 DeclarationName());
1814 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001815 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001816 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001817 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001818 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001819 }
1820
Nick Lewycky19b9f952010-07-26 16:56:01 +00001821 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001822 Invalid = true;
1823 continue;
1824 }
1825
1826 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001827 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001828 Base.getSourceRange(),
1829 Base.isVirtual(),
1830 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001831 BaseTypeLoc,
1832 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001833 InstantiatedBases.push_back(InstantiatedBase);
1834 else
1835 Invalid = true;
1836 }
1837
Craig Topperaa700cb2015-12-27 21:55:19 +00001838 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001839 Invalid = true;
1840
1841 return Invalid;
1842}
1843
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001844// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001845namespace clang {
1846 namespace sema {
1847 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1848 const MultiLevelTemplateArgumentList &TemplateArgs);
1849 }
1850}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001851
Richard Smith4b38ded2012-03-14 23:13:10 +00001852/// Determine whether we would be unable to instantiate this template (because
1853/// it either has no definition, or is in the process of being instantiated).
1854static bool DiagnoseUninstantiableTemplate(Sema &S,
1855 SourceLocation PointOfInstantiation,
1856 TagDecl *Instantiation,
1857 bool InstantiatedFromMember,
1858 TagDecl *Pattern,
1859 TagDecl *PatternDef,
1860 TemplateSpecializationKind TSK,
1861 bool Complain = true) {
1862 if (PatternDef && !PatternDef->isBeingDefined())
1863 return false;
1864
1865 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1866 // Say nothing
1867 } else if (PatternDef) {
1868 assert(PatternDef->isBeingDefined());
1869 S.Diag(PointOfInstantiation,
1870 diag::err_template_instantiate_within_definition)
1871 << (TSK != TSK_ImplicitInstantiation)
1872 << S.Context.getTypeDeclType(Instantiation);
1873 // Not much point in noting the template declaration here, since
1874 // we're lexically inside it.
1875 Instantiation->setInvalidDecl();
1876 } else if (InstantiatedFromMember) {
1877 S.Diag(PointOfInstantiation,
1878 diag::err_implicit_instantiate_member_undefined)
1879 << S.Context.getTypeDeclType(Instantiation);
Alp Toker2afa8782014-05-28 12:20:14 +00001880 S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
Richard Smith4b38ded2012-03-14 23:13:10 +00001881 } else {
1882 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1883 << (TSK != TSK_ImplicitInstantiation)
1884 << S.Context.getTypeDeclType(Instantiation);
1885 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1886 }
1887
1888 // In general, Instantiation isn't marked invalid to get more than one
1889 // error for multiple undefined instantiations. But the code that does
1890 // explicit declaration -> explicit definition conversion can't handle
1891 // invalid declarations, so mark as invalid in that case.
1892 if (TSK == TSK_ExplicitInstantiationDeclaration)
1893 Instantiation->setInvalidDecl();
1894 return true;
1895}
1896
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001897/// \brief Instantiate the definition of a class from a given pattern.
1898///
1899/// \param PointOfInstantiation The point of instantiation within the
1900/// source code.
1901///
1902/// \param Instantiation is the declaration whose definition is being
1903/// instantiated. This will be either a class template specialization
1904/// or a member class of a class template specialization.
1905///
1906/// \param Pattern is the pattern from which the instantiation
1907/// occurs. This will be either the declaration of a class template or
1908/// the declaration of a member class of a class template.
1909///
1910/// \param TemplateArgs The template arguments to be substituted into
1911/// the pattern.
1912///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001913/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001914///
1915/// \param Complain whether to complain if the class cannot be instantiated due
1916/// to the lack of a definition.
1917///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001918/// \returns true if an error occurred, false otherwise.
1919bool
1920Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1921 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001922 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001923 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001924 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001925 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001926 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smith4b38ded2012-03-14 23:13:10 +00001927 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1928 Instantiation->getInstantiatedFromMemberClass(),
1929 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001930 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001931 Pattern = PatternDef;
1932
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001933 // \brief Record the point of instantiation.
1934 if (MemberSpecializationInfo *MSInfo
1935 = Instantiation->getMemberSpecializationInfo()) {
1936 MSInfo->setTemplateSpecializationKind(TSK);
1937 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001938 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001939 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001940 Spec->setTemplateSpecializationKind(TSK);
1941 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001942 }
Richard Smitha1087602014-03-10 00:04:29 +00001943
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001944 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001945 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001946 return true;
1947
1948 // Enter the scope of this instantiation. We don't use
1949 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001950 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001951 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001952 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001953
Douglas Gregor51121572010-03-24 01:33:17 +00001954 // If this is an instantiation of a local class, merge this local
1955 // instantiation scope with the enclosing scope. Otherwise, every
1956 // instantiation of a class has its own local instantiation scope.
1957 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001958 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001959
Reid Kleckner5b640342016-02-26 19:51:02 +00001960 // All dllexported classes created during instantiation should be fully
1961 // emitted after instantiation completes. We may not be ready to emit any
1962 // delayed classes already on the stack, so save them away and put them back
1963 // later.
1964 decltype(DelayedDllExportClasses) ExportedClasses;
1965 std::swap(ExportedClasses, DelayedDllExportClasses);
1966
John McCall6602bb12010-08-01 02:01:53 +00001967 // Pull attributes from the pattern onto the instantiation.
1968 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1969
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001970 // Start the definition of this instantiation.
1971 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00001972
1973 // The instantiation is visible here, even if it was first declared in an
1974 // unimported module.
1975 Instantiation->setHidden(false);
1976
1977 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00001978 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001979
John McCall76d824f2009-08-25 22:02:44 +00001980 // Do substitution on the base class specifiers.
1981 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001982 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001983
Douglas Gregor869853e2010-11-10 19:44:59 +00001984 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001985 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001986 // Delay instantiation of late parsed attributes.
1987 LateInstantiatedAttrVec LateAttrs;
1988 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1989
Aaron Ballman629afae2014-03-07 19:56:05 +00001990 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001991 // Don't instantiate members not belonging in this semantic context.
1992 // e.g. for:
1993 // @code
1994 // template <int i> class A {
1995 // class B *g;
1996 // };
1997 // @endcode
1998 // 'class B' has the template as lexical context but semantically it is
1999 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002000 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002001 continue;
2002
Aaron Ballman629afae2014-03-07 19:56:05 +00002003 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002004 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002005 continue;
2006 }
2007
Aaron Ballman629afae2014-03-07 19:56:05 +00002008 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002009 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002010 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002011 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002012 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2013 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2014 // specialization causes the implicit instantiation of the definitions
2015 // of unscoped member enumerations.
2016 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002017 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2018 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002019 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2020 assert(MSInfo && "no spec info for member enum specialization");
2021 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2022 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2023 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002024 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2025 if (SA->isFailed()) {
2026 // A static_assert failed. Bail out; instantiating this
2027 // class is probably not meaningful.
2028 Instantiation->setInvalidDecl();
2029 break;
2030 }
Richard Smith7d137e32012-03-23 03:33:32 +00002031 }
2032
2033 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002034 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002035 } else {
2036 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002037 // instantiations was a semantic disaster, and we'll want to mark the
2038 // declaration invalid.
2039 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002040 }
2041 }
2042
2043 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002044 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2045 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002046 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002047
Reid Kleckner93f661a2015-03-17 21:51:43 +00002048 // Default arguments are parsed, if not instantiated. We can go instantiate
2049 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002050 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002051
Reid Kleckner5b640342016-02-26 19:51:02 +00002052 // Put back the delayed exported classes that we moved out of the way.
2053 std::swap(ExportedClasses, DelayedDllExportClasses);
2054
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002055 // 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;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002061
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
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002069 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
Richard Smithd3b5c9082012-07-27 04:22:15 +00002078 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002079
Richard Smitha1087602014-03-10 00:04:29 +00002080 // FIXME: We should do something similar for explicit instantiations so they
2081 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002082 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002083 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002084 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002085 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002086 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002087
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002088 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002089 // Perform any dependent diagnostics from the pattern.
2090 PerformDependentDiagnostics(Pattern, TemplateArgs);
2091
Douglas Gregor869853e2010-11-10 19:44:59 +00002092 // Instantiate any out-of-line class template partial
2093 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002094 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002095 P = Instantiator.delayed_partial_spec_begin(),
2096 PEnd = Instantiator.delayed_partial_spec_end();
2097 P != PEnd; ++P) {
2098 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002099 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)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002113 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002114 break;
2115 }
2116 }
2117 }
2118
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002119 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002120 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002121
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002122 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002123 Consumer.HandleTagDeclDefinition(Instantiation);
2124
Douglas Gregor88d292c2010-05-13 16:44:06 +00002125 // 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
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002131 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002132}
2133
Richard Smith4b38ded2012-03-14 23:13:10 +00002134/// \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.
2149bool 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);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002168 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002169 return true;
2170
Richard Smitha1087602014-03-10 00:04:29 +00002171 // The instantiation is visible here, even if it was first declared in an
2172 // unimported module.
2173 Instantiation->setHidden(false);
2174
Richard Smith4b38ded2012-03-14 23:13:10 +00002175 // 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
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002195
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.
2210bool 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
Serge Pavlov907233f2015-04-28 17:58:47 +00002249 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002250
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
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002269namespace {
2270 /// \brief A partial specialization whose template arguments have matched
2271 /// a given template-id.
2272 struct PartialSpecMatchResult {
2273 ClassTemplatePartialSpecializationDecl *Partial;
2274 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002275 };
2276}
2277
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002278bool Sema::InstantiateClassTemplateSpecialization(
2279 SourceLocation PointOfInstantiation,
2280 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2281 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002282 // Perform the actual instantiation on the canonical declaration.
2283 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002284 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor00a511f2009-09-15 16:51:42 +00002285 if (ClassTemplateSpec->isInvalidDecl())
2286 return true;
2287
Douglas Gregor463421d2009-03-03 04:44:36 +00002288 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002289 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002290
Douglas Gregor170bc422009-06-12 22:31:52 +00002291 // 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.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002299 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002300 SmallVector<MatchResult, 4> Matched;
2301 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002302 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002303 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002304 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2305 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002306 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002307 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002308 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002309 ClassTemplateSpec->getTemplateArgs(),
2310 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002311 // 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));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002315 (void)Result;
2316 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002317 Matched.push_back(PartialSpecMatchResult());
2318 Matched.back().Partial = Partial;
2319 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002320 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002321 }
2322
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002323 // 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.
Alp Toker965f8822013-11-27 05:22:15 +00002326
Douglas Gregor21610382009-10-29 00:04:11 +00002327 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002328 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002329 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.
Craig Topper2341c0d2013-07-04 03:08:24 +00002341 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2342 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002343 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002344 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002345 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002346 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002347 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002348 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002349
Douglas Gregor21610382009-10-29 00:04:11 +00002350 // Determine if the best partial specialization is more specialized than
2351 // the others.
2352 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002353 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2354 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002355 P != PEnd; ++P) {
2356 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002357 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002358 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002359 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002360 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.
Craig Topper2341c0d2013-07-04 03:08:24 +00002372 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2373 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002374 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002375 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2376 << getTemplateArgumentBindingsText(
2377 P->Partial->getTemplateParameters(),
2378 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002379
Douglas Gregor21610382009-10-29 00:04:11 +00002380 return true;
2381 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002382 }
2383
2384 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002385 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002386 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;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002396 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002397 } else {
2398 // -- If no matches are found, the instantiation is generated
2399 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002400 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002401 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
Douglas Gregor01afeef2009-08-28 20:31:08 +00002407 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002408 }
2409
Douglas Gregor01afeef2009-08-28 20:31:08 +00002410 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002411 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002412
Douglas Gregoref6ab412009-10-27 06:26:26 +00002413 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2414 Pattern,
2415 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002416 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002417 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002418
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002419 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002420}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002421
John McCall76d824f2009-08-25 22:02:44 +00002422/// \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.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002425void
2426Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002427 CXXRecordDecl *Instantiation,
2428 const MultiLevelTemplateArgumentList &TemplateArgs,
2429 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002430 // 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.
David Majnemer192d1792013-11-27 08:20:38 +00002433 assert(
2434 (TSK == TSK_ExplicitInstantiationDefinition ||
2435 TSK == TSK_ExplicitInstantiationDeclaration ||
2436 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2437 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002438 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002439 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002440 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002441 if (FunctionDecl *Pattern
2442 = Function->getInstantiatedFromMemberFunction()) {
2443 MemberSpecializationInfo *MSInfo
2444 = Function->getMemberSpecializationInfo();
2445 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002446 if (MSInfo->getTemplateSpecializationKind()
2447 == TSK_ExplicitSpecialization)
2448 continue;
2449
Douglas Gregor1d957a32009-10-27 18:42:08 +00002450 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2451 Function,
2452 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002453 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002454 SuppressNew) ||
2455 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002456 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002457
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())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002465 continue;
2466
Richard Smitheb36ddf2014-04-24 22:45:46 +00002467 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) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002474 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002475 } else if (TSK == TSK_ImplicitInstantiation) {
2476 PendingLocalImplicitInstantiations.push_back(
2477 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002478 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002479 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002480 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002481 if (isa<VarTemplateSpecializationDecl>(Var))
2482 continue;
2483
Douglas Gregor86d142a2009-10-08 07:24:58 +00002484 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002485 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2486 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002487 if (MSInfo->getTemplateSpecializationKind()
2488 == TSK_ExplicitSpecialization)
2489 continue;
2490
Douglas Gregor1d957a32009-10-27 18:42:08 +00002491 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2492 Var,
2493 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002494 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002495 SuppressNew) ||
2496 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002497 continue;
2498
Douglas Gregor1d957a32009-10-27 18:42:08 +00002499 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);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002511 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002512 } else {
2513 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2514 }
2515 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002516 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002517 // 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.
Richard Smith069ecf62014-11-20 22:56:34 +00002520 // Skip closure types; they'll get instantiated when we instantiate
2521 // the corresponding lambda-expression.
2522 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2523 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002524 continue;
2525
Douglas Gregor1d957a32009-10-27 18:42:08 +00002526 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2527 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002528
2529 if (MSInfo->getTemplateSpecializationKind()
2530 == TSK_ExplicitSpecialization)
2531 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002532
Douglas Gregor1d957a32009-10-27 18:42:08 +00002533 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2534 Record,
2535 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002536 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002537 SuppressNew) ||
2538 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002539 continue;
2540
Douglas Gregor1d957a32009-10-27 18:42:08 +00002541 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2542 assert(Pattern && "Missing instantiated-from-template information");
2543
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002544 if (!Record->getDefinition()) {
2545 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002546 // 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,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002561 TemplateArgs,
2562 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002563 } else {
2564 if (TSK == TSK_ExplicitInstantiationDefinition &&
2565 Record->getTemplateSpecializationKind() ==
2566 TSK_ExplicitInstantiationDeclaration) {
2567 Record->setTemplateSpecializationKind(TSK);
2568 MarkVTableUsed(PointOfInstantiation, Record, true);
2569 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002570 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002571
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002572 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002573 if (Pattern)
2574 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2575 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002576 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002577 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 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002606 } 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 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002619 }
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.
Mike Stump11289f42009-09-09 15:08:12 +00002626void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002627Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002628 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002629 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2630 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002631 // 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,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002640 getTemplateInstantiationArgs(ClassTemplateSpec),
2641 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002642}
2643
John McCalldadc5752010-08-24 06:29:42 +00002644StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002645Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002646 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002647 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002648
2649 TemplateInstantiator Instantiator(*this, TemplateArgs,
2650 SourceLocation(),
2651 DeclarationName());
2652 return Instantiator.TransformStmt(S);
2653}
2654
John McCalldadc5752010-08-24 06:29:42 +00002655ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002656Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002657 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002658 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002659
Douglas Gregora16548e2009-08-11 05:31:07 +00002660 TemplateInstantiator Instantiator(*this, TemplateArgs,
2661 SourceLocation(),
2662 DeclarationName());
2663 return Instantiator.TransformExpr(E);
2664}
2665
Richard Smithd59b8322012-12-19 01:39:02 +00002666ExprResult 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
Craig Topper99d23532015-12-24 23:58:29 +00002675bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002676 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002677 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002678 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002679 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002680
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002681 TemplateInstantiator Instantiator(*this, TemplateArgs,
2682 SourceLocation(),
2683 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002684 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2685 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002686}
2687
Douglas Gregor14454802011-02-25 02:25:35 +00002688NestedNameSpecifierLoc
2689Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2690 const MultiLevelTemplateArgumentList &TemplateArgs) {
2691 if (!NNS)
2692 return NestedNameSpecifierLoc();
2693
2694 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2695 DeclarationName());
2696 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2697}
2698
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002699/// \brief Do template substitution on declaration name info.
2700DeclarationNameInfo
2701Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2702 const MultiLevelTemplateArgumentList &TemplateArgs) {
2703 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2704 NameInfo.getName());
2705 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2706}
2707
Douglas Gregoraa594892009-03-31 18:38:02 +00002708TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002709Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2710 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002711 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002712 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2713 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002714 CXXScopeSpec SS;
2715 SS.Adopt(QualifierLoc);
2716 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002717}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002718
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002719bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2720 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002721 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002722 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2723 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002724
2725 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002726}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002727
Richard Smith70b13042015-01-09 01:19:56 +00002728static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002729 // When storing ParmVarDecls in the local instantiation scope, we always
2730 // want to use the ParmVarDecl from the canonical function declaration,
2731 // since the map is then valid for any redeclaration or definition of that
2732 // function.
2733 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2734 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2735 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002736 // This parameter might be from a freestanding function type within the
2737 // function and isn't necessarily referring to one of FD's parameters.
2738 if (FD->getParamDecl(i) == PV)
2739 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002740 }
2741 }
2742 return D;
2743}
2744
2745
Douglas Gregorf3010112011-01-07 16:43:16 +00002746llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2747LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002748 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002749 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002750 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002751
Douglas Gregor14cf7522010-04-30 18:55:50 +00002752 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002753 const Decl *CheckD = D;
2754 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002755 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002756 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002757 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002758
2759 // If this is a tag declaration, it's possible that we need to look for
2760 // a previous declaration.
2761 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002762 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002763 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002764 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002765 } while (CheckD);
2766
Douglas Gregor14cf7522010-04-30 18:55:50 +00002767 // If we aren't combined with our outer scope, we're done.
2768 if (!Current->CombineWithOuterScope)
2769 break;
2770 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002771
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002772 // If we're performing a partial substitution during template argument
2773 // deduction, we may not have values for template parameters yet.
2774 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2775 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002776 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002777
Serge Pavlove7ad8312015-05-15 10:10:28 +00002778 // Local types referenced prior to definition may require instantiation.
2779 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2780 if (RD->isLocalClass())
2781 return nullptr;
2782
2783 // Enumeration types referenced prior to definition may appear as a result of
2784 // error recovery.
2785 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002786 return nullptr;
2787
Chris Lattnercab02a62011-02-17 20:34:02 +00002788 // If we didn't find the decl, then we either have a sema bug, or we have a
2789 // forward reference to a label declaration. Return null to indicate that
2790 // we have an uninstantiated label.
2791 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002792 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002793}
2794
John McCall19c1bfd2010-08-25 05:32:35 +00002795void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002796 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002797 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002798 if (Stored.isNull()) {
2799#ifndef NDEBUG
2800 // It should not be present in any surrounding scope either.
2801 LocalInstantiationScope *Current = this;
2802 while (Current->CombineWithOuterScope && Current->Outer) {
2803 Current = Current->Outer;
2804 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2805 "Instantiated local in inner and outer scopes");
2806 }
2807#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002808 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002809 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002810 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002811 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002812 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002813 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002814}
Douglas Gregorf3010112011-01-07 16:43:16 +00002815
James Y Knight48fefa32015-09-30 14:04:23 +00002816void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2817 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002818 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002819 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2820 Pack->push_back(Inst);
2821}
2822
2823void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002824#ifndef NDEBUG
2825 // This should be the first time we've been told about this decl.
2826 for (LocalInstantiationScope *Current = this;
2827 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2828 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2829 "Creating local pack after instantiation of local");
2830#endif
2831
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002832 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002833 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002834 DeclArgumentPack *Pack = new DeclArgumentPack;
2835 Stored = Pack;
2836 ArgumentPacks.push_back(Pack);
2837}
2838
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002839void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2840 const TemplateArgument *ExplicitArgs,
2841 unsigned NumExplicitArgs) {
2842 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2843 "Already have a partially-substituted pack");
2844 assert((!PartiallySubstitutedPack
2845 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2846 "Wrong number of arguments in partially-substituted pack");
2847 PartiallySubstitutedPack = Pack;
2848 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2849 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2850}
2851
2852NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2853 const TemplateArgument **ExplicitArgs,
2854 unsigned *NumExplicitArgs) const {
2855 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002856 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002857 if (NumExplicitArgs)
2858 *NumExplicitArgs = 0;
2859
2860 for (const LocalInstantiationScope *Current = this; Current;
2861 Current = Current->Outer) {
2862 if (Current->PartiallySubstitutedPack) {
2863 if (ExplicitArgs)
2864 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2865 if (NumExplicitArgs)
2866 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2867
2868 return Current->PartiallySubstitutedPack;
2869 }
2870
2871 if (!Current->CombineWithOuterScope)
2872 break;
2873 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002874
2875 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002876}