blob: 4749962d04534803b5a593582fed0397c19b32d4 [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"
Richard Smith4b054b22016-08-24 21:25:37 +000018#include "clang/AST/ASTMutationListener.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/Basic/LangOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000022#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000023#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000024#include "clang/Sema/Lookup.h"
Richard Smithe19b95d2016-05-26 20:23:13 +000025#include "clang/Sema/PrettyDeclStackTrace.h"
John McCallde6836a2010-08-24 07:21:54 +000026#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000027#include "clang/Sema/TemplateDeduction.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000028
29using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000030using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000031
Douglas Gregor4ea568f2009-03-10 18:03:33 +000032//===----------------------------------------------------------------------===/
33// Template Instantiation Support
34//===----------------------------------------------------------------------===/
35
Douglas Gregor01afeef2009-08-28 20:31:08 +000036/// \brief Retrieve the template argument list(s) that should be used to
37/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000038///
39/// \param D the declaration for which we are computing template instantiation
40/// arguments.
41///
42/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000043///
44/// \param RelativeToPrimary true if we should get the template
45/// arguments relative to the primary template, even when we're
46/// dealing with a specialization. This is only relevant for function
47/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000048///
49/// \param Pattern If non-NULL, indicates the pattern from which we will be
50/// instantiating the definition of the given declaration, \p D. This is
51/// used to determine the proper set of template instantiation arguments for
52/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000053MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000054Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000055 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000056 bool RelativeToPrimary,
57 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000058 // Accumulate the set of template argument lists in this structure.
59 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000061 if (Innermost)
62 Result.addOuterTemplateArguments(Innermost);
63
Douglas Gregora654dd82009-08-28 17:37:35 +000064 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000065 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000066 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000067
68 // Add template arguments from a variable template instantiation.
69 if (VarTemplateSpecializationDecl *Spec =
70 dyn_cast<VarTemplateSpecializationDecl>(D)) {
71 // We're done when we hit an explicit specialization.
72 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
73 !isa<VarTemplatePartialSpecializationDecl>(Spec))
74 return Result;
75
76 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
77
78 // If this variable template specialization was instantiated from a
79 // specialized member that is a variable template, we're done.
80 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000081 llvm::PointerUnion<VarTemplateDecl*,
82 VarTemplatePartialSpecializationDecl*> Specialized
83 = Spec->getSpecializedTemplateOrPartial();
84 if (VarTemplatePartialSpecializationDecl *Partial =
85 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
86 if (Partial->isMemberSpecialization())
87 return Result;
88 } else {
89 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
90 if (Tmpl->isMemberSpecialization())
91 return Result;
92 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000093 }
94
Douglas Gregor55462622011-06-15 14:20:42 +000095 // If we have a template template parameter with translation unit context,
96 // then we're performing substitution into a default template argument of
97 // this template template parameter before we've constructed the template
98 // that will own this template template parameter. In this case, we
99 // use empty template parameter lists for all of the outer templates
100 // to avoid performing any substitutions.
101 if (Ctx->isTranslationUnit()) {
102 if (TemplateTemplateParmDecl *TTP
103 = dyn_cast<TemplateTemplateParmDecl>(D)) {
104 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000105 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000106 return Result;
107 }
108 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000109 }
110
John McCall970d5302009-08-29 03:16:09 +0000111 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000112 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +0000113 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +0000114 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
115 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000116 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
117 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000118 break;
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregora654dd82009-08-28 17:37:35 +0000120 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000121
122 // If this class template specialization was instantiated from a
123 // specialized member that is a class template, we're done.
124 assert(Spec->getSpecializedTemplate() && "No class template?");
125 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
126 break;
Mike Stump11289f42009-09-09 15:08:12 +0000127 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000128 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000129 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000130 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000131 (Function->getTemplateSpecializationKind() ==
132 TSK_ExplicitSpecialization &&
133 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000134 break;
135
Douglas Gregora654dd82009-08-28 17:37:35 +0000136 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000137 = Function->getTemplateSpecializationArgs()) {
138 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000139 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000140
Douglas Gregorcf915552009-10-13 16:30:37 +0000141 // If this function was instantiated from a specialized member that is
142 // a function template, we're done.
143 assert(Function->getPrimaryTemplate() && "No function template?");
144 if (Function->getPrimaryTemplate()->isMemberSpecialization())
145 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000146
147 // If this function is a generic lambda specialization, we are done.
148 if (isGenericLambdaCallOperatorSpecialization(Function))
149 break;
150
Douglas Gregor43669f82011-03-05 17:54:25 +0000151 } else if (FunctionTemplateDecl *FunTmpl
152 = Function->getDescribedFunctionTemplate()) {
153 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000154 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000155 }
156
John McCall970d5302009-08-29 03:16:09 +0000157 // If this is a friend declaration and it declares an entity at
158 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000159 // instead of its semantic parent, unless of course the pattern we're
160 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000161 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000162 Function->getDeclContext()->isFileContext() &&
163 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000164 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000165 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000166 continue;
167 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000168 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
169 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
170 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000171 const TemplateSpecializationType *TST =
172 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
173 Result.addOuterTemplateArguments(
174 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000175 if (ClassTemplate->isMemberSpecialization())
176 break;
177 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000178 }
John McCall970d5302009-08-29 03:16:09 +0000179
180 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000181 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000182 }
Mike Stump11289f42009-09-09 15:08:12 +0000183
Douglas Gregora654dd82009-08-28 17:37:35 +0000184 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000185}
186
Douglas Gregor84d49a22009-11-11 21:54:23 +0000187bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
188 switch (Kind) {
189 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000190 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000191 case DefaultTemplateArgumentInstantiation:
192 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000193 case ExplicitTemplateArgumentSubstitution:
194 case DeducedTemplateArgumentSubstitution:
195 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000196 return true;
197
Douglas Gregor84d49a22009-11-11 21:54:23 +0000198 case DefaultTemplateArgumentChecking:
199 return false;
200 }
David Blaikie8a40f702012-01-17 06:56:22 +0000201
202 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000203}
204
Benjamin Kramer7761a042015-03-06 16:36:50 +0000205Sema::InstantiatingTemplate::InstantiatingTemplate(
206 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000207 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
208 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000209 sema::TemplateDeductionInfo *DeductionInfo)
210 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
211 SemaRef.InNonInstantiationSFINAEContext) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000212 // Don't allow further instantiation if a fatal error has occcured. Any
213 // diagnostics we might have raised will not be visible.
214 if (SemaRef.Diags.hasFatalErrorOccurred()) {
215 Invalid = true;
216 return;
217 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000218 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
219 if (!Invalid) {
220 ActiveTemplateInstantiation Inst;
221 Inst.Kind = Kind;
222 Inst.PointOfInstantiation = PointOfInstantiation;
223 Inst.Entity = Entity;
224 Inst.Template = Template;
225 Inst.TemplateArgs = TemplateArgs.data();
226 Inst.NumTemplateArgs = TemplateArgs.size();
227 Inst.DeductionInfo = DeductionInfo;
228 Inst.InstantiationRange = InstantiationRange;
229 SemaRef.InNonInstantiationSFINAEContext = false;
230 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
231 if (!Inst.isInstantiationRecord())
232 ++SemaRef.NonInstantiationEntries;
233 }
234}
235
Benjamin Kramer7761a042015-03-06 16:36:50 +0000236Sema::InstantiatingTemplate::InstantiatingTemplate(
237 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
238 SourceRange InstantiationRange)
239 : InstantiatingTemplate(SemaRef,
240 ActiveTemplateInstantiation::TemplateInstantiation,
241 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000242
Benjamin Kramer7761a042015-03-06 16:36:50 +0000243Sema::InstantiatingTemplate::InstantiatingTemplate(
244 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
245 ExceptionSpecification, SourceRange InstantiationRange)
246 : InstantiatingTemplate(
247 SemaRef, ActiveTemplateInstantiation::ExceptionSpecInstantiation,
248 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000249
Benjamin Kramer7761a042015-03-06 16:36:50 +0000250Sema::InstantiatingTemplate::InstantiatingTemplate(
251 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
252 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
253 : InstantiatingTemplate(
254 SemaRef,
255 ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
256 PointOfInstantiation, InstantiationRange, Template, nullptr,
257 TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000258
Benjamin Kramer7761a042015-03-06 16:36:50 +0000259Sema::InstantiatingTemplate::InstantiatingTemplate(
260 Sema &SemaRef, SourceLocation PointOfInstantiation,
261 FunctionTemplateDecl *FunctionTemplate,
262 ArrayRef<TemplateArgument> TemplateArgs,
263 ActiveTemplateInstantiation::InstantiationKind Kind,
264 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
265 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
266 InstantiationRange, FunctionTemplate, nullptr,
267 TemplateArgs, &DeductionInfo) {}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000268
Benjamin Kramer7761a042015-03-06 16:36:50 +0000269Sema::InstantiatingTemplate::InstantiatingTemplate(
270 Sema &SemaRef, SourceLocation PointOfInstantiation,
271 ClassTemplatePartialSpecializationDecl *PartialSpec,
272 ArrayRef<TemplateArgument> TemplateArgs,
273 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
274 : InstantiatingTemplate(
275 SemaRef,
276 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
277 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
278 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000279
Larisse Voufo39a1e502013-08-06 01:03:05 +0000280Sema::InstantiatingTemplate::InstantiatingTemplate(
281 Sema &SemaRef, SourceLocation PointOfInstantiation,
282 VarTemplatePartialSpecializationDecl *PartialSpec,
283 ArrayRef<TemplateArgument> TemplateArgs,
284 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000285 : InstantiatingTemplate(
286 SemaRef,
287 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
288 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
289 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000290
Benjamin Kramer7761a042015-03-06 16:36:50 +0000291Sema::InstantiatingTemplate::InstantiatingTemplate(
292 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
293 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
294 : InstantiatingTemplate(
295 SemaRef,
296 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
297 PointOfInstantiation, InstantiationRange, Param, nullptr,
298 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000299
Benjamin Kramer7761a042015-03-06 16:36:50 +0000300Sema::InstantiatingTemplate::InstantiatingTemplate(
301 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
302 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
303 SourceRange InstantiationRange)
304 : InstantiatingTemplate(
305 SemaRef,
306 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
307 PointOfInstantiation, InstantiationRange, Param, Template,
308 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000309
Benjamin Kramer7761a042015-03-06 16:36:50 +0000310Sema::InstantiatingTemplate::InstantiatingTemplate(
311 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
312 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
313 SourceRange InstantiationRange)
314 : InstantiatingTemplate(
315 SemaRef,
316 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
317 PointOfInstantiation, InstantiationRange, Param, Template,
318 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000319
Benjamin Kramer7761a042015-03-06 16:36:50 +0000320Sema::InstantiatingTemplate::InstantiatingTemplate(
321 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
322 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
323 SourceRange InstantiationRange)
324 : InstantiatingTemplate(
325 SemaRef, ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
326 PointOfInstantiation, InstantiationRange, Param, Template,
327 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000328
Douglas Gregor85673582009-05-18 17:01:57 +0000329void Sema::InstantiatingTemplate::Clear() {
330 if (!Invalid) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000331 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
332 assert(SemaRef.NonInstantiationEntries > 0);
333 --SemaRef.NonInstantiationEntries;
334 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000335 SemaRef.InNonInstantiationSFINAEContext
336 = SavedInNonInstantiationSFINAEContext;
Richard Smith0e5d7b82013-07-25 23:08:39 +0000337
338 // Name lookup no longer looks in this template's defining module.
339 assert(SemaRef.ActiveTemplateInstantiations.size() >=
340 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
341 "forgot to remove a lookup module for a template instantiation");
342 if (SemaRef.ActiveTemplateInstantiations.size() ==
343 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
344 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
345 SemaRef.LookupModulesCache.erase(M);
346 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
347 }
348
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000349 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000350 Invalid = true;
351 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000352}
353
Douglas Gregor79cf6032009-03-10 20:44:00 +0000354bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
355 SourceLocation PointOfInstantiation,
356 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000357 assert(SemaRef.NonInstantiationEntries <=
358 SemaRef.ActiveTemplateInstantiations.size());
359 if ((SemaRef.ActiveTemplateInstantiations.size() -
360 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000361 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000362 return false;
363
Mike Stump11289f42009-09-09 15:08:12 +0000364 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000365 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000366 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000367 << InstantiationRange;
368 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000369 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000370 return true;
371}
372
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000373/// \brief Prints the current instantiation stack through a series of
374/// notes.
375void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000376 // Determine which template instantiations to skip, if any.
377 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
378 unsigned Limit = Diags.getTemplateBacktraceLimit();
379 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
380 SkipStart = Limit / 2 + Limit % 2;
381 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
382 }
383
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000384 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000385 unsigned InstantiationIdx = 0;
Craig Topper2341c0d2013-07-04 03:08:24 +0000386 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000387 Active = ActiveTemplateInstantiations.rbegin(),
388 ActiveEnd = ActiveTemplateInstantiations.rend();
389 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000390 ++Active, ++InstantiationIdx) {
391 // Skip this instantiation?
392 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
393 if (InstantiationIdx == SkipStart) {
394 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000395 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000396 diag::note_instantiation_contexts_suppressed)
397 << unsigned(ActiveTemplateInstantiations.size() - Limit);
398 }
399 continue;
400 }
401
Douglas Gregor79cf6032009-03-10 20:44:00 +0000402 switch (Active->Kind) {
403 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000404 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000405 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
406 unsigned DiagID = diag::note_template_member_class_here;
407 if (isa<ClassTemplateSpecializationDecl>(Record))
408 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000409 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000410 << Context.getTypeDeclType(Record)
411 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000412 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000413 unsigned DiagID;
414 if (Function->getPrimaryTemplate())
415 DiagID = diag::note_function_template_spec_here;
416 else
417 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000418 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000419 << Function
420 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000421 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000422 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000423 VD->isStaticDataMember()?
424 diag::note_template_static_data_member_def_here
425 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000426 << VD
427 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000428 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
429 Diags.Report(Active->PointOfInstantiation,
430 diag::note_template_enum_def_here)
431 << ED
432 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000433 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
434 Diags.Report(Active->PointOfInstantiation,
435 diag::note_template_nsdmi_here)
436 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000437 } else {
438 Diags.Report(Active->PointOfInstantiation,
439 diag::note_template_type_alias_instantiation_here)
440 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000441 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000442 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000443 break;
444 }
445
446 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000447 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000448 SmallVector<char, 128> TemplateArgsStr;
449 llvm::raw_svector_ostream OS(TemplateArgsStr);
450 Template->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000451 TemplateSpecializationType::PrintTemplateArgumentList(
452 OS, Active->template_arguments(), 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);
David Majnemer6fbeee32016-07-07 04:43:07 +0000503 TemplateSpecializationType::PrintTemplateArgumentList(
504 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000505 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000506 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000507 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000508 << Active->InstantiationRange;
509 break;
510 }
Mike Stump11289f42009-09-09 15:08:12 +0000511
Douglas Gregore62e6a02009-11-11 19:13:48 +0000512 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000513 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000514 std::string Name;
515 if (!Parm->getName().empty())
516 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000517
518 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000519 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
520 TemplateParams = Template->getTemplateParameters();
521 else
522 TemplateParams =
523 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
524 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000525 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000526 diag::note_prior_template_arg_substitution)
527 << isa<TemplateTemplateParmDecl>(Parm)
528 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000529 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000530 Active->TemplateArgs,
531 Active->NumTemplateArgs)
532 << Active->InstantiationRange;
533 break;
534 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000535
536 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000537 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000538 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
539 TemplateParams = Template->getTemplateParameters();
540 else
541 TemplateParams =
542 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
543 ->getTemplateParameters();
544
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000545 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000546 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000547 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000548 Active->TemplateArgs,
549 Active->NumTemplateArgs)
550 << Active->InstantiationRange;
551 break;
552 }
Richard Smithf623c962012-04-17 00:58:00 +0000553
554 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
555 Diags.Report(Active->PointOfInstantiation,
556 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000557 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000558 << Active->InstantiationRange;
559 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000560 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000561 }
562}
563
David Blaikie05785d12013-02-20 22:23:23 +0000564Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000565 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000566 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000567
Craig Topper2341c0d2013-07-04 03:08:24 +0000568 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor33834512009-06-14 07:33:30 +0000569 Active = ActiveTemplateInstantiations.rbegin(),
570 ActiveEnd = ActiveTemplateInstantiations.rend();
571 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000572 ++Active)
573 {
Douglas Gregor33834512009-06-14 07:33:30 +0000574 switch(Active->Kind) {
Douglas Gregoredb76852011-01-27 22:31:44 +0000575 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000576 // An instantiation of an alias template may or may not be a SFINAE
577 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000578 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000579 break;
580 // Fall through.
581 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000582 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000583 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000584 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000585
Douglas Gregor33834512009-06-14 07:33:30 +0000586 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000587 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000588 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000589 // A default template argument instantiation and substitution into
590 // template parameters with arguments for prior parameters may or may
591 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000592 break;
Mike Stump11289f42009-09-09 15:08:12 +0000593
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000594 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
595 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
596 // We're either substitution explicitly-specified template arguments
597 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000598 assert(Active->DeductionInfo && "Missing deduction info pointer");
599 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000600 }
601 }
602
David Blaikie7a30dc52013-02-21 01:47:18 +0000603 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000604}
605
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000606/// \brief Retrieve the depth and index of a parameter pack.
607static std::pair<unsigned, unsigned>
608getDepthAndIndex(NamedDecl *ND) {
609 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
610 return std::make_pair(TTP->getDepth(), TTP->getIndex());
611
612 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
613 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
614
615 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
616 return std::make_pair(TTP->getDepth(), TTP->getIndex());
617}
618
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000619//===----------------------------------------------------------------------===/
620// Template Instantiation for Types
621//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000622namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000623 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000624 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000625 SourceLocation Loc;
626 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000627
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000628 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000629 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000630
631 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000632 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000633 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000634 DeclarationName Entity)
635 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000636 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000637
Mike Stump11289f42009-09-09 15:08:12 +0000638 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000639 /// transformed.
640 ///
641 /// For the purposes of template instantiation, a type has already been
642 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000643 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000644
Douglas Gregord6ff3322009-08-04 16:50:30 +0000645 /// \brief Returns the location of the entity being instantiated, if known.
646 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000647
Douglas Gregord6ff3322009-08-04 16:50:30 +0000648 /// \brief Returns the name of the entity being instantiated, if any.
649 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000650
Douglas Gregoref6ab412009-10-27 06:26:26 +0000651 /// \brief Sets the "base" location and entity when that
652 /// information is known based on another transformation.
653 void setBase(SourceLocation Loc, DeclarationName Entity) {
654 this->Loc = Loc;
655 this->Entity = Entity;
656 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000657
658 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
659 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000660 ArrayRef<UnexpandedParameterPack> Unexpanded,
661 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000662 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000663 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
664 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000665 TemplateArgs,
666 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000667 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000668 NumExpansions);
669 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000670
Douglas Gregorf3010112011-01-07 16:43:16 +0000671 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
672 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
673 }
674
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000675 TemplateArgument ForgetPartiallySubstitutedPack() {
676 TemplateArgument Result;
677 if (NamedDecl *PartialPack
678 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
679 MultiLevelTemplateArgumentList &TemplateArgs
680 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
681 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000682 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000683 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
684 Result = TemplateArgs(Depth, Index);
685 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
686 }
687 }
688
689 return Result;
690 }
691
692 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
693 if (Arg.isNull())
694 return;
695
696 if (NamedDecl *PartialPack
697 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
698 MultiLevelTemplateArgumentList &TemplateArgs
699 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
700 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000701 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000702 TemplateArgs.setArgument(Depth, Index, Arg);
703 }
704 }
705
Douglas Gregord6ff3322009-08-04 16:50:30 +0000706 /// \brief Transform the given declaration by instantiating a reference to
707 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000708 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000709
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000710 void transformAttrs(Decl *Old, Decl *New) {
711 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
712 }
713
714 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000715 // If we've instantiated the call operator of a lambda or the call
716 // operator template of a generic lambda, update the "instantiation of"
717 // information.
718 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
719 if (NewMD && isLambdaCallOperator(NewMD)) {
720 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
721 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
722 NewTD->setInstantiatedFromMemberTemplate(
723 OldMD->getDescribedFunctionTemplate());
724 else
725 NewMD->setInstantiationOfMemberFunction(OldMD,
726 TSK_ImplicitInstantiation);
727 }
728
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000729 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000730
731 // We recreated a local declaration, but not by instantiating it. There
732 // may be pending dependent diagnostics to produce.
733 if (auto *DC = dyn_cast<DeclContext>(Old))
734 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000735 }
736
Mike Stump11289f42009-09-09 15:08:12 +0000737 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000738 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000739 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000740
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000741 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000742 /// declaration.
743 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
744
Douglas Gregorebe10102009-08-20 07:17:43 +0000745 /// \brief Rebuild the exception declaration and register the declaration
746 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000747 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000748 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000749 SourceLocation StartLoc,
750 SourceLocation NameLoc,
751 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000752
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000753 /// \brief Rebuild the Objective-C exception declaration and register the
754 /// declaration as an instantiated local.
755 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
756 TypeSourceInfo *TSInfo, QualType T);
757
John McCall7f41d982009-09-11 04:59:25 +0000758 /// \brief Check for tag mismatches when instantiating an
759 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000760 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
761 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000762 NestedNameSpecifierLoc QualifierLoc,
763 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000764
Craig Topperc3ec1492014-05-26 06:22:03 +0000765 TemplateName
766 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
767 SourceLocation NameLoc,
768 QualType ObjectType = QualType(),
769 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregor9db53502011-03-02 18:07:45 +0000770
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000771 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
772
John McCalldadc5752010-08-24 06:29:42 +0000773 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
774 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
775 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000776
John McCalldadc5752010-08-24 06:29:42 +0000777 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000778 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000779 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
780 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000781
782 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
783 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
784
785 /// \brief Transform a reference to a function parameter pack.
786 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
787 ParmVarDecl *PD);
788
789 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
790 /// expand a function parameter pack reference which refers to an expanded
791 /// pack.
792 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
793
Hans Wennborge113c202014-09-18 16:01:32 +0000794 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000795 FunctionProtoTypeLoc TL) {
796 // Call the base version; it will forward to our overridden version below.
797 return inherited::TransformFunctionProtoType(TLB, TL);
798 }
799
800 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000801 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
802 FunctionProtoTypeLoc TL,
803 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000804 unsigned ThisTypeQuals,
805 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000806
Douglas Gregor715e4612011-01-14 22:40:04 +0000807 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000808 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000809 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000810 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000811
Mike Stump11289f42009-09-09 15:08:12 +0000812 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000813 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000814 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000815 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000816
Douglas Gregorada4b792011-01-14 02:55:32 +0000817 /// \brief Transforms an already-substituted template type parameter pack
818 /// into either itself (if we aren't substituting into its pack expansion)
819 /// or the appropriate substituted argument.
820 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
821 SubstTemplateTypeParmPackTypeLoc TL);
822
Richard Smith2589b9802012-07-25 03:56:55 +0000823 ExprResult TransformLambdaExpr(LambdaExpr *E) {
824 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
825 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
826 }
827
David Majnemerb1004102014-03-02 18:46:05 +0000828 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000829 TemplateParameterList *OrigTPL) {
830 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
831
832 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
833 TemplateDeclInstantiator DeclInstantiator(getSema(),
834 /* DeclContext *Owner */ Owner, TemplateArgs);
835 return DeclInstantiator.SubstTemplateParams(OrigTPL);
836 }
John McCall7c454bb2011-07-15 05:09:51 +0000837 private:
838 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
839 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000840 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000841 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000842}
Douglas Gregor04318252009-07-06 15:59:29 +0000843
Douglas Gregor5597ab42010-05-07 23:12:07 +0000844bool TemplateInstantiator::AlreadyTransformed(QualType T) {
845 if (T.isNull())
846 return true;
847
Douglas Gregor678d76c2011-07-01 01:22:09 +0000848 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000849 return false;
850
851 getSema().MarkDeclarationsReferencedInType(Loc, T);
852 return true;
853}
854
Eli Friedman8917ad52013-07-19 19:40:38 +0000855static TemplateArgument
856getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
857 assert(S.ArgumentPackSubstitutionIndex >= 0);
858 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
859 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
860 if (Arg.isPackExpansion())
861 Arg = Arg.getPackExpansionPattern();
862 return Arg;
863}
864
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000865Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000866 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000867 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000868
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000869 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000870 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000871 // If the corresponding template argument is NULL or non-existent, it's
872 // because we are performing instantiation from explicitly-specified
873 // template arguments in a function template, but there were some
874 // arguments left unspecified.
875 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
876 TTP->getPosition()))
877 return D;
878
Douglas Gregorf5500772011-01-05 15:48:55 +0000879 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
880
881 if (TTP->isParameterPack()) {
882 assert(Arg.getKind() == TemplateArgument::Pack &&
883 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000884 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000885 }
886
887 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000888 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000889 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000890 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000891 }
Mike Stump11289f42009-09-09 15:08:12 +0000892
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000893 // Fall through to find the instantiated declaration for this template
894 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000895 }
Mike Stump11289f42009-09-09 15:08:12 +0000896
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000897 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000898}
899
Douglas Gregor25289362010-03-01 17:25:41 +0000900Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000901 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000902 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000903 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000904
Douglas Gregorebe10102009-08-20 07:17:43 +0000905 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
906 return Inst;
907}
908
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000909NamedDecl *
910TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
911 SourceLocation Loc) {
912 // If the first part of the nested-name-specifier was a template type
913 // parameter, instantiate that type parameter down to a tag type.
914 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
915 const TemplateTypeParmType *TTP
916 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000917
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000918 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000919 // FIXME: This needs testing w/ member access expressions.
920 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
921
922 if (TTP->isParameterPack()) {
923 assert(Arg.getKind() == TemplateArgument::Pack &&
924 "Missing argument pack");
925
Douglas Gregore1d60df2011-01-14 23:41:42 +0000926 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +0000927 return nullptr;
928
Eli Friedman8917ad52013-07-19 19:40:38 +0000929 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000930 }
931
932 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000933 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000934 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000935
936 if (const TagType *Tag = T->getAs<TagType>())
937 return Tag->getDecl();
938
939 // The resulting type is not a tag; complain.
940 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +0000941 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000942 }
943 }
944
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000945 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000946}
947
Douglas Gregorebe10102009-08-20 07:17:43 +0000948VarDecl *
949TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000950 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000951 SourceLocation StartLoc,
952 SourceLocation NameLoc,
953 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000954 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000955 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000956 if (Var)
957 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
958 return Var;
959}
960
961VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
962 TypeSourceInfo *TSInfo,
963 QualType T) {
964 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
965 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000966 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
967 return Var;
968}
969
John McCall7f41d982009-09-11 04:59:25 +0000970QualType
John McCall954b5de2010-11-04 19:04:38 +0000971TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
972 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000973 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000974 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +0000975 if (const TagType *TT = T->getAs<TagType>()) {
976 TagDecl* TD = TT->getDecl();
977
John McCall954b5de2010-11-04 19:04:38 +0000978 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +0000979
John McCall7f41d982009-09-11 04:59:25 +0000980 IdentifierInfo *Id = TD->getIdentifier();
981
982 // TODO: should we even warn on struct/class mismatches for this? Seems
983 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +0000984 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000985 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +0000986 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +0000987 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000988 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
989 << Id
990 << FixItHint::CreateReplacement(SourceRange(TagLocation),
991 TD->getKindName());
992 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
993 }
John McCall7f41d982009-09-11 04:59:25 +0000994 }
995 }
996
John McCall954b5de2010-11-04 19:04:38 +0000997 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
998 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000999 QualifierLoc,
1000 T);
John McCall7f41d982009-09-11 04:59:25 +00001001}
1002
Douglas Gregor9db53502011-03-02 18:07:45 +00001003TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1004 TemplateName Name,
Nico Weberc153d242014-07-28 00:02:09 +00001005 SourceLocation NameLoc,
Douglas Gregor9db53502011-03-02 18:07:45 +00001006 QualType ObjectType,
1007 NamedDecl *FirstQualifierInScope) {
1008 if (TemplateTemplateParmDecl *TTP
1009 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1010 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1011 // If the corresponding template argument is NULL or non-existent, it's
1012 // because we are performing instantiation from explicitly-specified
1013 // template arguments in a function template, but there were some
1014 // arguments left unspecified.
1015 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1016 TTP->getPosition()))
1017 return Name;
1018
1019 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1020
1021 if (TTP->isParameterPack()) {
1022 assert(Arg.getKind() == TemplateArgument::Pack &&
1023 "Missing argument pack");
1024
1025 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1026 // We have the template argument pack to substitute, but we're not
1027 // actually expanding the enclosing pack expansion yet. So, just
1028 // keep the entire argument pack.
1029 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1030 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001031
1032 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001033 }
1034
1035 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001036 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001037
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001038 // We don't ever want to substitute for a qualified template name, since
1039 // the qualifier is handled separately. So, look through the qualified
1040 // template name to its underlying declaration.
1041 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1042 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001043
1044 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001045 return Template;
1046 }
1047 }
1048
1049 if (SubstTemplateTemplateParmPackStorage *SubstPack
1050 = Name.getAsSubstTemplateTemplateParmPack()) {
1051 if (getSema().ArgumentPackSubstitutionIndex == -1)
1052 return Name;
1053
Eli Friedman8917ad52013-07-19 19:40:38 +00001054 TemplateArgument Arg = SubstPack->getArgumentPack();
1055 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1056 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001057 }
1058
1059 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1060 FirstQualifierInScope);
1061}
1062
John McCalldadc5752010-08-24 06:29:42 +00001063ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001064TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001065 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001066 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001067
Wei Panc354d212013-09-16 13:57:27 +00001068 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001069}
1070
John McCalldadc5752010-08-24 06:29:42 +00001071ExprResult
John McCall13481c52010-02-06 08:42:39 +00001072TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001073 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001074 // If the corresponding template argument is NULL or non-existent, it's
1075 // because we are performing instantiation from explicitly-specified
1076 // template arguments in a function template, but there were some
1077 // arguments left unspecified.
1078 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1079 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001080 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001081
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001082 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1083 if (NTTP->isParameterPack()) {
1084 assert(Arg.getKind() == TemplateArgument::Pack &&
1085 "Missing argument pack");
1086
1087 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001088 // We have an argument pack, but we can't select a particular argument
1089 // out of it yet. Therefore, we'll build an expression to hold on to that
1090 // argument pack.
1091 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1092 E->getLocation(),
1093 NTTP->getDeclName());
1094 if (TargetType.isNull())
1095 return ExprError();
1096
1097 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1098 NTTP,
1099 E->getLocation(),
1100 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001101 }
1102
Eli Friedman8917ad52013-07-19 19:40:38 +00001103 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001104 }
Mike Stump11289f42009-09-09 15:08:12 +00001105
John McCall7c454bb2011-07-15 05:09:51 +00001106 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1107}
1108
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001109const LoopHintAttr *
1110TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1111 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1112
1113 if (TransformedExpr == LH->getValue())
1114 return LH;
1115
1116 // Generate error if there is a problem with the value.
1117 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1118 return LH;
1119
1120 // Create new LoopHintValueAttr with integral expression in place of the
1121 // non-type template parameter.
1122 return LoopHintAttr::CreateImplicit(
1123 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1124 LH->getState(), TransformedExpr, LH->getRange());
1125}
1126
John McCall7c454bb2011-07-15 05:09:51 +00001127ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1128 NonTypeTemplateParmDecl *parm,
1129 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001130 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001131 ExprResult result;
1132 QualType type;
1133
John McCall13481c52010-02-06 08:42:39 +00001134 // The template argument itself might be an expression, in which
1135 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001136 if (arg.getKind() == TemplateArgument::Expression) {
1137 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001138 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001139 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001140
Eli Friedmanb826a002012-09-26 02:36:12 +00001141 } else if (arg.getKind() == TemplateArgument::Declaration ||
1142 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001143 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001144 if (arg.getKind() == TemplateArgument::Declaration) {
1145 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001146
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001147 // Find the instantiation of the template argument. This is
1148 // required for nested templates.
1149 VD = cast_or_null<ValueDecl>(
1150 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1151 if (!VD)
1152 return ExprError();
1153 } else {
1154 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001155 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001156 }
1157
John McCall15dda372010-02-06 10:23:53 +00001158 // Derive the type we want the substituted decl to have. This had
1159 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001160 if (parm->isExpandedParameterPack()) {
1161 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1162 } else if (parm->isParameterPack() &&
1163 isa<PackExpansionType>(parm->getType())) {
1164 type = SemaRef.SubstType(
1165 cast<PackExpansionType>(parm->getType())->getPattern(),
1166 TemplateArgs, loc, parm->getDeclName());
1167 } else {
1168 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1169 loc, parm->getDeclName());
1170 }
1171 assert(!type.isNull() && "type substitution failed for param type");
1172 assert(!type->isDependentType() && "param type still dependent");
1173 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001174
John McCall7c454bb2011-07-15 05:09:51 +00001175 if (!result.isInvalid()) type = result.get()->getType();
1176 } else {
1177 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1178
1179 // Note that this type can be different from the type of 'result',
1180 // e.g. if it's an enum type.
1181 type = arg.getIntegralType();
1182 }
1183 if (result.isInvalid()) return ExprError();
1184
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001185 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001186 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1187 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001188}
1189
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001190ExprResult
1191TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1192 SubstNonTypeTemplateParmPackExpr *E) {
1193 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1194 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001195 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001196 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001197
1198 TemplateArgument Arg = E->getArgumentPack();
1199 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001200 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1201 E->getParameterPackLocation(),
1202 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001203}
John McCall13481c52010-02-06 08:42:39 +00001204
John McCalldadc5752010-08-24 06:29:42 +00001205ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001206TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1207 SourceLocation Loc) {
1208 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1209 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1210}
1211
1212ExprResult
1213TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1214 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1215 // We can expand this parameter pack now.
1216 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1217 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1218 if (!VD)
1219 return ExprError();
1220 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1221 }
1222
1223 QualType T = TransformType(E->getType());
1224 if (T.isNull())
1225 return ExprError();
1226
1227 // Transform each of the parameter expansions into the corresponding
1228 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001229 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001230 Parms.reserve(E->getNumExpansions());
1231 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1232 I != End; ++I) {
1233 ParmVarDecl *D =
1234 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1235 if (!D)
1236 return ExprError();
1237 Parms.push_back(D);
1238 }
1239
1240 return FunctionParmPackExpr::Create(getSema().Context, T,
1241 E->getParameterPack(),
1242 E->getParameterPackLocation(), Parms);
1243}
1244
1245ExprResult
1246TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1247 ParmVarDecl *PD) {
1248 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1249 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1250 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1251 assert(Found && "no instantiation for parameter pack");
1252
1253 Decl *TransformedDecl;
1254 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001255 // If this is a reference to a function parameter pack which we can
1256 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001257 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1258 QualType T = TransformType(E->getType());
1259 if (T.isNull())
1260 return ExprError();
1261 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1262 E->getExprLoc(), *Pack);
1263 }
1264
1265 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1266 } else {
1267 TransformedDecl = Found->get<Decl*>();
1268 }
1269
1270 // We have either an unexpanded pack or a specific expansion.
1271 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1272 E->getExprLoc());
1273}
1274
1275ExprResult
John McCall13481c52010-02-06 08:42:39 +00001276TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1277 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001278
1279 // Handle references to non-type template parameters and non-type template
1280 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001281 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1282 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1283 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001284
1285 // We have a non-type template parameter that isn't fully substituted;
1286 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001287 }
Mike Stump11289f42009-09-09 15:08:12 +00001288
Richard Smithb15fe3a2012-09-12 00:56:43 +00001289 // Handle references to function parameter packs.
1290 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1291 if (PD->isParameterPack())
1292 return TransformFunctionParmPackRefExpr(E, PD);
1293
John McCall47f29ea2009-12-08 09:21:05 +00001294 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001295}
1296
John McCalldadc5752010-08-24 06:29:42 +00001297ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001298 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001299 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1300 getDescribedFunctionTemplate() &&
1301 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001302 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1303 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1304 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001305}
1306
Richard Smith2e321552014-11-12 02:00:47 +00001307template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001308QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1309 FunctionProtoTypeLoc TL,
1310 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001311 unsigned ThisTypeQuals,
1312 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001313 // We need a local instantiation scope for this function prototype.
1314 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001315 return inherited::TransformFunctionProtoType(
1316 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001317}
1318
John McCall58f10c32010-03-11 09:03:00 +00001319ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001320TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001321 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001322 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001323 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001324 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001325 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001326}
1327
Mike Stump11289f42009-09-09 15:08:12 +00001328QualType
John McCall550e0c22009-10-21 00:40:46 +00001329TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001330 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001331 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001332 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001333 // Replace the template type parameter with its corresponding
1334 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001335
1336 // If the corresponding template argument is NULL or doesn't exist, it's
1337 // because we are performing instantiation from explicitly-specified
1338 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001339 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001340 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1341 TemplateTypeParmTypeLoc NewTL
1342 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1343 NewTL.setNameLoc(TL.getNameLoc());
1344 return TL.getType();
1345 }
Mike Stump11289f42009-09-09 15:08:12 +00001346
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001347 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1348
1349 if (T->isParameterPack()) {
1350 assert(Arg.getKind() == TemplateArgument::Pack &&
1351 "Missing argument pack");
1352
1353 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001354 // We have the template argument pack, but we're not expanding the
1355 // enclosing pack expansion yet. Just save the template argument
1356 // pack for later substitution.
1357 QualType Result
1358 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1359 SubstTemplateTypeParmPackTypeLoc NewTL
1360 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1361 NewTL.setNameLoc(TL.getNameLoc());
1362 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001363 }
1364
Eli Friedman8917ad52013-07-19 19:40:38 +00001365 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001366 }
1367
1368 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001369 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001370
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001371 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001372
1373 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001374 QualType Result
1375 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1376 SubstTemplateTypeParmTypeLoc NewTL
1377 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1378 NewTL.setNameLoc(TL.getNameLoc());
1379 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001380 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001381
1382 // The template type parameter comes from an inner template (e.g.,
1383 // the template parameter list of a member template inside the
1384 // template we are instantiating). Create a new template type
1385 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001386 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001387 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1388 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1389 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1390
John McCall550e0c22009-10-21 00:40:46 +00001391 QualType Result
1392 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1393 - TemplateArgs.getNumLevels(),
1394 T->getIndex(),
1395 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001396 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001397 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1398 NewTL.setNameLoc(TL.getNameLoc());
1399 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001400}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001401
Douglas Gregorada4b792011-01-14 02:55:32 +00001402QualType
1403TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1404 TypeLocBuilder &TLB,
1405 SubstTemplateTypeParmPackTypeLoc TL) {
1406 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1407 // We aren't expanding the parameter pack, so just return ourselves.
1408 SubstTemplateTypeParmPackTypeLoc NewTL
1409 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1410 NewTL.setNameLoc(TL.getNameLoc());
1411 return TL.getType();
1412 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001413
1414 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1415 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1416 QualType Result = Arg.getAsType();
1417
Douglas Gregorada4b792011-01-14 02:55:32 +00001418 Result = getSema().Context.getSubstTemplateTypeParmType(
1419 TL.getTypePtr()->getReplacedParameter(),
1420 Result);
1421 SubstTemplateTypeParmTypeLoc NewTL
1422 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1423 NewTL.setNameLoc(TL.getNameLoc());
1424 return Result;
1425}
1426
John McCall76d824f2009-08-25 22:02:44 +00001427/// \brief Perform substitution on the type T with a given set of template
1428/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001429///
1430/// This routine substitutes the given template arguments into the
1431/// type T and produces the instantiated type.
1432///
1433/// \param T the type into which the template arguments will be
1434/// substituted. If this type is not dependent, it will be returned
1435/// immediately.
1436///
James Dennett634962f2012-06-14 21:40:34 +00001437/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001438/// substituted for the top-level template parameters within T.
1439///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001440/// \param Loc the location in the source code where this substitution
1441/// is being performed. It will typically be the location of the
1442/// declarator (if we're instantiating the type of some declaration)
1443/// or the location of the type in the source code (if, e.g., we're
1444/// instantiating the type of a cast expression).
1445///
1446/// \param Entity the name of the entity associated with a declaration
1447/// being instantiated (if any). May be empty to indicate that there
1448/// is no such entity (if, e.g., this is a type that occurs as part of
1449/// a cast expression) or that the entity has no name (e.g., an
1450/// unnamed function parameter).
1451///
1452/// \returns If the instantiation succeeds, the instantiated
1453/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001454TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001455 const MultiLevelTemplateArgumentList &Args,
1456 SourceLocation Loc,
1457 DeclarationName Entity) {
1458 assert(!ActiveTemplateInstantiations.empty() &&
1459 "Cannot perform an instantiation without some context on the "
1460 "instantiation stack");
1461
Douglas Gregor678d76c2011-07-01 01:22:09 +00001462 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001463 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001464 return T;
1465
1466 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1467 return Instantiator.TransformType(T);
1468}
1469
Douglas Gregor5499af42011-01-05 23:12:31 +00001470TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1471 const MultiLevelTemplateArgumentList &Args,
1472 SourceLocation Loc,
1473 DeclarationName Entity) {
1474 assert(!ActiveTemplateInstantiations.empty() &&
1475 "Cannot perform an instantiation without some context on the "
1476 "instantiation stack");
1477
1478 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001479 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001480
Douglas Gregor678d76c2011-07-01 01:22:09 +00001481 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001482 !TL.getType()->isVariablyModifiedType()) {
1483 // FIXME: Make a copy of the TypeLoc data here, so that we can
1484 // return a new TypeSourceInfo. Inefficient!
1485 TypeLocBuilder TLB;
1486 TLB.pushFullCopy(TL);
1487 return TLB.getTypeSourceInfo(Context, TL.getType());
1488 }
1489
1490 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1491 TypeLocBuilder TLB;
1492 TLB.reserve(TL.getFullDataSize());
1493 QualType Result = Instantiator.TransformType(TLB, TL);
1494 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001495 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001496
1497 return TLB.getTypeSourceInfo(Context, Result);
1498}
1499
John McCall609459e2009-10-21 00:58:09 +00001500/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001501QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001502 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001503 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001504 assert(!ActiveTemplateInstantiations.empty() &&
1505 "Cannot perform an instantiation without some context on the "
1506 "instantiation stack");
1507
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001508 // If T is not a dependent type or a variably-modified type, there
1509 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001510 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001511 return T;
1512
Douglas Gregord6ff3322009-08-04 16:50:30 +00001513 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1514 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001515}
Douglas Gregor463421d2009-03-03 04:44:36 +00001516
John McCallb29f78f2010-04-09 17:38:44 +00001517static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001518 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001519 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001520 return true;
1521
Abramo Bagnara6d810632010-12-14 22:11:44 +00001522 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001523 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001524 return false;
1525
David Blaikie6adc78e2013-02-18 22:06:02 +00001526 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001527 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001528 // This must be synthesized from a typedef.
1529 if (!P) continue;
1530
Nico Weberc0973372016-02-01 22:31:51 +00001531 // If there are any parameters, a new TypeSourceInfo that refers to the
1532 // instantiated parameters must be built.
1533 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001534 }
1535
1536 return false;
1537}
1538
1539/// A form of SubstType intended specifically for instantiating the
1540/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001541/// instantiation of default-argument expressions and to avoid
1542/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001543TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1544 const MultiLevelTemplateArgumentList &Args,
1545 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001546 DeclarationName Entity,
1547 CXXRecordDecl *ThisContext,
1548 unsigned ThisTypeQuals) {
John McCallb29f78f2010-04-09 17:38:44 +00001549 assert(!ActiveTemplateInstantiations.empty() &&
1550 "Cannot perform an instantiation without some context on the "
1551 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001552
John McCallb29f78f2010-04-09 17:38:44 +00001553 if (!NeedsInstantiationAsFunctionType(T))
1554 return T;
1555
1556 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1557
1558 TypeLocBuilder TLB;
1559
1560 TypeLoc TL = T->getTypeLoc();
1561 TLB.reserve(TL.getFullDataSize());
1562
Douglas Gregor3024f072012-04-16 07:05:22 +00001563 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001564
Richard Smith2e321552014-11-12 02:00:47 +00001565 if (FunctionProtoTypeLoc Proto =
1566 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1567 // Instantiate the type, other than its exception specification. The
1568 // exception specification is instantiated in InitFunctionInstantiation
1569 // once we've built the FunctionDecl.
1570 // FIXME: Set the exception specification to EST_Uninstantiated here,
1571 // instead of rebuilding the function type again later.
1572 Result = Instantiator.TransformFunctionProtoType(
1573 TLB, Proto, ThisContext, ThisTypeQuals,
1574 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1575 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001576 } else {
1577 Result = Instantiator.TransformType(TLB, TL);
1578 }
John McCallb29f78f2010-04-09 17:38:44 +00001579 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001580 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001581
1582 return TLB.getTypeSourceInfo(Context, Result);
1583}
1584
Richard Smith2e321552014-11-12 02:00:47 +00001585void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1586 const MultiLevelTemplateArgumentList &Args) {
1587 FunctionProtoType::ExceptionSpecInfo ESI =
1588 Proto->getExtProtoInfo().ExceptionSpec;
1589 assert(ESI.Type != EST_Uninstantiated);
1590
1591 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1592 New->getDeclName());
1593
1594 SmallVector<QualType, 4> ExceptionStorage;
1595 bool Changed = false;
1596 if (Instantiator.TransformExceptionSpec(
1597 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1598 ExceptionStorage, Changed))
1599 // On error, recover by dropping the exception specification.
1600 ESI.Type = EST_None;
1601
1602 UpdateExceptionSpec(New, ESI);
1603}
1604
Douglas Gregor940bca72010-04-12 07:48:19 +00001605ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001606 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001607 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001608 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001609 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001610 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001611 TypeSourceInfo *NewDI = nullptr;
1612
Douglas Gregor5499af42011-01-05 23:12:31 +00001613 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001614 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1615
Douglas Gregor5499af42011-01-05 23:12:31 +00001616 // We have a function parameter pack. Substitute into the pattern of the
1617 // expansion.
1618 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1619 OldParm->getLocation(), OldParm->getDeclName());
1620 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001621 return nullptr;
1622
Douglas Gregor5499af42011-01-05 23:12:31 +00001623 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1624 // We still have unexpanded parameter packs, which means that
1625 // our function parameter is still a function parameter pack.
1626 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001627 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001628 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001629 } else if (ExpectParameterPack) {
1630 // We expected to get a parameter pack but didn't (because the type
1631 // itself is not a pack expansion type), so complain. This can occur when
1632 // the substitution goes through an alias template that "loses" the
1633 // pack expansion.
1634 Diag(OldParm->getLocation(),
1635 diag::err_function_parameter_pack_without_parameter_packs)
1636 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001637 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001638 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001639 } else {
1640 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1641 OldParm->getDeclName());
1642 }
1643
Douglas Gregor940bca72010-04-12 07:48:19 +00001644 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001645 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001646
1647 if (NewDI->getType()->isVoidType()) {
1648 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001649 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001650 }
1651
1652 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001653 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001654 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001655 OldParm->getIdentifier(),
1656 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001657 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001658 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001659 return nullptr;
1660
Douglas Gregor940bca72010-04-12 07:48:19 +00001661 // Mark the (new) default argument as uninstantiated (if any).
1662 if (OldParm->hasUninstantiatedDefaultArg()) {
1663 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1664 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001665 } else if (OldParm->hasUnparsedDefaultArg()) {
1666 NewParm->setUnparsedDefaultArg();
1667 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001668 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1669 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001670 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1671 // Instantiate default arguments for methods of local classes (DR1484)
1672 // and non-defining declarations.
1673 Sema::ContextRAII SavedContext(*this, OwningFunc);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001674 LocalInstantiationScope Local(*this);
1675 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001676 if (NewArg.isUsable()) {
1677 // It would be nice if we still had this.
1678 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1679 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1680 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001681 } else {
1682 // FIXME: if we non-lazily instantiated non-dependent default args for
1683 // non-dependent parameter types we could remove a bunch of duplicate
1684 // conversion warnings for such arguments.
1685 NewParm->setUninstantiatedDefaultArg(Arg);
1686 }
1687 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001688
1689 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001690
Douglas Gregorf3010112011-01-07 16:43:16 +00001691 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001692 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001693 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1694 } else {
1695 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001696 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001697 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001698
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001699 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1700 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001701 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001702
1703 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1704 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001705
1706 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1707
Douglas Gregor940bca72010-04-12 07:48:19 +00001708 return NewParm;
1709}
1710
Douglas Gregordd472162011-01-07 00:20:55 +00001711/// \brief Substitute the given template arguments into the given set of
1712/// parameters, producing the set of parameter types that would be generated
1713/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001714bool Sema::SubstParmTypes(
1715 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1716 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1717 const MultiLevelTemplateArgumentList &TemplateArgs,
1718 SmallVectorImpl<QualType> &ParamTypes,
1719 SmallVectorImpl<ParmVarDecl *> *OutParams,
1720 ExtParameterInfoBuilder &ParamInfos) {
Douglas Gregordd472162011-01-07 00:20:55 +00001721 assert(!ActiveTemplateInstantiations.empty() &&
1722 "Cannot perform an instantiation without some context on the "
1723 "instantiation stack");
1724
1725 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1726 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001727 return Instantiator.TransformFunctionTypeParams(
1728 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001729}
1730
John McCall76d824f2009-08-25 22:02:44 +00001731/// \brief Perform substitution on the base class specifiers of the
1732/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001733///
1734/// Produces a diagnostic and returns true on error, returns false and
1735/// attaches the instantiated base classes to the class template
1736/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001737bool
John McCall76d824f2009-08-25 22:02:44 +00001738Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1739 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001740 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001741 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001742 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001743 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001744 if (!Base.getType()->isDependentType()) {
1745 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001746 if (RD->isInvalidDecl())
1747 Instantiation->setInvalidDecl();
1748 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001749 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001750 continue;
1751 }
1752
Douglas Gregor752a5952011-01-03 22:36:02 +00001753 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001754 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001755 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001756 // This is a pack expansion. See whether we should expand it now, or
1757 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001758 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001759 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001760 Unexpanded);
1761 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001762 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001763 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001764 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1765 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001766 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001767 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001768 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001769 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001770 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001771 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001772 }
1773
1774 // If we should expand this pack expansion now, do so.
1775 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001776 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001777 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1778
Aaron Ballman574705e2014-03-13 15:41:46 +00001779 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001780 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001781 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001782 DeclarationName());
1783 if (!BaseTypeLoc) {
1784 Invalid = true;
1785 continue;
1786 }
1787
1788 if (CXXBaseSpecifier *InstantiatedBase
1789 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001790 Base.getSourceRange(),
1791 Base.isVirtual(),
1792 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001793 BaseTypeLoc,
1794 SourceLocation()))
1795 InstantiatedBases.push_back(InstantiatedBase);
1796 else
1797 Invalid = true;
1798 }
1799
1800 continue;
1801 }
1802
1803 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001804 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001805 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001806 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001807 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001808 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001809 DeclarationName());
1810 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001811 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001812 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001813 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001814 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001815 }
1816
Nick Lewycky19b9f952010-07-26 16:56:01 +00001817 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001818 Invalid = true;
1819 continue;
1820 }
1821
1822 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001823 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001824 Base.getSourceRange(),
1825 Base.isVirtual(),
1826 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001827 BaseTypeLoc,
1828 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001829 InstantiatedBases.push_back(InstantiatedBase);
1830 else
1831 Invalid = true;
1832 }
1833
Craig Topperaa700cb2015-12-27 21:55:19 +00001834 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001835 Invalid = true;
1836
1837 return Invalid;
1838}
1839
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001840// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001841namespace clang {
1842 namespace sema {
1843 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1844 const MultiLevelTemplateArgumentList &TemplateArgs);
1845 }
1846}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001847
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001848/// \brief Instantiate the definition of a class from a given pattern.
1849///
1850/// \param PointOfInstantiation The point of instantiation within the
1851/// source code.
1852///
1853/// \param Instantiation is the declaration whose definition is being
1854/// instantiated. This will be either a class template specialization
1855/// or a member class of a class template specialization.
1856///
1857/// \param Pattern is the pattern from which the instantiation
1858/// occurs. This will be either the declaration of a class template or
1859/// the declaration of a member class of a class template.
1860///
1861/// \param TemplateArgs The template arguments to be substituted into
1862/// the pattern.
1863///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001864/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001865///
1866/// \param Complain whether to complain if the class cannot be instantiated due
1867/// to the lack of a definition.
1868///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001869/// \returns true if an error occurred, false otherwise.
1870bool
1871Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1872 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001873 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001874 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001875 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001876 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001877 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00001878 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00001879 Instantiation->getInstantiatedFromMemberClass(),
1880 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001881 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001882 Pattern = PatternDef;
1883
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001884 // \brief Record the point of instantiation.
1885 if (MemberSpecializationInfo *MSInfo
1886 = Instantiation->getMemberSpecializationInfo()) {
1887 MSInfo->setTemplateSpecializationKind(TSK);
1888 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001889 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001890 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001891 Spec->setTemplateSpecializationKind(TSK);
1892 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001893 }
Richard Smitha1087602014-03-10 00:04:29 +00001894
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001895 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001896 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001897 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00001898 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
1899 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001900
1901 // Enter the scope of this instantiation. We don't use
1902 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001903 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001904 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001905 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001906
Douglas Gregor51121572010-03-24 01:33:17 +00001907 // If this is an instantiation of a local class, merge this local
1908 // instantiation scope with the enclosing scope. Otherwise, every
1909 // instantiation of a class has its own local instantiation scope.
1910 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001911 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001912
Reid Kleckner5b640342016-02-26 19:51:02 +00001913 // All dllexported classes created during instantiation should be fully
1914 // emitted after instantiation completes. We may not be ready to emit any
1915 // delayed classes already on the stack, so save them away and put them back
1916 // later.
1917 decltype(DelayedDllExportClasses) ExportedClasses;
1918 std::swap(ExportedClasses, DelayedDllExportClasses);
1919
John McCall6602bb12010-08-01 02:01:53 +00001920 // Pull attributes from the pattern onto the instantiation.
1921 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1922
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001923 // Start the definition of this instantiation.
1924 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00001925
1926 // The instantiation is visible here, even if it was first declared in an
1927 // unimported module.
1928 Instantiation->setHidden(false);
1929
1930 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00001931 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001932
John McCall76d824f2009-08-25 22:02:44 +00001933 // Do substitution on the base class specifiers.
1934 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001935 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001936
Douglas Gregor869853e2010-11-10 19:44:59 +00001937 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001938 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001939 // Delay instantiation of late parsed attributes.
1940 LateInstantiatedAttrVec LateAttrs;
1941 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1942
Aaron Ballman629afae2014-03-07 19:56:05 +00001943 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001944 // Don't instantiate members not belonging in this semantic context.
1945 // e.g. for:
1946 // @code
1947 // template <int i> class A {
1948 // class B *g;
1949 // };
1950 // @endcode
1951 // 'class B' has the template as lexical context but semantically it is
1952 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00001953 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001954 continue;
1955
Aaron Ballman629afae2014-03-07 19:56:05 +00001956 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00001957 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00001958 continue;
1959 }
1960
Aaron Ballman629afae2014-03-07 19:56:05 +00001961 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001962 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00001963 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00001964 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00001965 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
1966 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1967 // specialization causes the implicit instantiation of the definitions
1968 // of unscoped member enumerations.
1969 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00001970 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
1971 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00001972 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
1973 assert(MSInfo && "no spec info for member enum specialization");
1974 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
1975 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1976 }
Richard Smithded9c2e2012-07-11 22:37:56 +00001977 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
1978 if (SA->isFailed()) {
1979 // A static_assert failed. Bail out; instantiating this
1980 // class is probably not meaningful.
1981 Instantiation->setInvalidDecl();
1982 break;
1983 }
Richard Smith7d137e32012-03-23 03:33:32 +00001984 }
1985
1986 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001987 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001988 } else {
1989 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001990 // instantiations was a semantic disaster, and we'll want to mark the
1991 // declaration invalid.
1992 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001993 }
1994 }
1995
1996 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00001997 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
1998 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001999 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002000
Reid Kleckner93f661a2015-03-17 21:51:43 +00002001 // Default arguments are parsed, if not instantiated. We can go instantiate
2002 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002003 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002004
Reid Kleckner5b640342016-02-26 19:51:02 +00002005 // Put back the delayed exported classes that we moved out of the way.
2006 std::swap(ExportedClasses, DelayedDllExportClasses);
2007
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002008 // Instantiate late parsed attributes, and attach them to their decls.
2009 // See Sema::InstantiateAttrs
2010 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2011 E = LateAttrs.end(); I != E; ++I) {
2012 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2013 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002014
2015 // Allow 'this' within late-parsed attributes.
2016 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2017 CXXRecordDecl *ThisContext =
2018 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2019 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2020 ND && ND->isCXXInstanceMember());
2021
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002022 Attr *NewAttr =
2023 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2024 I->NewDecl->addAttr(NewAttr);
2025 LocalInstantiationScope::deleteScopes(I->Scope,
2026 Instantiator.getStartingScope());
2027 }
2028 Instantiator.disableLateAttributeInstantiation();
2029 LateAttrs.clear();
2030
Richard Smithd3b5c9082012-07-27 04:22:15 +00002031 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002032
Richard Smitha1087602014-03-10 00:04:29 +00002033 // FIXME: We should do something similar for explicit instantiations so they
2034 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002035 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002036 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002037 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002038 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002039 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002040
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002041 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002042 // Perform any dependent diagnostics from the pattern.
2043 PerformDependentDiagnostics(Pattern, TemplateArgs);
2044
Douglas Gregor869853e2010-11-10 19:44:59 +00002045 // Instantiate any out-of-line class template partial
2046 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002047 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002048 P = Instantiator.delayed_partial_spec_begin(),
2049 PEnd = Instantiator.delayed_partial_spec_end();
2050 P != PEnd; ++P) {
2051 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002052 P->first, P->second)) {
2053 Instantiation->setInvalidDecl();
2054 break;
2055 }
2056 }
2057
2058 // Instantiate any out-of-line variable template partial
2059 // specializations now.
2060 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2061 P = Instantiator.delayed_var_partial_spec_begin(),
2062 PEnd = Instantiator.delayed_var_partial_spec_end();
2063 P != PEnd; ++P) {
2064 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2065 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002066 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002067 break;
2068 }
2069 }
2070 }
2071
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002072 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002073 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002074
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002075 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002076 Consumer.HandleTagDeclDefinition(Instantiation);
2077
Douglas Gregor88d292c2010-05-13 16:44:06 +00002078 // Always emit the vtable for an explicit instantiation definition
2079 // of a polymorphic class template specialization.
2080 if (TSK == TSK_ExplicitInstantiationDefinition)
2081 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2082 }
2083
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002084 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002085}
2086
Richard Smith4b38ded2012-03-14 23:13:10 +00002087/// \brief Instantiate the definition of an enum from a given pattern.
2088///
2089/// \param PointOfInstantiation The point of instantiation within the
2090/// source code.
2091/// \param Instantiation is the declaration whose definition is being
2092/// instantiated. This will be a member enumeration of a class
2093/// temploid specialization, or a local enumeration within a
2094/// function temploid specialization.
2095/// \param Pattern The templated declaration from which the instantiation
2096/// occurs.
2097/// \param TemplateArgs The template arguments to be substituted into
2098/// the pattern.
2099/// \param TSK The kind of implicit or explicit instantiation to perform.
2100///
2101/// \return \c true if an error occurred, \c false otherwise.
2102bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2103 EnumDecl *Instantiation, EnumDecl *Pattern,
2104 const MultiLevelTemplateArgumentList &TemplateArgs,
2105 TemplateSpecializationKind TSK) {
2106 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002107 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002108 Instantiation->getInstantiatedFromMemberEnum(),
2109 Pattern, PatternDef, TSK,/*Complain*/true))
2110 return true;
2111 Pattern = PatternDef;
2112
2113 // Record the point of instantiation.
2114 if (MemberSpecializationInfo *MSInfo
2115 = Instantiation->getMemberSpecializationInfo()) {
2116 MSInfo->setTemplateSpecializationKind(TSK);
2117 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2118 }
2119
2120 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002121 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002122 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00002123 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2124 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002125
Richard Smitha1087602014-03-10 00:04:29 +00002126 // The instantiation is visible here, even if it was first declared in an
2127 // unimported module.
2128 Instantiation->setHidden(false);
2129
Richard Smith4b38ded2012-03-14 23:13:10 +00002130 // Enter the scope of this instantiation. We don't use
2131 // PushDeclContext because we don't have a scope.
2132 ContextRAII SavedContext(*this, Instantiation);
2133 EnterExpressionEvaluationContext EvalContext(*this,
2134 Sema::PotentiallyEvaluated);
2135
2136 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2137
2138 // Pull attributes from the pattern onto the instantiation.
2139 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2140
2141 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2142 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2143
2144 // Exit the scope of this instantiation.
2145 SavedContext.pop();
2146
2147 return Instantiation->isInvalidDecl();
2148}
2149
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002150
2151/// \brief Instantiate the definition of a field from the given pattern.
2152///
2153/// \param PointOfInstantiation The point of instantiation within the
2154/// source code.
2155/// \param Instantiation is the declaration whose definition is being
2156/// instantiated. This will be a class of a class temploid
2157/// specialization, or a local enumeration within a function temploid
2158/// specialization.
2159/// \param Pattern The templated declaration from which the instantiation
2160/// occurs.
2161/// \param TemplateArgs The template arguments to be substituted into
2162/// the pattern.
2163///
2164/// \return \c true if an error occurred, \c false otherwise.
2165bool Sema::InstantiateInClassInitializer(
2166 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2167 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2168 // If there is no initializer, we don't need to do anything.
2169 if (!Pattern->hasInClassInitializer())
2170 return false;
2171
2172 assert(Instantiation->getInClassInitStyle() ==
2173 Pattern->getInClassInitStyle() &&
2174 "pattern and instantiation disagree about init style");
2175
2176 // Error out if we haven't parsed the initializer of the pattern yet because
2177 // we are waiting for the closing brace of the outer class.
2178 Expr *OldInit = Pattern->getInClassInitializer();
2179 if (!OldInit) {
2180 RecordDecl *PatternRD = Pattern->getParent();
2181 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2182 if (OutermostClass == PatternRD) {
2183 Diag(Pattern->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
2184 << PatternRD << Pattern;
2185 } else {
2186 Diag(Pattern->getLocEnd(),
2187 diag::err_in_class_initializer_not_yet_parsed_outer_class)
2188 << PatternRD << OutermostClass << Pattern;
2189 }
2190 Instantiation->setInvalidDecl();
2191 return true;
2192 }
2193
2194 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2195 if (Inst.isInvalid())
2196 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00002197 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2198 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002199
2200 // Enter the scope of this instantiation. We don't use PushDeclContext because
2201 // we don't have a scope.
2202 ContextRAII SavedContext(*this, Instantiation->getParent());
2203 EnterExpressionEvaluationContext EvalContext(*this,
2204 Sema::PotentiallyEvaluated);
2205
Serge Pavlov907233f2015-04-28 17:58:47 +00002206 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002207
2208 // Instantiate the initializer.
2209 ActOnStartCXXInClassMemberInitializer();
2210 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2211
2212 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2213 /*CXXDirectInit=*/false);
2214 Expr *Init = NewInit.get();
2215 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2216 ActOnFinishCXXInClassMemberInitializer(
2217 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2218
Richard Smith4b054b22016-08-24 21:25:37 +00002219 if (auto *L = getASTMutationListener())
2220 L->DefaultMemberInitializerInstantiated(Instantiation);
2221
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002222 // Exit the scope of this instantiation.
2223 SavedContext.pop();
2224
2225 // Return true if the in-class initializer is still missing.
2226 return !Instantiation->getInClassInitializer();
2227}
2228
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002229namespace {
2230 /// \brief A partial specialization whose template arguments have matched
2231 /// a given template-id.
2232 struct PartialSpecMatchResult {
2233 ClassTemplatePartialSpecializationDecl *Partial;
2234 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002235 };
2236}
2237
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002238bool Sema::InstantiateClassTemplateSpecialization(
2239 SourceLocation PointOfInstantiation,
2240 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2241 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002242 // Perform the actual instantiation on the canonical declaration.
2243 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002244 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor00a511f2009-09-15 16:51:42 +00002245 if (ClassTemplateSpec->isInvalidDecl())
2246 return true;
2247
Douglas Gregor463421d2009-03-03 04:44:36 +00002248 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002249 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002250
Douglas Gregor170bc422009-06-12 22:31:52 +00002251 // C++ [temp.class.spec.match]p1:
2252 // When a class template is used in a context that requires an
2253 // instantiation of the class, it is necessary to determine
2254 // whether the instantiation is to be generated using the primary
2255 // template or one of the partial specializations. This is done by
2256 // matching the template arguments of the class template
2257 // specialization with the template argument lists of the partial
2258 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002259 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002260 SmallVector<MatchResult, 4> Matched;
2261 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002262 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002263 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002264 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2265 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002266 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002267 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002268 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002269 ClassTemplateSpec->getTemplateArgs(),
2270 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002271 // Store the failed-deduction information for use in diagnostics, later.
2272 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002273 FailedCandidates.addCandidate().set(
2274 DeclAccessPair::make(Template, AS_public), Partial,
2275 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002276 (void)Result;
2277 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002278 Matched.push_back(PartialSpecMatchResult());
2279 Matched.back().Partial = Partial;
2280 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002281 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002282 }
2283
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002284 // If we're dealing with a member template where the template parameters
2285 // have been instantiated, this provides the original template parameters
2286 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002287
Douglas Gregor21610382009-10-29 00:04:11 +00002288 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002289 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002290 if (Matched.size() == 1) {
2291 // -- If exactly one matching specialization is found, the
2292 // instantiation is generated from that specialization.
2293 // We don't need to do anything for this.
2294 } else {
2295 // -- If more than one matching specialization is found, the
2296 // partial order rules (14.5.4.2) are used to determine
2297 // whether one of the specializations is more specialized
2298 // than the others. If none of the specializations is more
2299 // specialized than all of the other matching
2300 // specializations, then the use of the class template is
2301 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002302 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2303 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002304 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002305 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002306 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002307 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002308 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002309 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002310
Douglas Gregor21610382009-10-29 00:04:11 +00002311 // Determine if the best partial specialization is more specialized than
2312 // the others.
2313 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002314 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2315 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002316 P != PEnd; ++P) {
2317 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002318 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002319 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002320 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002321 Ambiguous = true;
2322 break;
2323 }
2324 }
2325
2326 if (Ambiguous) {
2327 // Partial ordering did not produce a clear winner. Complain.
2328 ClassTemplateSpec->setInvalidDecl();
2329 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2330 << ClassTemplateSpec;
2331
2332 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002333 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2334 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002335 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002336 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2337 << getTemplateArgumentBindingsText(
2338 P->Partial->getTemplateParameters(),
2339 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002340
Douglas Gregor21610382009-10-29 00:04:11 +00002341 return true;
2342 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002343 }
2344
2345 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002346 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002347 while (OrigPartialSpec->getInstantiatedFromMember()) {
2348 // If we've found an explicit specialization of this class template,
2349 // stop here and use that as the pattern.
2350 if (OrigPartialSpec->isMemberSpecialization())
2351 break;
2352
2353 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2354 }
2355
2356 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002357 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002358 } else {
2359 // -- If no matches are found, the instantiation is generated
2360 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002361 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002362 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2363 // If we've found an explicit specialization of this class template,
2364 // stop here and use that as the pattern.
2365 if (OrigTemplate->isMemberSpecialization())
2366 break;
2367
Douglas Gregor01afeef2009-08-28 20:31:08 +00002368 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002369 }
2370
Douglas Gregor01afeef2009-08-28 20:31:08 +00002371 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002372 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002373
Douglas Gregoref6ab412009-10-27 06:26:26 +00002374 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2375 Pattern,
2376 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002377 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002378 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002379
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002380 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002381}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002382
John McCall76d824f2009-08-25 22:02:44 +00002383/// \brief Instantiates the definitions of all of the member
2384/// of the given class, which is an instantiation of a class template
2385/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002386void
2387Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002388 CXXRecordDecl *Instantiation,
2389 const MultiLevelTemplateArgumentList &TemplateArgs,
2390 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002391 // FIXME: We need to notify the ASTMutationListener that we did all of these
2392 // things, in case we have an explicit instantiation definition in a PCM, a
2393 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002394 assert(
2395 (TSK == TSK_ExplicitInstantiationDefinition ||
2396 TSK == TSK_ExplicitInstantiationDeclaration ||
2397 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2398 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002399 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002400 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002401 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002402 if (FunctionDecl *Pattern
2403 = Function->getInstantiatedFromMemberFunction()) {
2404 MemberSpecializationInfo *MSInfo
2405 = Function->getMemberSpecializationInfo();
2406 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002407 if (MSInfo->getTemplateSpecializationKind()
2408 == TSK_ExplicitSpecialization)
2409 continue;
2410
Douglas Gregor1d957a32009-10-27 18:42:08 +00002411 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2412 Function,
2413 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002414 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002415 SuppressNew) ||
2416 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002417 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002418
2419 // C++11 [temp.explicit]p8:
2420 // An explicit instantiation definition that names a class template
2421 // specialization explicitly instantiates the class template
2422 // specialization and is only an explicit instantiation definition
2423 // of members whose definition is visible at the point of
2424 // instantiation.
2425 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002426 continue;
2427
Richard Smitheb36ddf2014-04-24 22:45:46 +00002428 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2429
2430 if (Function->isDefined()) {
2431 // Let the ASTConsumer know that this function has been explicitly
2432 // instantiated now, and its linkage might have changed.
2433 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2434 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002435 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002436 } else if (TSK == TSK_ImplicitInstantiation) {
2437 PendingLocalImplicitInstantiations.push_back(
2438 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002439 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002440 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002441 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002442 if (isa<VarTemplateSpecializationDecl>(Var))
2443 continue;
2444
Douglas Gregor86d142a2009-10-08 07:24:58 +00002445 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002446 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2447 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002448 if (MSInfo->getTemplateSpecializationKind()
2449 == TSK_ExplicitSpecialization)
2450 continue;
2451
Douglas Gregor1d957a32009-10-27 18:42:08 +00002452 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2453 Var,
2454 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002455 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002456 SuppressNew) ||
2457 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002458 continue;
2459
Douglas Gregor1d957a32009-10-27 18:42:08 +00002460 if (TSK == TSK_ExplicitInstantiationDefinition) {
2461 // C++0x [temp.explicit]p8:
2462 // An explicit instantiation definition that names a class template
2463 // specialization explicitly instantiates the class template
2464 // specialization and is only an explicit instantiation definition
2465 // of members whose definition is visible at the point of
2466 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002467 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002468 continue;
2469
2470 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002471 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002472 } else {
2473 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2474 }
2475 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002476 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002477 // Always skip the injected-class-name, along with any
2478 // redeclarations of nested classes, since both would cause us
2479 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002480 // Skip closure types; they'll get instantiated when we instantiate
2481 // the corresponding lambda-expression.
2482 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2483 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002484 continue;
2485
Douglas Gregor1d957a32009-10-27 18:42:08 +00002486 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2487 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002488
2489 if (MSInfo->getTemplateSpecializationKind()
2490 == TSK_ExplicitSpecialization)
2491 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002492
Hans Wennborga86a83b2016-05-26 19:42:56 +00002493 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2494 TSK == TSK_ExplicitInstantiationDeclaration) {
2495 // In MSVC mode, explicit instantiation decl of the outer class doesn't
2496 // affect the inner class.
2497 continue;
2498 }
2499
Douglas Gregor1d957a32009-10-27 18:42:08 +00002500 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2501 Record,
2502 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002503 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002504 SuppressNew) ||
2505 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002506 continue;
2507
Douglas Gregor1d957a32009-10-27 18:42:08 +00002508 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2509 assert(Pattern && "Missing instantiated-from-template information");
2510
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002511 if (!Record->getDefinition()) {
2512 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002513 // C++0x [temp.explicit]p8:
2514 // An explicit instantiation definition that names a class template
2515 // specialization explicitly instantiates the class template
2516 // specialization and is only an explicit instantiation definition
2517 // of members whose definition is visible at the point of
2518 // instantiation.
2519 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2520 MSInfo->setTemplateSpecializationKind(TSK);
2521 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2522 }
2523
2524 continue;
2525 }
2526
2527 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002528 TemplateArgs,
2529 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002530 } else {
2531 if (TSK == TSK_ExplicitInstantiationDefinition &&
2532 Record->getTemplateSpecializationKind() ==
2533 TSK_ExplicitInstantiationDeclaration) {
2534 Record->setTemplateSpecializationKind(TSK);
2535 MarkVTableUsed(PointOfInstantiation, Record, true);
2536 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002537 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002538
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002539 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002540 if (Pattern)
2541 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2542 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002543 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002544 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2545 assert(MSInfo && "No member specialization information?");
2546
2547 if (MSInfo->getTemplateSpecializationKind()
2548 == TSK_ExplicitSpecialization)
2549 continue;
2550
2551 if (CheckSpecializationInstantiationRedecl(
2552 PointOfInstantiation, TSK, Enum,
2553 MSInfo->getTemplateSpecializationKind(),
2554 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2555 SuppressNew)
2556 continue;
2557
2558 if (Enum->getDefinition())
2559 continue;
2560
Richard Smith6739a102016-05-05 00:56:12 +00002561 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002562 assert(Pattern && "Missing instantiated-from-template information");
2563
2564 if (TSK == TSK_ExplicitInstantiationDefinition) {
2565 if (!Pattern->getDefinition())
2566 continue;
2567
2568 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2569 } else {
2570 MSInfo->setTemplateSpecializationKind(TSK);
2571 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2572 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002573 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2574 // No need to instantiate in-class initializers during explicit
2575 // instantiation.
2576 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2577 CXXRecordDecl *ClassPattern =
2578 Instantiation->getTemplateInstantiationPattern();
2579 DeclContext::lookup_result Lookup =
2580 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002581 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002582 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2583 TemplateArgs);
2584 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002585 }
2586 }
2587}
2588
2589/// \brief Instantiate the definitions of all of the members of the
2590/// given class template specialization, which was named as part of an
2591/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002592void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002593Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002594 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002595 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2596 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002597 // C++0x [temp.explicit]p7:
2598 // An explicit instantiation that names a class template
2599 // specialization is an explicit instantion of the same kind
2600 // (declaration or definition) of each of its members (not
2601 // including members inherited from base classes) that has not
2602 // been previously explicitly specialized in the translation unit
2603 // containing the explicit instantiation, except as described
2604 // below.
2605 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002606 getTemplateInstantiationArgs(ClassTemplateSpec),
2607 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002608}
2609
John McCalldadc5752010-08-24 06:29:42 +00002610StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002611Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002612 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002613 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002614
2615 TemplateInstantiator Instantiator(*this, TemplateArgs,
2616 SourceLocation(),
2617 DeclarationName());
2618 return Instantiator.TransformStmt(S);
2619}
2620
John McCalldadc5752010-08-24 06:29:42 +00002621ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002622Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002623 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002624 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002625
Douglas Gregora16548e2009-08-11 05:31:07 +00002626 TemplateInstantiator Instantiator(*this, TemplateArgs,
2627 SourceLocation(),
2628 DeclarationName());
2629 return Instantiator.TransformExpr(E);
2630}
2631
Richard Smithd59b8322012-12-19 01:39:02 +00002632ExprResult Sema::SubstInitializer(Expr *Init,
2633 const MultiLevelTemplateArgumentList &TemplateArgs,
2634 bool CXXDirectInit) {
2635 TemplateInstantiator Instantiator(*this, TemplateArgs,
2636 SourceLocation(),
2637 DeclarationName());
2638 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2639}
2640
Craig Topper99d23532015-12-24 23:58:29 +00002641bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002642 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002643 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002644 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002645 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002646
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002647 TemplateInstantiator Instantiator(*this, TemplateArgs,
2648 SourceLocation(),
2649 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002650 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2651 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002652}
2653
Douglas Gregor14454802011-02-25 02:25:35 +00002654NestedNameSpecifierLoc
2655Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2656 const MultiLevelTemplateArgumentList &TemplateArgs) {
2657 if (!NNS)
2658 return NestedNameSpecifierLoc();
2659
2660 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2661 DeclarationName());
2662 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2663}
2664
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002665/// \brief Do template substitution on declaration name info.
2666DeclarationNameInfo
2667Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2668 const MultiLevelTemplateArgumentList &TemplateArgs) {
2669 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2670 NameInfo.getName());
2671 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2672}
2673
Douglas Gregoraa594892009-03-31 18:38:02 +00002674TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002675Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2676 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002677 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002678 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2679 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002680 CXXScopeSpec SS;
2681 SS.Adopt(QualifierLoc);
2682 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002683}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002684
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002685bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2686 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002687 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002688 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2689 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002690
2691 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002692}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002693
Richard Smith70b13042015-01-09 01:19:56 +00002694static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002695 // When storing ParmVarDecls in the local instantiation scope, we always
2696 // want to use the ParmVarDecl from the canonical function declaration,
2697 // since the map is then valid for any redeclaration or definition of that
2698 // function.
2699 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2700 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2701 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002702 // This parameter might be from a freestanding function type within the
2703 // function and isn't necessarily referring to one of FD's parameters.
2704 if (FD->getParamDecl(i) == PV)
2705 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002706 }
2707 }
2708 return D;
2709}
2710
2711
Douglas Gregorf3010112011-01-07 16:43:16 +00002712llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2713LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002714 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002715 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002716 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002717
Douglas Gregor14cf7522010-04-30 18:55:50 +00002718 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002719 const Decl *CheckD = D;
2720 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002721 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002722 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002723 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002724
2725 // If this is a tag declaration, it's possible that we need to look for
2726 // a previous declaration.
2727 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002728 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002729 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002730 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002731 } while (CheckD);
2732
Douglas Gregor14cf7522010-04-30 18:55:50 +00002733 // If we aren't combined with our outer scope, we're done.
2734 if (!Current->CombineWithOuterScope)
2735 break;
2736 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002737
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002738 // If we're performing a partial substitution during template argument
2739 // deduction, we may not have values for template parameters yet.
2740 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2741 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002742 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002743
Serge Pavlove7ad8312015-05-15 10:10:28 +00002744 // Local types referenced prior to definition may require instantiation.
2745 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2746 if (RD->isLocalClass())
2747 return nullptr;
2748
2749 // Enumeration types referenced prior to definition may appear as a result of
2750 // error recovery.
2751 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002752 return nullptr;
2753
Chris Lattnercab02a62011-02-17 20:34:02 +00002754 // If we didn't find the decl, then we either have a sema bug, or we have a
2755 // forward reference to a label declaration. Return null to indicate that
2756 // we have an uninstantiated label.
2757 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002758 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002759}
2760
John McCall19c1bfd2010-08-25 05:32:35 +00002761void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002762 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002763 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002764 if (Stored.isNull()) {
2765#ifndef NDEBUG
2766 // It should not be present in any surrounding scope either.
2767 LocalInstantiationScope *Current = this;
2768 while (Current->CombineWithOuterScope && Current->Outer) {
2769 Current = Current->Outer;
2770 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2771 "Instantiated local in inner and outer scopes");
2772 }
2773#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002774 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002775 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002776 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002777 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002778 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002779 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002780}
Douglas Gregorf3010112011-01-07 16:43:16 +00002781
James Y Knight48fefa32015-09-30 14:04:23 +00002782void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2783 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002784 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002785 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2786 Pack->push_back(Inst);
2787}
2788
2789void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002790#ifndef NDEBUG
2791 // This should be the first time we've been told about this decl.
2792 for (LocalInstantiationScope *Current = this;
2793 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2794 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2795 "Creating local pack after instantiation of local");
2796#endif
2797
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002798 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002799 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002800 DeclArgumentPack *Pack = new DeclArgumentPack;
2801 Stored = Pack;
2802 ArgumentPacks.push_back(Pack);
2803}
2804
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002805void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2806 const TemplateArgument *ExplicitArgs,
2807 unsigned NumExplicitArgs) {
2808 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2809 "Already have a partially-substituted pack");
2810 assert((!PartiallySubstitutedPack
2811 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2812 "Wrong number of arguments in partially-substituted pack");
2813 PartiallySubstitutedPack = Pack;
2814 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2815 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2816}
2817
2818NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2819 const TemplateArgument **ExplicitArgs,
2820 unsigned *NumExplicitArgs) const {
2821 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002822 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002823 if (NumExplicitArgs)
2824 *NumExplicitArgs = 0;
2825
2826 for (const LocalInstantiationScope *Current = this; Current;
2827 Current = Current->Outer) {
2828 if (Current->PartiallySubstitutedPack) {
2829 if (ExplicitArgs)
2830 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2831 if (NumExplicitArgs)
2832 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2833
2834 return Current->PartiallySubstitutedPack;
2835 }
2836
2837 if (!Current->CombineWithOuterScope)
2838 break;
2839 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002840
2841 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002842}