blob: 24a47d19421dfcd896c03e94c800c55241889e9c [file] [log] [blame]
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation.
10//
11//===----------------------------------------------------------------------===/
12
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregord6ff3322009-08-04 16:50:30 +000014#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
Faisal Vali2cba1332013-10-23 06:44:28 +000017#include "clang/AST/ASTLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/Basic/LangOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000022#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000023#include "clang/Sema/Lookup.h"
Richard Smithe19b95d2016-05-26 20:23:13 +000024#include "clang/Sema/PrettyDeclStackTrace.h"
John McCallde6836a2010-08-24 07:21:54 +000025#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000026#include "clang/Sema/TemplateDeduction.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000027
28using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000029using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000030
Douglas Gregor4ea568f2009-03-10 18:03:33 +000031//===----------------------------------------------------------------------===/
32// Template Instantiation Support
33//===----------------------------------------------------------------------===/
34
Douglas Gregor01afeef2009-08-28 20:31:08 +000035/// \brief Retrieve the template argument list(s) that should be used to
36/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000037///
38/// \param D the declaration for which we are computing template instantiation
39/// arguments.
40///
41/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000042///
43/// \param RelativeToPrimary true if we should get the template
44/// arguments relative to the primary template, even when we're
45/// dealing with a specialization. This is only relevant for function
46/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000047///
48/// \param Pattern If non-NULL, indicates the pattern from which we will be
49/// instantiating the definition of the given declaration, \p D. This is
50/// used to determine the proper set of template instantiation arguments for
51/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000052MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000053Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000054 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000055 bool RelativeToPrimary,
56 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000057 // Accumulate the set of template argument lists in this structure.
58 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000060 if (Innermost)
61 Result.addOuterTemplateArguments(Innermost);
62
Douglas Gregora654dd82009-08-28 17:37:35 +000063 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000064 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000065 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000066
67 // Add template arguments from a variable template instantiation.
68 if (VarTemplateSpecializationDecl *Spec =
69 dyn_cast<VarTemplateSpecializationDecl>(D)) {
70 // We're done when we hit an explicit specialization.
71 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
72 !isa<VarTemplatePartialSpecializationDecl>(Spec))
73 return Result;
74
75 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
76
77 // If this variable template specialization was instantiated from a
78 // specialized member that is a variable template, we're done.
79 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000080 llvm::PointerUnion<VarTemplateDecl*,
81 VarTemplatePartialSpecializationDecl*> Specialized
82 = Spec->getSpecializedTemplateOrPartial();
83 if (VarTemplatePartialSpecializationDecl *Partial =
84 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
85 if (Partial->isMemberSpecialization())
86 return Result;
87 } else {
88 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
89 if (Tmpl->isMemberSpecialization())
90 return Result;
91 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000092 }
93
Douglas Gregor55462622011-06-15 14:20:42 +000094 // If we have a template template parameter with translation unit context,
95 // then we're performing substitution into a default template argument of
96 // this template template parameter before we've constructed the template
97 // that will own this template template parameter. In this case, we
98 // use empty template parameter lists for all of the outer templates
99 // to avoid performing any substitutions.
100 if (Ctx->isTranslationUnit()) {
101 if (TemplateTemplateParmDecl *TTP
102 = dyn_cast<TemplateTemplateParmDecl>(D)) {
103 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000104 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000105 return Result;
106 }
107 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000108 }
109
John McCall970d5302009-08-29 03:16:09 +0000110 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000111 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +0000112 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +0000113 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
114 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000115 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
116 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000117 break;
Mike Stump11289f42009-09-09 15:08:12 +0000118
Douglas Gregora654dd82009-08-28 17:37:35 +0000119 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000120
121 // If this class template specialization was instantiated from a
122 // specialized member that is a class template, we're done.
123 assert(Spec->getSpecializedTemplate() && "No class template?");
124 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
125 break;
Mike Stump11289f42009-09-09 15:08:12 +0000126 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000127 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000128 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000129 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000130 (Function->getTemplateSpecializationKind() ==
131 TSK_ExplicitSpecialization &&
132 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000133 break;
134
Douglas Gregora654dd82009-08-28 17:37:35 +0000135 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000136 = Function->getTemplateSpecializationArgs()) {
137 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000138 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000139
Douglas Gregorcf915552009-10-13 16:30:37 +0000140 // If this function was instantiated from a specialized member that is
141 // a function template, we're done.
142 assert(Function->getPrimaryTemplate() && "No function template?");
143 if (Function->getPrimaryTemplate()->isMemberSpecialization())
144 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000145
146 // If this function is a generic lambda specialization, we are done.
147 if (isGenericLambdaCallOperatorSpecialization(Function))
148 break;
149
Douglas Gregor43669f82011-03-05 17:54:25 +0000150 } else if (FunctionTemplateDecl *FunTmpl
151 = Function->getDescribedFunctionTemplate()) {
152 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000153 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000154 }
155
John McCall970d5302009-08-29 03:16:09 +0000156 // If this is a friend declaration and it declares an entity at
157 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000158 // instead of its semantic parent, unless of course the pattern we're
159 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000160 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000161 Function->getDeclContext()->isFileContext() &&
162 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000163 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000164 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000165 continue;
166 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000167 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
168 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
169 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000170 const TemplateSpecializationType *TST =
171 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
172 Result.addOuterTemplateArguments(
173 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000174 if (ClassTemplate->isMemberSpecialization())
175 break;
176 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000177 }
John McCall970d5302009-08-29 03:16:09 +0000178
179 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000180 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000181 }
Mike Stump11289f42009-09-09 15:08:12 +0000182
Douglas Gregora654dd82009-08-28 17:37:35 +0000183 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000184}
185
Douglas Gregor84d49a22009-11-11 21:54:23 +0000186bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
187 switch (Kind) {
188 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000189 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000190 case DefaultTemplateArgumentInstantiation:
191 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000192 case ExplicitTemplateArgumentSubstitution:
193 case DeducedTemplateArgumentSubstitution:
194 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000195 return true;
196
Douglas Gregor84d49a22009-11-11 21:54:23 +0000197 case DefaultTemplateArgumentChecking:
198 return false;
199 }
David Blaikie8a40f702012-01-17 06:56:22 +0000200
201 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000202}
203
Benjamin Kramer7761a042015-03-06 16:36:50 +0000204Sema::InstantiatingTemplate::InstantiatingTemplate(
205 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000206 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
207 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000208 sema::TemplateDeductionInfo *DeductionInfo)
209 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
210 SemaRef.InNonInstantiationSFINAEContext) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000211 // Don't allow further instantiation if a fatal error has occcured. Any
212 // diagnostics we might have raised will not be visible.
213 if (SemaRef.Diags.hasFatalErrorOccurred()) {
214 Invalid = true;
215 return;
216 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000217 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
218 if (!Invalid) {
219 ActiveTemplateInstantiation Inst;
220 Inst.Kind = Kind;
221 Inst.PointOfInstantiation = PointOfInstantiation;
222 Inst.Entity = Entity;
223 Inst.Template = Template;
224 Inst.TemplateArgs = TemplateArgs.data();
225 Inst.NumTemplateArgs = TemplateArgs.size();
226 Inst.DeductionInfo = DeductionInfo;
227 Inst.InstantiationRange = InstantiationRange;
228 SemaRef.InNonInstantiationSFINAEContext = false;
229 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
230 if (!Inst.isInstantiationRecord())
231 ++SemaRef.NonInstantiationEntries;
232 }
233}
234
Benjamin Kramer7761a042015-03-06 16:36:50 +0000235Sema::InstantiatingTemplate::InstantiatingTemplate(
236 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
237 SourceRange InstantiationRange)
238 : InstantiatingTemplate(SemaRef,
239 ActiveTemplateInstantiation::TemplateInstantiation,
240 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000241
Benjamin Kramer7761a042015-03-06 16:36:50 +0000242Sema::InstantiatingTemplate::InstantiatingTemplate(
243 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
244 ExceptionSpecification, SourceRange InstantiationRange)
245 : InstantiatingTemplate(
246 SemaRef, ActiveTemplateInstantiation::ExceptionSpecInstantiation,
247 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000248
Benjamin Kramer7761a042015-03-06 16:36:50 +0000249Sema::InstantiatingTemplate::InstantiatingTemplate(
250 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
251 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
252 : InstantiatingTemplate(
253 SemaRef,
254 ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
255 PointOfInstantiation, InstantiationRange, Template, nullptr,
256 TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000257
Benjamin Kramer7761a042015-03-06 16:36:50 +0000258Sema::InstantiatingTemplate::InstantiatingTemplate(
259 Sema &SemaRef, SourceLocation PointOfInstantiation,
260 FunctionTemplateDecl *FunctionTemplate,
261 ArrayRef<TemplateArgument> TemplateArgs,
262 ActiveTemplateInstantiation::InstantiationKind Kind,
263 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
264 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
265 InstantiationRange, FunctionTemplate, nullptr,
266 TemplateArgs, &DeductionInfo) {}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000267
Benjamin Kramer7761a042015-03-06 16:36:50 +0000268Sema::InstantiatingTemplate::InstantiatingTemplate(
269 Sema &SemaRef, SourceLocation PointOfInstantiation,
270 ClassTemplatePartialSpecializationDecl *PartialSpec,
271 ArrayRef<TemplateArgument> TemplateArgs,
272 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
273 : InstantiatingTemplate(
274 SemaRef,
275 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
276 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
277 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000278
Larisse Voufo39a1e502013-08-06 01:03:05 +0000279Sema::InstantiatingTemplate::InstantiatingTemplate(
280 Sema &SemaRef, SourceLocation PointOfInstantiation,
281 VarTemplatePartialSpecializationDecl *PartialSpec,
282 ArrayRef<TemplateArgument> TemplateArgs,
283 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000284 : InstantiatingTemplate(
285 SemaRef,
286 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
287 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
288 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000289
Benjamin Kramer7761a042015-03-06 16:36:50 +0000290Sema::InstantiatingTemplate::InstantiatingTemplate(
291 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
292 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
293 : InstantiatingTemplate(
294 SemaRef,
295 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
296 PointOfInstantiation, InstantiationRange, Param, nullptr,
297 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000298
Benjamin Kramer7761a042015-03-06 16:36:50 +0000299Sema::InstantiatingTemplate::InstantiatingTemplate(
300 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
301 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
302 SourceRange InstantiationRange)
303 : InstantiatingTemplate(
304 SemaRef,
305 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
306 PointOfInstantiation, InstantiationRange, Param, Template,
307 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000308
Benjamin Kramer7761a042015-03-06 16:36:50 +0000309Sema::InstantiatingTemplate::InstantiatingTemplate(
310 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
311 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
312 SourceRange InstantiationRange)
313 : InstantiatingTemplate(
314 SemaRef,
315 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
316 PointOfInstantiation, InstantiationRange, Param, Template,
317 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000318
Benjamin Kramer7761a042015-03-06 16:36:50 +0000319Sema::InstantiatingTemplate::InstantiatingTemplate(
320 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
321 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
322 SourceRange InstantiationRange)
323 : InstantiatingTemplate(
324 SemaRef, ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
325 PointOfInstantiation, InstantiationRange, Param, Template,
326 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000327
Douglas Gregor85673582009-05-18 17:01:57 +0000328void Sema::InstantiatingTemplate::Clear() {
329 if (!Invalid) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000330 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
331 assert(SemaRef.NonInstantiationEntries > 0);
332 --SemaRef.NonInstantiationEntries;
333 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000334 SemaRef.InNonInstantiationSFINAEContext
335 = SavedInNonInstantiationSFINAEContext;
Richard Smith0e5d7b82013-07-25 23:08:39 +0000336
337 // Name lookup no longer looks in this template's defining module.
338 assert(SemaRef.ActiveTemplateInstantiations.size() >=
339 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
340 "forgot to remove a lookup module for a template instantiation");
341 if (SemaRef.ActiveTemplateInstantiations.size() ==
342 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
343 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
344 SemaRef.LookupModulesCache.erase(M);
345 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
346 }
347
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000348 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000349 Invalid = true;
350 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000351}
352
Douglas Gregor79cf6032009-03-10 20:44:00 +0000353bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
354 SourceLocation PointOfInstantiation,
355 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000356 assert(SemaRef.NonInstantiationEntries <=
357 SemaRef.ActiveTemplateInstantiations.size());
358 if ((SemaRef.ActiveTemplateInstantiations.size() -
359 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000360 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000361 return false;
362
Mike Stump11289f42009-09-09 15:08:12 +0000363 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000364 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000365 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000366 << InstantiationRange;
367 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000368 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000369 return true;
370}
371
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000372/// \brief Prints the current instantiation stack through a series of
373/// notes.
374void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000375 // Determine which template instantiations to skip, if any.
376 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
377 unsigned Limit = Diags.getTemplateBacktraceLimit();
378 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
379 SkipStart = Limit / 2 + Limit % 2;
380 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
381 }
382
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000383 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000384 unsigned InstantiationIdx = 0;
Craig Topper2341c0d2013-07-04 03:08:24 +0000385 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000386 Active = ActiveTemplateInstantiations.rbegin(),
387 ActiveEnd = ActiveTemplateInstantiations.rend();
388 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000389 ++Active, ++InstantiationIdx) {
390 // Skip this instantiation?
391 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
392 if (InstantiationIdx == SkipStart) {
393 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000394 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000395 diag::note_instantiation_contexts_suppressed)
396 << unsigned(ActiveTemplateInstantiations.size() - Limit);
397 }
398 continue;
399 }
400
Douglas Gregor79cf6032009-03-10 20:44:00 +0000401 switch (Active->Kind) {
402 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000403 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000404 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
405 unsigned DiagID = diag::note_template_member_class_here;
406 if (isa<ClassTemplateSpecializationDecl>(Record))
407 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000408 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000409 << Context.getTypeDeclType(Record)
410 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000411 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000412 unsigned DiagID;
413 if (Function->getPrimaryTemplate())
414 DiagID = diag::note_function_template_spec_here;
415 else
416 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000417 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000418 << Function
419 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000420 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000421 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000422 VD->isStaticDataMember()?
423 diag::note_template_static_data_member_def_here
424 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000425 << VD
426 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000427 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
428 Diags.Report(Active->PointOfInstantiation,
429 diag::note_template_enum_def_here)
430 << ED
431 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000432 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
433 Diags.Report(Active->PointOfInstantiation,
434 diag::note_template_nsdmi_here)
435 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000436 } else {
437 Diags.Report(Active->PointOfInstantiation,
438 diag::note_template_type_alias_instantiation_here)
439 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000440 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000441 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000442 break;
443 }
444
445 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000446 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000447 SmallVector<char, 128> TemplateArgsStr;
448 llvm::raw_svector_ostream OS(TemplateArgsStr);
449 Template->printName(OS);
450 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump11289f42009-09-09 15:08:12 +0000451 Active->TemplateArgs,
Douglas Gregor7de59662009-05-29 20:38:28 +0000452 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000453 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000454 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000455 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000456 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000457 << Active->InstantiationRange;
458 break;
459 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000460
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000461 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000462 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000463 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000464 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000465 << FnTmpl
466 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
467 Active->TemplateArgs,
468 Active->NumTemplateArgs)
469 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000470 break;
471 }
Mike Stump11289f42009-09-09 15:08:12 +0000472
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000473 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000474 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
475 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000476 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000477 diag::note_partial_spec_deduct_instantiation_here)
478 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000479 << getTemplateArgumentBindingsText(
480 PartialSpec->getTemplateParameters(),
481 Active->TemplateArgs,
482 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000483 << Active->InstantiationRange;
484 } else {
485 FunctionTemplateDecl *FnTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000486 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000487 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000488 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000489 << FnTmpl
490 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
491 Active->TemplateArgs,
492 Active->NumTemplateArgs)
493 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000494 }
495 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000496
Anders Carlsson657bad42009-09-05 05:14:19 +0000497 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000498 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000499 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000500
Benjamin Kramer9170e912013-02-22 15:46:01 +0000501 SmallVector<char, 128> TemplateArgsStr;
502 llvm::raw_svector_ostream OS(TemplateArgsStr);
503 FD->printName(OS);
504 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump11289f42009-09-09 15:08:12 +0000505 Active->TemplateArgs,
Anders Carlsson657bad42009-09-05 05:14:19 +0000506 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000507 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000508 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000509 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000510 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000511 << Active->InstantiationRange;
512 break;
513 }
Mike Stump11289f42009-09-09 15:08:12 +0000514
Douglas Gregore62e6a02009-11-11 19:13:48 +0000515 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000516 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000517 std::string Name;
518 if (!Parm->getName().empty())
519 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000520
521 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000522 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
523 TemplateParams = Template->getTemplateParameters();
524 else
525 TemplateParams =
526 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
527 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000528 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000529 diag::note_prior_template_arg_substitution)
530 << isa<TemplateTemplateParmDecl>(Parm)
531 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000532 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000533 Active->TemplateArgs,
534 Active->NumTemplateArgs)
535 << Active->InstantiationRange;
536 break;
537 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000538
539 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000540 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000541 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
542 TemplateParams = Template->getTemplateParameters();
543 else
544 TemplateParams =
545 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
546 ->getTemplateParameters();
547
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000548 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000549 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000550 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000551 Active->TemplateArgs,
552 Active->NumTemplateArgs)
553 << Active->InstantiationRange;
554 break;
555 }
Richard Smithf623c962012-04-17 00:58:00 +0000556
557 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
558 Diags.Report(Active->PointOfInstantiation,
559 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000560 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000561 << Active->InstantiationRange;
562 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000563 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000564 }
565}
566
David Blaikie05785d12013-02-20 22:23:23 +0000567Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000568 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000569 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000570
Craig Topper2341c0d2013-07-04 03:08:24 +0000571 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor33834512009-06-14 07:33:30 +0000572 Active = ActiveTemplateInstantiations.rbegin(),
573 ActiveEnd = ActiveTemplateInstantiations.rend();
574 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000575 ++Active)
576 {
Douglas Gregor33834512009-06-14 07:33:30 +0000577 switch(Active->Kind) {
Douglas Gregoredb76852011-01-27 22:31:44 +0000578 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000579 // An instantiation of an alias template may or may not be a SFINAE
580 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000581 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000582 break;
583 // Fall through.
584 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000585 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000586 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000587 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000588
Douglas Gregor33834512009-06-14 07:33:30 +0000589 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000590 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000591 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000592 // A default template argument instantiation and substitution into
593 // template parameters with arguments for prior parameters may or may
594 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000595 break;
Mike Stump11289f42009-09-09 15:08:12 +0000596
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000597 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
598 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
599 // We're either substitution explicitly-specified template arguments
600 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000601 assert(Active->DeductionInfo && "Missing deduction info pointer");
602 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000603 }
604 }
605
David Blaikie7a30dc52013-02-21 01:47:18 +0000606 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000607}
608
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000609/// \brief Retrieve the depth and index of a parameter pack.
610static std::pair<unsigned, unsigned>
611getDepthAndIndex(NamedDecl *ND) {
612 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
613 return std::make_pair(TTP->getDepth(), TTP->getIndex());
614
615 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
616 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
617
618 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
619 return std::make_pair(TTP->getDepth(), TTP->getIndex());
620}
621
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000622//===----------------------------------------------------------------------===/
623// Template Instantiation for Types
624//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000625namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000626 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000627 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000628 SourceLocation Loc;
629 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000630
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000631 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000632 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000633
634 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000635 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000636 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000637 DeclarationName Entity)
638 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000639 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000640
Mike Stump11289f42009-09-09 15:08:12 +0000641 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000642 /// transformed.
643 ///
644 /// For the purposes of template instantiation, a type has already been
645 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000646 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000647
Douglas Gregord6ff3322009-08-04 16:50:30 +0000648 /// \brief Returns the location of the entity being instantiated, if known.
649 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000650
Douglas Gregord6ff3322009-08-04 16:50:30 +0000651 /// \brief Returns the name of the entity being instantiated, if any.
652 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000653
Douglas Gregoref6ab412009-10-27 06:26:26 +0000654 /// \brief Sets the "base" location and entity when that
655 /// information is known based on another transformation.
656 void setBase(SourceLocation Loc, DeclarationName Entity) {
657 this->Loc = Loc;
658 this->Entity = Entity;
659 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000660
661 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
662 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000663 ArrayRef<UnexpandedParameterPack> Unexpanded,
664 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000665 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000666 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
667 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000668 TemplateArgs,
669 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000670 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000671 NumExpansions);
672 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000673
Douglas Gregorf3010112011-01-07 16:43:16 +0000674 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
675 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
676 }
677
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000678 TemplateArgument ForgetPartiallySubstitutedPack() {
679 TemplateArgument Result;
680 if (NamedDecl *PartialPack
681 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
682 MultiLevelTemplateArgumentList &TemplateArgs
683 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
684 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000685 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000686 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
687 Result = TemplateArgs(Depth, Index);
688 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
689 }
690 }
691
692 return Result;
693 }
694
695 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
696 if (Arg.isNull())
697 return;
698
699 if (NamedDecl *PartialPack
700 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
701 MultiLevelTemplateArgumentList &TemplateArgs
702 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
703 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000704 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000705 TemplateArgs.setArgument(Depth, Index, Arg);
706 }
707 }
708
Douglas Gregord6ff3322009-08-04 16:50:30 +0000709 /// \brief Transform the given declaration by instantiating a reference to
710 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000711 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000712
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000713 void transformAttrs(Decl *Old, Decl *New) {
714 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
715 }
716
717 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000718 // If we've instantiated the call operator of a lambda or the call
719 // operator template of a generic lambda, update the "instantiation of"
720 // information.
721 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
722 if (NewMD && isLambdaCallOperator(NewMD)) {
723 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
724 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
725 NewTD->setInstantiatedFromMemberTemplate(
726 OldMD->getDescribedFunctionTemplate());
727 else
728 NewMD->setInstantiationOfMemberFunction(OldMD,
729 TSK_ImplicitInstantiation);
730 }
731
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000732 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000733
734 // We recreated a local declaration, but not by instantiating it. There
735 // may be pending dependent diagnostics to produce.
736 if (auto *DC = dyn_cast<DeclContext>(Old))
737 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000738 }
739
Mike Stump11289f42009-09-09 15:08:12 +0000740 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000741 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000742 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000743
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000744 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000745 /// declaration.
746 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
747
Douglas Gregorebe10102009-08-20 07:17:43 +0000748 /// \brief Rebuild the exception declaration and register the declaration
749 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000750 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000751 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000752 SourceLocation StartLoc,
753 SourceLocation NameLoc,
754 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000755
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000756 /// \brief Rebuild the Objective-C exception declaration and register the
757 /// declaration as an instantiated local.
758 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
759 TypeSourceInfo *TSInfo, QualType T);
760
John McCall7f41d982009-09-11 04:59:25 +0000761 /// \brief Check for tag mismatches when instantiating an
762 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000763 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
764 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000765 NestedNameSpecifierLoc QualifierLoc,
766 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000767
Craig Topperc3ec1492014-05-26 06:22:03 +0000768 TemplateName
769 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
770 SourceLocation NameLoc,
771 QualType ObjectType = QualType(),
772 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregor9db53502011-03-02 18:07:45 +0000773
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000774 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
775
John McCalldadc5752010-08-24 06:29:42 +0000776 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
777 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
778 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000779
John McCalldadc5752010-08-24 06:29:42 +0000780 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000781 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000782 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
783 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000784
785 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
786 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
787
788 /// \brief Transform a reference to a function parameter pack.
789 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
790 ParmVarDecl *PD);
791
792 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
793 /// expand a function parameter pack reference which refers to an expanded
794 /// pack.
795 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
796
Hans Wennborge113c202014-09-18 16:01:32 +0000797 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000798 FunctionProtoTypeLoc TL) {
799 // Call the base version; it will forward to our overridden version below.
800 return inherited::TransformFunctionProtoType(TLB, TL);
801 }
802
803 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000804 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
805 FunctionProtoTypeLoc TL,
806 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000807 unsigned ThisTypeQuals,
808 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000809
Douglas Gregor715e4612011-01-14 22:40:04 +0000810 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000811 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000812 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000813 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000814
Mike Stump11289f42009-09-09 15:08:12 +0000815 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000816 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000817 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000818 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000819
Douglas Gregorada4b792011-01-14 02:55:32 +0000820 /// \brief Transforms an already-substituted template type parameter pack
821 /// into either itself (if we aren't substituting into its pack expansion)
822 /// or the appropriate substituted argument.
823 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
824 SubstTemplateTypeParmPackTypeLoc TL);
825
Richard Smith2589b9802012-07-25 03:56:55 +0000826 ExprResult TransformLambdaExpr(LambdaExpr *E) {
827 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
828 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
829 }
830
David Majnemerb1004102014-03-02 18:46:05 +0000831 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000832 TemplateParameterList *OrigTPL) {
833 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
834
835 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
836 TemplateDeclInstantiator DeclInstantiator(getSema(),
837 /* DeclContext *Owner */ Owner, TemplateArgs);
838 return DeclInstantiator.SubstTemplateParams(OrigTPL);
839 }
John McCall7c454bb2011-07-15 05:09:51 +0000840 private:
841 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
842 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000843 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000844 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000845}
Douglas Gregor04318252009-07-06 15:59:29 +0000846
Douglas Gregor5597ab42010-05-07 23:12:07 +0000847bool TemplateInstantiator::AlreadyTransformed(QualType T) {
848 if (T.isNull())
849 return true;
850
Douglas Gregor678d76c2011-07-01 01:22:09 +0000851 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000852 return false;
853
854 getSema().MarkDeclarationsReferencedInType(Loc, T);
855 return true;
856}
857
Eli Friedman8917ad52013-07-19 19:40:38 +0000858static TemplateArgument
859getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
860 assert(S.ArgumentPackSubstitutionIndex >= 0);
861 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
862 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
863 if (Arg.isPackExpansion())
864 Arg = Arg.getPackExpansionPattern();
865 return Arg;
866}
867
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000868Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000869 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000870 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000871
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000872 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000873 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000874 // If the corresponding template argument is NULL or non-existent, it's
875 // because we are performing instantiation from explicitly-specified
876 // template arguments in a function template, but there were some
877 // arguments left unspecified.
878 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
879 TTP->getPosition()))
880 return D;
881
Douglas Gregorf5500772011-01-05 15:48:55 +0000882 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
883
884 if (TTP->isParameterPack()) {
885 assert(Arg.getKind() == TemplateArgument::Pack &&
886 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000887 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000888 }
889
890 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000891 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000892 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000893 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000894 }
Mike Stump11289f42009-09-09 15:08:12 +0000895
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000896 // Fall through to find the instantiated declaration for this template
897 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000898 }
Mike Stump11289f42009-09-09 15:08:12 +0000899
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000900 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000901}
902
Douglas Gregor25289362010-03-01 17:25:41 +0000903Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000904 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000905 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000906 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregorebe10102009-08-20 07:17:43 +0000908 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
909 return Inst;
910}
911
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000912NamedDecl *
913TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
914 SourceLocation Loc) {
915 // If the first part of the nested-name-specifier was a template type
916 // parameter, instantiate that type parameter down to a tag type.
917 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
918 const TemplateTypeParmType *TTP
919 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000920
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000921 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000922 // FIXME: This needs testing w/ member access expressions.
923 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
924
925 if (TTP->isParameterPack()) {
926 assert(Arg.getKind() == TemplateArgument::Pack &&
927 "Missing argument pack");
928
Douglas Gregore1d60df2011-01-14 23:41:42 +0000929 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +0000930 return nullptr;
931
Eli Friedman8917ad52013-07-19 19:40:38 +0000932 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000933 }
934
935 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000936 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000937 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000938
939 if (const TagType *Tag = T->getAs<TagType>())
940 return Tag->getDecl();
941
942 // The resulting type is not a tag; complain.
943 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +0000944 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000945 }
946 }
947
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000948 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000949}
950
Douglas Gregorebe10102009-08-20 07:17:43 +0000951VarDecl *
952TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000953 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000954 SourceLocation StartLoc,
955 SourceLocation NameLoc,
956 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000957 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000958 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000959 if (Var)
960 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
961 return Var;
962}
963
964VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
965 TypeSourceInfo *TSInfo,
966 QualType T) {
967 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
968 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000969 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
970 return Var;
971}
972
John McCall7f41d982009-09-11 04:59:25 +0000973QualType
John McCall954b5de2010-11-04 19:04:38 +0000974TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
975 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000976 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000977 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +0000978 if (const TagType *TT = T->getAs<TagType>()) {
979 TagDecl* TD = TT->getDecl();
980
John McCall954b5de2010-11-04 19:04:38 +0000981 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +0000982
John McCall7f41d982009-09-11 04:59:25 +0000983 IdentifierInfo *Id = TD->getIdentifier();
984
985 // TODO: should we even warn on struct/class mismatches for this? Seems
986 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +0000987 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000988 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +0000989 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +0000990 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000991 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
992 << Id
993 << FixItHint::CreateReplacement(SourceRange(TagLocation),
994 TD->getKindName());
995 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
996 }
John McCall7f41d982009-09-11 04:59:25 +0000997 }
998 }
999
John McCall954b5de2010-11-04 19:04:38 +00001000 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1001 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001002 QualifierLoc,
1003 T);
John McCall7f41d982009-09-11 04:59:25 +00001004}
1005
Douglas Gregor9db53502011-03-02 18:07:45 +00001006TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1007 TemplateName Name,
Nico Weberc153d242014-07-28 00:02:09 +00001008 SourceLocation NameLoc,
Douglas Gregor9db53502011-03-02 18:07:45 +00001009 QualType ObjectType,
1010 NamedDecl *FirstQualifierInScope) {
1011 if (TemplateTemplateParmDecl *TTP
1012 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1013 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1014 // If the corresponding template argument is NULL or non-existent, it's
1015 // because we are performing instantiation from explicitly-specified
1016 // template arguments in a function template, but there were some
1017 // arguments left unspecified.
1018 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1019 TTP->getPosition()))
1020 return Name;
1021
1022 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1023
1024 if (TTP->isParameterPack()) {
1025 assert(Arg.getKind() == TemplateArgument::Pack &&
1026 "Missing argument pack");
1027
1028 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1029 // We have the template argument pack to substitute, but we're not
1030 // actually expanding the enclosing pack expansion yet. So, just
1031 // keep the entire argument pack.
1032 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1033 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001034
1035 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001036 }
1037
1038 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001039 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001040
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001041 // We don't ever want to substitute for a qualified template name, since
1042 // the qualifier is handled separately. So, look through the qualified
1043 // template name to its underlying declaration.
1044 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1045 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001046
1047 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001048 return Template;
1049 }
1050 }
1051
1052 if (SubstTemplateTemplateParmPackStorage *SubstPack
1053 = Name.getAsSubstTemplateTemplateParmPack()) {
1054 if (getSema().ArgumentPackSubstitutionIndex == -1)
1055 return Name;
1056
Eli Friedman8917ad52013-07-19 19:40:38 +00001057 TemplateArgument Arg = SubstPack->getArgumentPack();
1058 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1059 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001060 }
1061
1062 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1063 FirstQualifierInScope);
1064}
1065
John McCalldadc5752010-08-24 06:29:42 +00001066ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001067TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001068 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001069 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001070
Wei Panc354d212013-09-16 13:57:27 +00001071 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001072}
1073
John McCalldadc5752010-08-24 06:29:42 +00001074ExprResult
John McCall13481c52010-02-06 08:42:39 +00001075TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001076 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001077 // If the corresponding template argument is NULL or non-existent, it's
1078 // because we are performing instantiation from explicitly-specified
1079 // template arguments in a function template, but there were some
1080 // arguments left unspecified.
1081 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1082 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001083 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001084
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001085 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1086 if (NTTP->isParameterPack()) {
1087 assert(Arg.getKind() == TemplateArgument::Pack &&
1088 "Missing argument pack");
1089
1090 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001091 // We have an argument pack, but we can't select a particular argument
1092 // out of it yet. Therefore, we'll build an expression to hold on to that
1093 // argument pack.
1094 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1095 E->getLocation(),
1096 NTTP->getDeclName());
1097 if (TargetType.isNull())
1098 return ExprError();
1099
1100 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1101 NTTP,
1102 E->getLocation(),
1103 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001104 }
1105
Eli Friedman8917ad52013-07-19 19:40:38 +00001106 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001107 }
Mike Stump11289f42009-09-09 15:08:12 +00001108
John McCall7c454bb2011-07-15 05:09:51 +00001109 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1110}
1111
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001112const LoopHintAttr *
1113TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1114 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1115
1116 if (TransformedExpr == LH->getValue())
1117 return LH;
1118
1119 // Generate error if there is a problem with the value.
1120 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1121 return LH;
1122
1123 // Create new LoopHintValueAttr with integral expression in place of the
1124 // non-type template parameter.
1125 return LoopHintAttr::CreateImplicit(
1126 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1127 LH->getState(), TransformedExpr, LH->getRange());
1128}
1129
John McCall7c454bb2011-07-15 05:09:51 +00001130ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1131 NonTypeTemplateParmDecl *parm,
1132 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001133 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001134 ExprResult result;
1135 QualType type;
1136
John McCall13481c52010-02-06 08:42:39 +00001137 // The template argument itself might be an expression, in which
1138 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001139 if (arg.getKind() == TemplateArgument::Expression) {
1140 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001141 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001142 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001143
Eli Friedmanb826a002012-09-26 02:36:12 +00001144 } else if (arg.getKind() == TemplateArgument::Declaration ||
1145 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001146 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001147 if (arg.getKind() == TemplateArgument::Declaration) {
1148 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001149
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001150 // Find the instantiation of the template argument. This is
1151 // required for nested templates.
1152 VD = cast_or_null<ValueDecl>(
1153 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1154 if (!VD)
1155 return ExprError();
1156 } else {
1157 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001158 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001159 }
1160
John McCall15dda372010-02-06 10:23:53 +00001161 // Derive the type we want the substituted decl to have. This had
1162 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001163 if (parm->isExpandedParameterPack()) {
1164 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1165 } else if (parm->isParameterPack() &&
1166 isa<PackExpansionType>(parm->getType())) {
1167 type = SemaRef.SubstType(
1168 cast<PackExpansionType>(parm->getType())->getPattern(),
1169 TemplateArgs, loc, parm->getDeclName());
1170 } else {
1171 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1172 loc, parm->getDeclName());
1173 }
1174 assert(!type.isNull() && "type substitution failed for param type");
1175 assert(!type->isDependentType() && "param type still dependent");
1176 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001177
John McCall7c454bb2011-07-15 05:09:51 +00001178 if (!result.isInvalid()) type = result.get()->getType();
1179 } else {
1180 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1181
1182 // Note that this type can be different from the type of 'result',
1183 // e.g. if it's an enum type.
1184 type = arg.getIntegralType();
1185 }
1186 if (result.isInvalid()) return ExprError();
1187
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001188 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001189 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1190 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001191}
1192
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001193ExprResult
1194TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1195 SubstNonTypeTemplateParmPackExpr *E) {
1196 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1197 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001198 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001199 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001200
1201 TemplateArgument Arg = E->getArgumentPack();
1202 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001203 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1204 E->getParameterPackLocation(),
1205 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001206}
John McCall13481c52010-02-06 08:42:39 +00001207
John McCalldadc5752010-08-24 06:29:42 +00001208ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001209TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1210 SourceLocation Loc) {
1211 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1212 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1213}
1214
1215ExprResult
1216TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1217 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1218 // We can expand this parameter pack now.
1219 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1220 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1221 if (!VD)
1222 return ExprError();
1223 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1224 }
1225
1226 QualType T = TransformType(E->getType());
1227 if (T.isNull())
1228 return ExprError();
1229
1230 // Transform each of the parameter expansions into the corresponding
1231 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001232 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001233 Parms.reserve(E->getNumExpansions());
1234 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1235 I != End; ++I) {
1236 ParmVarDecl *D =
1237 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1238 if (!D)
1239 return ExprError();
1240 Parms.push_back(D);
1241 }
1242
1243 return FunctionParmPackExpr::Create(getSema().Context, T,
1244 E->getParameterPack(),
1245 E->getParameterPackLocation(), Parms);
1246}
1247
1248ExprResult
1249TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1250 ParmVarDecl *PD) {
1251 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1252 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1253 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1254 assert(Found && "no instantiation for parameter pack");
1255
1256 Decl *TransformedDecl;
1257 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001258 // If this is a reference to a function parameter pack which we can
1259 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001260 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1261 QualType T = TransformType(E->getType());
1262 if (T.isNull())
1263 return ExprError();
1264 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1265 E->getExprLoc(), *Pack);
1266 }
1267
1268 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1269 } else {
1270 TransformedDecl = Found->get<Decl*>();
1271 }
1272
1273 // We have either an unexpanded pack or a specific expansion.
1274 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1275 E->getExprLoc());
1276}
1277
1278ExprResult
John McCall13481c52010-02-06 08:42:39 +00001279TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1280 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001281
1282 // Handle references to non-type template parameters and non-type template
1283 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001284 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1285 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1286 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001287
1288 // We have a non-type template parameter that isn't fully substituted;
1289 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001290 }
Mike Stump11289f42009-09-09 15:08:12 +00001291
Richard Smithb15fe3a2012-09-12 00:56:43 +00001292 // Handle references to function parameter packs.
1293 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1294 if (PD->isParameterPack())
1295 return TransformFunctionParmPackRefExpr(E, PD);
1296
John McCall47f29ea2009-12-08 09:21:05 +00001297 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001298}
1299
John McCalldadc5752010-08-24 06:29:42 +00001300ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001301 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001302 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1303 getDescribedFunctionTemplate() &&
1304 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001305 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1306 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1307 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001308}
1309
Richard Smith2e321552014-11-12 02:00:47 +00001310template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001311QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1312 FunctionProtoTypeLoc TL,
1313 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001314 unsigned ThisTypeQuals,
1315 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001316 // We need a local instantiation scope for this function prototype.
1317 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001318 return inherited::TransformFunctionProtoType(
1319 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001320}
1321
John McCall58f10c32010-03-11 09:03:00 +00001322ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001323TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001324 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001325 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001326 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001327 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001328 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001329}
1330
Mike Stump11289f42009-09-09 15:08:12 +00001331QualType
John McCall550e0c22009-10-21 00:40:46 +00001332TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001333 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001334 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001335 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001336 // Replace the template type parameter with its corresponding
1337 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001338
1339 // If the corresponding template argument is NULL or doesn't exist, it's
1340 // because we are performing instantiation from explicitly-specified
1341 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001342 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001343 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1344 TemplateTypeParmTypeLoc NewTL
1345 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1346 NewTL.setNameLoc(TL.getNameLoc());
1347 return TL.getType();
1348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001350 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1351
1352 if (T->isParameterPack()) {
1353 assert(Arg.getKind() == TemplateArgument::Pack &&
1354 "Missing argument pack");
1355
1356 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001357 // We have the template argument pack, but we're not expanding the
1358 // enclosing pack expansion yet. Just save the template argument
1359 // pack for later substitution.
1360 QualType Result
1361 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1362 SubstTemplateTypeParmPackTypeLoc NewTL
1363 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1364 NewTL.setNameLoc(TL.getNameLoc());
1365 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001366 }
1367
Eli Friedman8917ad52013-07-19 19:40:38 +00001368 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001369 }
1370
1371 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001372 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001373
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001374 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001375
1376 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001377 QualType Result
1378 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1379 SubstTemplateTypeParmTypeLoc NewTL
1380 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1381 NewTL.setNameLoc(TL.getNameLoc());
1382 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001383 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001384
1385 // The template type parameter comes from an inner template (e.g.,
1386 // the template parameter list of a member template inside the
1387 // template we are instantiating). Create a new template type
1388 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001389 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001390 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1391 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1392 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1393
John McCall550e0c22009-10-21 00:40:46 +00001394 QualType Result
1395 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1396 - TemplateArgs.getNumLevels(),
1397 T->getIndex(),
1398 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001399 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001400 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1401 NewTL.setNameLoc(TL.getNameLoc());
1402 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001403}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001404
Douglas Gregorada4b792011-01-14 02:55:32 +00001405QualType
1406TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1407 TypeLocBuilder &TLB,
1408 SubstTemplateTypeParmPackTypeLoc TL) {
1409 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1410 // We aren't expanding the parameter pack, so just return ourselves.
1411 SubstTemplateTypeParmPackTypeLoc NewTL
1412 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1413 NewTL.setNameLoc(TL.getNameLoc());
1414 return TL.getType();
1415 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001416
1417 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1418 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1419 QualType Result = Arg.getAsType();
1420
Douglas Gregorada4b792011-01-14 02:55:32 +00001421 Result = getSema().Context.getSubstTemplateTypeParmType(
1422 TL.getTypePtr()->getReplacedParameter(),
1423 Result);
1424 SubstTemplateTypeParmTypeLoc NewTL
1425 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1426 NewTL.setNameLoc(TL.getNameLoc());
1427 return Result;
1428}
1429
John McCall76d824f2009-08-25 22:02:44 +00001430/// \brief Perform substitution on the type T with a given set of template
1431/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001432///
1433/// This routine substitutes the given template arguments into the
1434/// type T and produces the instantiated type.
1435///
1436/// \param T the type into which the template arguments will be
1437/// substituted. If this type is not dependent, it will be returned
1438/// immediately.
1439///
James Dennett634962f2012-06-14 21:40:34 +00001440/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001441/// substituted for the top-level template parameters within T.
1442///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001443/// \param Loc the location in the source code where this substitution
1444/// is being performed. It will typically be the location of the
1445/// declarator (if we're instantiating the type of some declaration)
1446/// or the location of the type in the source code (if, e.g., we're
1447/// instantiating the type of a cast expression).
1448///
1449/// \param Entity the name of the entity associated with a declaration
1450/// being instantiated (if any). May be empty to indicate that there
1451/// is no such entity (if, e.g., this is a type that occurs as part of
1452/// a cast expression) or that the entity has no name (e.g., an
1453/// unnamed function parameter).
1454///
1455/// \returns If the instantiation succeeds, the instantiated
1456/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001457TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001458 const MultiLevelTemplateArgumentList &Args,
1459 SourceLocation Loc,
1460 DeclarationName Entity) {
1461 assert(!ActiveTemplateInstantiations.empty() &&
1462 "Cannot perform an instantiation without some context on the "
1463 "instantiation stack");
1464
Douglas Gregor678d76c2011-07-01 01:22:09 +00001465 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001466 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001467 return T;
1468
1469 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1470 return Instantiator.TransformType(T);
1471}
1472
Douglas Gregor5499af42011-01-05 23:12:31 +00001473TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1474 const MultiLevelTemplateArgumentList &Args,
1475 SourceLocation Loc,
1476 DeclarationName Entity) {
1477 assert(!ActiveTemplateInstantiations.empty() &&
1478 "Cannot perform an instantiation without some context on the "
1479 "instantiation stack");
1480
1481 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001482 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001483
Douglas Gregor678d76c2011-07-01 01:22:09 +00001484 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001485 !TL.getType()->isVariablyModifiedType()) {
1486 // FIXME: Make a copy of the TypeLoc data here, so that we can
1487 // return a new TypeSourceInfo. Inefficient!
1488 TypeLocBuilder TLB;
1489 TLB.pushFullCopy(TL);
1490 return TLB.getTypeSourceInfo(Context, TL.getType());
1491 }
1492
1493 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1494 TypeLocBuilder TLB;
1495 TLB.reserve(TL.getFullDataSize());
1496 QualType Result = Instantiator.TransformType(TLB, TL);
1497 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001498 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001499
1500 return TLB.getTypeSourceInfo(Context, Result);
1501}
1502
John McCall609459e2009-10-21 00:58:09 +00001503/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001504QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001505 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001506 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001507 assert(!ActiveTemplateInstantiations.empty() &&
1508 "Cannot perform an instantiation without some context on the "
1509 "instantiation stack");
1510
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001511 // If T is not a dependent type or a variably-modified type, there
1512 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001513 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001514 return T;
1515
Douglas Gregord6ff3322009-08-04 16:50:30 +00001516 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1517 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001518}
Douglas Gregor463421d2009-03-03 04:44:36 +00001519
John McCallb29f78f2010-04-09 17:38:44 +00001520static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001521 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001522 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001523 return true;
1524
Abramo Bagnara6d810632010-12-14 22:11:44 +00001525 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001526 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001527 return false;
1528
David Blaikie6adc78e2013-02-18 22:06:02 +00001529 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001530 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001531 // This must be synthesized from a typedef.
1532 if (!P) continue;
1533
Nico Weberc0973372016-02-01 22:31:51 +00001534 // If there are any parameters, a new TypeSourceInfo that refers to the
1535 // instantiated parameters must be built.
1536 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001537 }
1538
1539 return false;
1540}
1541
1542/// A form of SubstType intended specifically for instantiating the
1543/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001544/// instantiation of default-argument expressions and to avoid
1545/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001546TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1547 const MultiLevelTemplateArgumentList &Args,
1548 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001549 DeclarationName Entity,
1550 CXXRecordDecl *ThisContext,
1551 unsigned ThisTypeQuals) {
John McCallb29f78f2010-04-09 17:38:44 +00001552 assert(!ActiveTemplateInstantiations.empty() &&
1553 "Cannot perform an instantiation without some context on the "
1554 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001555
John McCallb29f78f2010-04-09 17:38:44 +00001556 if (!NeedsInstantiationAsFunctionType(T))
1557 return T;
1558
1559 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1560
1561 TypeLocBuilder TLB;
1562
1563 TypeLoc TL = T->getTypeLoc();
1564 TLB.reserve(TL.getFullDataSize());
1565
Douglas Gregor3024f072012-04-16 07:05:22 +00001566 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001567
Richard Smith2e321552014-11-12 02:00:47 +00001568 if (FunctionProtoTypeLoc Proto =
1569 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1570 // Instantiate the type, other than its exception specification. The
1571 // exception specification is instantiated in InitFunctionInstantiation
1572 // once we've built the FunctionDecl.
1573 // FIXME: Set the exception specification to EST_Uninstantiated here,
1574 // instead of rebuilding the function type again later.
1575 Result = Instantiator.TransformFunctionProtoType(
1576 TLB, Proto, ThisContext, ThisTypeQuals,
1577 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1578 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001579 } else {
1580 Result = Instantiator.TransformType(TLB, TL);
1581 }
John McCallb29f78f2010-04-09 17:38:44 +00001582 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001583 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001584
1585 return TLB.getTypeSourceInfo(Context, Result);
1586}
1587
Richard Smith2e321552014-11-12 02:00:47 +00001588void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1589 const MultiLevelTemplateArgumentList &Args) {
1590 FunctionProtoType::ExceptionSpecInfo ESI =
1591 Proto->getExtProtoInfo().ExceptionSpec;
1592 assert(ESI.Type != EST_Uninstantiated);
1593
1594 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1595 New->getDeclName());
1596
1597 SmallVector<QualType, 4> ExceptionStorage;
1598 bool Changed = false;
1599 if (Instantiator.TransformExceptionSpec(
1600 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1601 ExceptionStorage, Changed))
1602 // On error, recover by dropping the exception specification.
1603 ESI.Type = EST_None;
1604
1605 UpdateExceptionSpec(New, ESI);
1606}
1607
Douglas Gregor940bca72010-04-12 07:48:19 +00001608ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001609 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001610 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001611 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001612 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001613 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001614 TypeSourceInfo *NewDI = nullptr;
1615
Douglas Gregor5499af42011-01-05 23:12:31 +00001616 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001617 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1618
Douglas Gregor5499af42011-01-05 23:12:31 +00001619 // We have a function parameter pack. Substitute into the pattern of the
1620 // expansion.
1621 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1622 OldParm->getLocation(), OldParm->getDeclName());
1623 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001624 return nullptr;
1625
Douglas Gregor5499af42011-01-05 23:12:31 +00001626 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1627 // We still have unexpanded parameter packs, which means that
1628 // our function parameter is still a function parameter pack.
1629 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001630 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001631 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001632 } else if (ExpectParameterPack) {
1633 // We expected to get a parameter pack but didn't (because the type
1634 // itself is not a pack expansion type), so complain. This can occur when
1635 // the substitution goes through an alias template that "loses" the
1636 // pack expansion.
1637 Diag(OldParm->getLocation(),
1638 diag::err_function_parameter_pack_without_parameter_packs)
1639 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001640 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001641 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001642 } else {
1643 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1644 OldParm->getDeclName());
1645 }
1646
Douglas Gregor940bca72010-04-12 07:48:19 +00001647 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001648 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001649
1650 if (NewDI->getType()->isVoidType()) {
1651 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001652 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001653 }
1654
1655 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001656 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001657 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001658 OldParm->getIdentifier(),
1659 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001660 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001661 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001662 return nullptr;
1663
Douglas Gregor940bca72010-04-12 07:48:19 +00001664 // Mark the (new) default argument as uninstantiated (if any).
1665 if (OldParm->hasUninstantiatedDefaultArg()) {
1666 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1667 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001668 } else if (OldParm->hasUnparsedDefaultArg()) {
1669 NewParm->setUnparsedDefaultArg();
1670 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001671 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1672 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001673 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1674 // Instantiate default arguments for methods of local classes (DR1484)
1675 // and non-defining declarations.
1676 Sema::ContextRAII SavedContext(*this, OwningFunc);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001677 LocalInstantiationScope Local(*this);
1678 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001679 if (NewArg.isUsable()) {
1680 // It would be nice if we still had this.
1681 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1682 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1683 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001684 } else {
1685 // FIXME: if we non-lazily instantiated non-dependent default args for
1686 // non-dependent parameter types we could remove a bunch of duplicate
1687 // conversion warnings for such arguments.
1688 NewParm->setUninstantiatedDefaultArg(Arg);
1689 }
1690 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001691
1692 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001693
Douglas Gregorf3010112011-01-07 16:43:16 +00001694 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001695 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001696 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1697 } else {
1698 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001699 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001700 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001701
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001702 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1703 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001704 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001705
1706 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1707 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001708
1709 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1710
Douglas Gregor940bca72010-04-12 07:48:19 +00001711 return NewParm;
1712}
1713
Douglas Gregordd472162011-01-07 00:20:55 +00001714/// \brief Substitute the given template arguments into the given set of
1715/// parameters, producing the set of parameter types that would be generated
1716/// from such a substitution.
1717bool Sema::SubstParmTypes(SourceLocation Loc,
1718 ParmVarDecl **Params, unsigned NumParams,
John McCallc8e321d2016-03-01 02:09:25 +00001719 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
Douglas Gregordd472162011-01-07 00:20:55 +00001720 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001721 SmallVectorImpl<QualType> &ParamTypes,
John McCallc8e321d2016-03-01 02:09:25 +00001722 SmallVectorImpl<ParmVarDecl *> *OutParams,
1723 ExtParameterInfoBuilder &ParamInfos) {
Douglas Gregordd472162011-01-07 00:20:55 +00001724 assert(!ActiveTemplateInstantiations.empty() &&
1725 "Cannot perform an instantiation without some context on the "
1726 "instantiation stack");
1727
1728 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1729 DeclarationName());
Craig Topperc3ec1492014-05-26 06:22:03 +00001730 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams,
John McCallc8e321d2016-03-01 02:09:25 +00001731 nullptr, ExtParamInfos,
1732 ParamTypes, OutParams,
1733 ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001734}
1735
John McCall76d824f2009-08-25 22:02:44 +00001736/// \brief Perform substitution on the base class specifiers of the
1737/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001738///
1739/// Produces a diagnostic and returns true on error, returns false and
1740/// attaches the instantiated base classes to the class template
1741/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001742bool
John McCall76d824f2009-08-25 22:02:44 +00001743Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1744 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001745 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001746 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001747 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001748 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001749 if (!Base.getType()->isDependentType()) {
1750 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001751 if (RD->isInvalidDecl())
1752 Instantiation->setInvalidDecl();
1753 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001754 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001755 continue;
1756 }
1757
Douglas Gregor752a5952011-01-03 22:36:02 +00001758 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001759 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001760 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001761 // This is a pack expansion. See whether we should expand it now, or
1762 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001763 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001764 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001765 Unexpanded);
1766 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001767 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001768 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001769 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1770 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001771 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001772 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001773 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001774 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001775 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001776 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001777 }
1778
1779 // If we should expand this pack expansion now, do so.
1780 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001781 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001782 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1783
Aaron Ballman574705e2014-03-13 15:41:46 +00001784 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001785 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001786 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001787 DeclarationName());
1788 if (!BaseTypeLoc) {
1789 Invalid = true;
1790 continue;
1791 }
1792
1793 if (CXXBaseSpecifier *InstantiatedBase
1794 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001795 Base.getSourceRange(),
1796 Base.isVirtual(),
1797 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001798 BaseTypeLoc,
1799 SourceLocation()))
1800 InstantiatedBases.push_back(InstantiatedBase);
1801 else
1802 Invalid = true;
1803 }
1804
1805 continue;
1806 }
1807
1808 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001809 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001810 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
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());
1815 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001816 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001817 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001818 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001819 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001820 }
1821
Nick Lewycky19b9f952010-07-26 16:56:01 +00001822 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001823 Invalid = true;
1824 continue;
1825 }
1826
1827 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001828 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001829 Base.getSourceRange(),
1830 Base.isVirtual(),
1831 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001832 BaseTypeLoc,
1833 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001834 InstantiatedBases.push_back(InstantiatedBase);
1835 else
1836 Invalid = true;
1837 }
1838
Craig Topperaa700cb2015-12-27 21:55:19 +00001839 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001840 Invalid = true;
1841
1842 return Invalid;
1843}
1844
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001845// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001846namespace clang {
1847 namespace sema {
1848 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1849 const MultiLevelTemplateArgumentList &TemplateArgs);
1850 }
1851}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001852
Richard Smith4b38ded2012-03-14 23:13:10 +00001853/// Determine whether we would be unable to instantiate this template (because
1854/// it either has no definition, or is in the process of being instantiated).
1855static bool DiagnoseUninstantiableTemplate(Sema &S,
1856 SourceLocation PointOfInstantiation,
1857 TagDecl *Instantiation,
1858 bool InstantiatedFromMember,
1859 TagDecl *Pattern,
1860 TagDecl *PatternDef,
1861 TemplateSpecializationKind TSK,
1862 bool Complain = true) {
Richard Smith6739a102016-05-05 00:56:12 +00001863 if (PatternDef && !PatternDef->isBeingDefined()) {
1864 NamedDecl *SuggestedDef = nullptr;
1865 if (!S.hasVisibleDefinition(PatternDef, &SuggestedDef,
1866 /*OnlyNeedComplete*/false)) {
1867 // If we're allowed to diagnose this and recover, do so.
1868 bool Recover = Complain && !S.isSFINAEContext();
1869 if (Complain)
1870 S.diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
1871 Sema::MissingImportKind::Definition, Recover);
1872 return !Recover;
1873 }
Richard Smith4b38ded2012-03-14 23:13:10 +00001874 return false;
Richard Smith6739a102016-05-05 00:56:12 +00001875 }
Richard Smith4b38ded2012-03-14 23:13:10 +00001876
1877 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1878 // Say nothing
1879 } else if (PatternDef) {
1880 assert(PatternDef->isBeingDefined());
1881 S.Diag(PointOfInstantiation,
1882 diag::err_template_instantiate_within_definition)
1883 << (TSK != TSK_ImplicitInstantiation)
1884 << S.Context.getTypeDeclType(Instantiation);
1885 // Not much point in noting the template declaration here, since
1886 // we're lexically inside it.
1887 Instantiation->setInvalidDecl();
1888 } else if (InstantiatedFromMember) {
1889 S.Diag(PointOfInstantiation,
1890 diag::err_implicit_instantiate_member_undefined)
1891 << S.Context.getTypeDeclType(Instantiation);
Alp Toker2afa8782014-05-28 12:20:14 +00001892 S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
Richard Smith4b38ded2012-03-14 23:13:10 +00001893 } else {
1894 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1895 << (TSK != TSK_ImplicitInstantiation)
1896 << S.Context.getTypeDeclType(Instantiation);
1897 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1898 }
1899
1900 // In general, Instantiation isn't marked invalid to get more than one
1901 // error for multiple undefined instantiations. But the code that does
1902 // explicit declaration -> explicit definition conversion can't handle
1903 // invalid declarations, so mark as invalid in that case.
1904 if (TSK == TSK_ExplicitInstantiationDeclaration)
1905 Instantiation->setInvalidDecl();
1906 return true;
1907}
1908
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001909/// \brief Instantiate the definition of a class from a given pattern.
1910///
1911/// \param PointOfInstantiation The point of instantiation within the
1912/// source code.
1913///
1914/// \param Instantiation is the declaration whose definition is being
1915/// instantiated. This will be either a class template specialization
1916/// or a member class of a class template specialization.
1917///
1918/// \param Pattern is the pattern from which the instantiation
1919/// occurs. This will be either the declaration of a class template or
1920/// the declaration of a member class of a class template.
1921///
1922/// \param TemplateArgs The template arguments to be substituted into
1923/// the pattern.
1924///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001925/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001926///
1927/// \param Complain whether to complain if the class cannot be instantiated due
1928/// to the lack of a definition.
1929///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001930/// \returns true if an error occurred, false otherwise.
1931bool
1932Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1933 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001934 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001935 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001936 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001937 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001938 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smith4b38ded2012-03-14 23:13:10 +00001939 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1940 Instantiation->getInstantiatedFromMemberClass(),
1941 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001942 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001943 Pattern = PatternDef;
1944
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001945 // \brief Record the point of instantiation.
1946 if (MemberSpecializationInfo *MSInfo
1947 = Instantiation->getMemberSpecializationInfo()) {
1948 MSInfo->setTemplateSpecializationKind(TSK);
1949 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001950 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001951 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001952 Spec->setTemplateSpecializationKind(TSK);
1953 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001954 }
Richard Smitha1087602014-03-10 00:04:29 +00001955
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001956 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001957 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001958 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00001959 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
1960 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001961
1962 // Enter the scope of this instantiation. We don't use
1963 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001964 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001965 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001966 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001967
Douglas Gregor51121572010-03-24 01:33:17 +00001968 // If this is an instantiation of a local class, merge this local
1969 // instantiation scope with the enclosing scope. Otherwise, every
1970 // instantiation of a class has its own local instantiation scope.
1971 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001972 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001973
Reid Kleckner5b640342016-02-26 19:51:02 +00001974 // All dllexported classes created during instantiation should be fully
1975 // emitted after instantiation completes. We may not be ready to emit any
1976 // delayed classes already on the stack, so save them away and put them back
1977 // later.
1978 decltype(DelayedDllExportClasses) ExportedClasses;
1979 std::swap(ExportedClasses, DelayedDllExportClasses);
1980
John McCall6602bb12010-08-01 02:01:53 +00001981 // Pull attributes from the pattern onto the instantiation.
1982 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1983
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001984 // Start the definition of this instantiation.
1985 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00001986
1987 // The instantiation is visible here, even if it was first declared in an
1988 // unimported module.
1989 Instantiation->setHidden(false);
1990
1991 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00001992 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001993
John McCall76d824f2009-08-25 22:02:44 +00001994 // Do substitution on the base class specifiers.
1995 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001996 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001997
Douglas Gregor869853e2010-11-10 19:44:59 +00001998 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001999 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002000 // Delay instantiation of late parsed attributes.
2001 LateInstantiatedAttrVec LateAttrs;
2002 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2003
Aaron Ballman629afae2014-03-07 19:56:05 +00002004 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002005 // Don't instantiate members not belonging in this semantic context.
2006 // e.g. for:
2007 // @code
2008 // template <int i> class A {
2009 // class B *g;
2010 // };
2011 // @endcode
2012 // 'class B' has the template as lexical context but semantically it is
2013 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002014 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002015 continue;
2016
Aaron Ballman629afae2014-03-07 19:56:05 +00002017 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002018 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002019 continue;
2020 }
2021
Aaron Ballman629afae2014-03-07 19:56:05 +00002022 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002023 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002024 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002025 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002026 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2027 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2028 // specialization causes the implicit instantiation of the definitions
2029 // of unscoped member enumerations.
2030 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002031 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2032 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002033 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2034 assert(MSInfo && "no spec info for member enum specialization");
2035 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2036 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2037 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002038 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2039 if (SA->isFailed()) {
2040 // A static_assert failed. Bail out; instantiating this
2041 // class is probably not meaningful.
2042 Instantiation->setInvalidDecl();
2043 break;
2044 }
Richard Smith7d137e32012-03-23 03:33:32 +00002045 }
2046
2047 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002048 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002049 } else {
2050 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002051 // instantiations was a semantic disaster, and we'll want to mark the
2052 // declaration invalid.
2053 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002054 }
2055 }
2056
2057 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002058 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2059 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002060 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002061
Reid Kleckner93f661a2015-03-17 21:51:43 +00002062 // Default arguments are parsed, if not instantiated. We can go instantiate
2063 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002064 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002065
Reid Kleckner5b640342016-02-26 19:51:02 +00002066 // Put back the delayed exported classes that we moved out of the way.
2067 std::swap(ExportedClasses, DelayedDllExportClasses);
2068
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002069 // Instantiate late parsed attributes, and attach them to their decls.
2070 // See Sema::InstantiateAttrs
2071 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2072 E = LateAttrs.end(); I != E; ++I) {
2073 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2074 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002075
2076 // Allow 'this' within late-parsed attributes.
2077 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2078 CXXRecordDecl *ThisContext =
2079 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2080 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2081 ND && ND->isCXXInstanceMember());
2082
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002083 Attr *NewAttr =
2084 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2085 I->NewDecl->addAttr(NewAttr);
2086 LocalInstantiationScope::deleteScopes(I->Scope,
2087 Instantiator.getStartingScope());
2088 }
2089 Instantiator.disableLateAttributeInstantiation();
2090 LateAttrs.clear();
2091
Richard Smithd3b5c9082012-07-27 04:22:15 +00002092 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002093
Richard Smitha1087602014-03-10 00:04:29 +00002094 // FIXME: We should do something similar for explicit instantiations so they
2095 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002096 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002097 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002098 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002099 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002100 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002101
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002102 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002103 // Perform any dependent diagnostics from the pattern.
2104 PerformDependentDiagnostics(Pattern, TemplateArgs);
2105
Douglas Gregor869853e2010-11-10 19:44:59 +00002106 // Instantiate any out-of-line class template partial
2107 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002108 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002109 P = Instantiator.delayed_partial_spec_begin(),
2110 PEnd = Instantiator.delayed_partial_spec_end();
2111 P != PEnd; ++P) {
2112 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002113 P->first, P->second)) {
2114 Instantiation->setInvalidDecl();
2115 break;
2116 }
2117 }
2118
2119 // Instantiate any out-of-line variable template partial
2120 // specializations now.
2121 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2122 P = Instantiator.delayed_var_partial_spec_begin(),
2123 PEnd = Instantiator.delayed_var_partial_spec_end();
2124 P != PEnd; ++P) {
2125 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2126 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002127 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002128 break;
2129 }
2130 }
2131 }
2132
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002133 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002134 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002135
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002136 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002137 Consumer.HandleTagDeclDefinition(Instantiation);
2138
Douglas Gregor88d292c2010-05-13 16:44:06 +00002139 // Always emit the vtable for an explicit instantiation definition
2140 // of a polymorphic class template specialization.
2141 if (TSK == TSK_ExplicitInstantiationDefinition)
2142 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2143 }
2144
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002145 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002146}
2147
Richard Smith4b38ded2012-03-14 23:13:10 +00002148/// \brief Instantiate the definition of an enum from a given pattern.
2149///
2150/// \param PointOfInstantiation The point of instantiation within the
2151/// source code.
2152/// \param Instantiation is the declaration whose definition is being
2153/// instantiated. This will be a member enumeration of a class
2154/// temploid specialization, or a local enumeration within a
2155/// function temploid specialization.
2156/// \param Pattern The templated declaration from which the instantiation
2157/// occurs.
2158/// \param TemplateArgs The template arguments to be substituted into
2159/// the pattern.
2160/// \param TSK The kind of implicit or explicit instantiation to perform.
2161///
2162/// \return \c true if an error occurred, \c false otherwise.
2163bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2164 EnumDecl *Instantiation, EnumDecl *Pattern,
2165 const MultiLevelTemplateArgumentList &TemplateArgs,
2166 TemplateSpecializationKind TSK) {
2167 EnumDecl *PatternDef = Pattern->getDefinition();
2168 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2169 Instantiation->getInstantiatedFromMemberEnum(),
2170 Pattern, PatternDef, TSK,/*Complain*/true))
2171 return true;
2172 Pattern = PatternDef;
2173
2174 // Record the point of instantiation.
2175 if (MemberSpecializationInfo *MSInfo
2176 = Instantiation->getMemberSpecializationInfo()) {
2177 MSInfo->setTemplateSpecializationKind(TSK);
2178 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2179 }
2180
2181 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002182 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002183 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00002184 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2185 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002186
Richard Smitha1087602014-03-10 00:04:29 +00002187 // The instantiation is visible here, even if it was first declared in an
2188 // unimported module.
2189 Instantiation->setHidden(false);
2190
Richard Smith4b38ded2012-03-14 23:13:10 +00002191 // Enter the scope of this instantiation. We don't use
2192 // PushDeclContext because we don't have a scope.
2193 ContextRAII SavedContext(*this, Instantiation);
2194 EnterExpressionEvaluationContext EvalContext(*this,
2195 Sema::PotentiallyEvaluated);
2196
2197 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2198
2199 // Pull attributes from the pattern onto the instantiation.
2200 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2201
2202 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2203 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2204
2205 // Exit the scope of this instantiation.
2206 SavedContext.pop();
2207
2208 return Instantiation->isInvalidDecl();
2209}
2210
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002211
2212/// \brief Instantiate the definition of a field from the given pattern.
2213///
2214/// \param PointOfInstantiation The point of instantiation within the
2215/// source code.
2216/// \param Instantiation is the declaration whose definition is being
2217/// instantiated. This will be a class of a class temploid
2218/// specialization, or a local enumeration within a function temploid
2219/// specialization.
2220/// \param Pattern The templated declaration from which the instantiation
2221/// occurs.
2222/// \param TemplateArgs The template arguments to be substituted into
2223/// the pattern.
2224///
2225/// \return \c true if an error occurred, \c false otherwise.
2226bool Sema::InstantiateInClassInitializer(
2227 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2228 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2229 // If there is no initializer, we don't need to do anything.
2230 if (!Pattern->hasInClassInitializer())
2231 return false;
2232
2233 assert(Instantiation->getInClassInitStyle() ==
2234 Pattern->getInClassInitStyle() &&
2235 "pattern and instantiation disagree about init style");
2236
2237 // Error out if we haven't parsed the initializer of the pattern yet because
2238 // we are waiting for the closing brace of the outer class.
2239 Expr *OldInit = Pattern->getInClassInitializer();
2240 if (!OldInit) {
2241 RecordDecl *PatternRD = Pattern->getParent();
2242 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2243 if (OutermostClass == PatternRD) {
2244 Diag(Pattern->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
2245 << PatternRD << Pattern;
2246 } else {
2247 Diag(Pattern->getLocEnd(),
2248 diag::err_in_class_initializer_not_yet_parsed_outer_class)
2249 << PatternRD << OutermostClass << Pattern;
2250 }
2251 Instantiation->setInvalidDecl();
2252 return true;
2253 }
2254
2255 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2256 if (Inst.isInvalid())
2257 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00002258 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2259 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002260
2261 // Enter the scope of this instantiation. We don't use PushDeclContext because
2262 // we don't have a scope.
2263 ContextRAII SavedContext(*this, Instantiation->getParent());
2264 EnterExpressionEvaluationContext EvalContext(*this,
2265 Sema::PotentiallyEvaluated);
2266
Serge Pavlov907233f2015-04-28 17:58:47 +00002267 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002268
2269 // Instantiate the initializer.
2270 ActOnStartCXXInClassMemberInitializer();
2271 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2272
2273 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2274 /*CXXDirectInit=*/false);
2275 Expr *Init = NewInit.get();
2276 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2277 ActOnFinishCXXInClassMemberInitializer(
2278 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2279
2280 // Exit the scope of this instantiation.
2281 SavedContext.pop();
2282
2283 // Return true if the in-class initializer is still missing.
2284 return !Instantiation->getInClassInitializer();
2285}
2286
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002287namespace {
2288 /// \brief A partial specialization whose template arguments have matched
2289 /// a given template-id.
2290 struct PartialSpecMatchResult {
2291 ClassTemplatePartialSpecializationDecl *Partial;
2292 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002293 };
2294}
2295
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002296bool Sema::InstantiateClassTemplateSpecialization(
2297 SourceLocation PointOfInstantiation,
2298 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2299 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002300 // Perform the actual instantiation on the canonical declaration.
2301 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002302 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor00a511f2009-09-15 16:51:42 +00002303 if (ClassTemplateSpec->isInvalidDecl())
2304 return true;
2305
Douglas Gregor463421d2009-03-03 04:44:36 +00002306 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002307 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002308
Douglas Gregor170bc422009-06-12 22:31:52 +00002309 // C++ [temp.class.spec.match]p1:
2310 // When a class template is used in a context that requires an
2311 // instantiation of the class, it is necessary to determine
2312 // whether the instantiation is to be generated using the primary
2313 // template or one of the partial specializations. This is done by
2314 // matching the template arguments of the class template
2315 // specialization with the template argument lists of the partial
2316 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002317 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002318 SmallVector<MatchResult, 4> Matched;
2319 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002320 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002321 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002322 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2323 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002324 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002325 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002326 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002327 ClassTemplateSpec->getTemplateArgs(),
2328 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002329 // Store the failed-deduction information for use in diagnostics, later.
2330 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002331 FailedCandidates.addCandidate().set(
2332 DeclAccessPair::make(Template, AS_public), Partial,
2333 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002334 (void)Result;
2335 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002336 Matched.push_back(PartialSpecMatchResult());
2337 Matched.back().Partial = Partial;
2338 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002339 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002340 }
2341
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002342 // If we're dealing with a member template where the template parameters
2343 // have been instantiated, this provides the original template parameters
2344 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002345
Douglas Gregor21610382009-10-29 00:04:11 +00002346 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002347 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002348 if (Matched.size() == 1) {
2349 // -- If exactly one matching specialization is found, the
2350 // instantiation is generated from that specialization.
2351 // We don't need to do anything for this.
2352 } else {
2353 // -- If more than one matching specialization is found, the
2354 // partial order rules (14.5.4.2) are used to determine
2355 // whether one of the specializations is more specialized
2356 // than the others. If none of the specializations is more
2357 // specialized than all of the other matching
2358 // specializations, then the use of the class template is
2359 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002360 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2361 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002362 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002363 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002364 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002365 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002366 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002367 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002368
Douglas Gregor21610382009-10-29 00:04:11 +00002369 // Determine if the best partial specialization is more specialized than
2370 // the others.
2371 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002372 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2373 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002374 P != PEnd; ++P) {
2375 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002376 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002377 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002378 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002379 Ambiguous = true;
2380 break;
2381 }
2382 }
2383
2384 if (Ambiguous) {
2385 // Partial ordering did not produce a clear winner. Complain.
2386 ClassTemplateSpec->setInvalidDecl();
2387 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2388 << ClassTemplateSpec;
2389
2390 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002391 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2392 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002393 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002394 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2395 << getTemplateArgumentBindingsText(
2396 P->Partial->getTemplateParameters(),
2397 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002398
Douglas Gregor21610382009-10-29 00:04:11 +00002399 return true;
2400 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002401 }
2402
2403 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002404 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002405 while (OrigPartialSpec->getInstantiatedFromMember()) {
2406 // If we've found an explicit specialization of this class template,
2407 // stop here and use that as the pattern.
2408 if (OrigPartialSpec->isMemberSpecialization())
2409 break;
2410
2411 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2412 }
2413
2414 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002415 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002416 } else {
2417 // -- If no matches are found, the instantiation is generated
2418 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002419 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002420 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2421 // If we've found an explicit specialization of this class template,
2422 // stop here and use that as the pattern.
2423 if (OrigTemplate->isMemberSpecialization())
2424 break;
2425
Douglas Gregor01afeef2009-08-28 20:31:08 +00002426 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002427 }
2428
Douglas Gregor01afeef2009-08-28 20:31:08 +00002429 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002430 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002431
Douglas Gregoref6ab412009-10-27 06:26:26 +00002432 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2433 Pattern,
2434 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002435 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002436 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002437
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002438 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002439}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002440
John McCall76d824f2009-08-25 22:02:44 +00002441/// \brief Instantiates the definitions of all of the member
2442/// of the given class, which is an instantiation of a class template
2443/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002444void
2445Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002446 CXXRecordDecl *Instantiation,
2447 const MultiLevelTemplateArgumentList &TemplateArgs,
2448 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002449 // FIXME: We need to notify the ASTMutationListener that we did all of these
2450 // things, in case we have an explicit instantiation definition in a PCM, a
2451 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002452 assert(
2453 (TSK == TSK_ExplicitInstantiationDefinition ||
2454 TSK == TSK_ExplicitInstantiationDeclaration ||
2455 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2456 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002457 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002458 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002459 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002460 if (FunctionDecl *Pattern
2461 = Function->getInstantiatedFromMemberFunction()) {
2462 MemberSpecializationInfo *MSInfo
2463 = Function->getMemberSpecializationInfo();
2464 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002465 if (MSInfo->getTemplateSpecializationKind()
2466 == TSK_ExplicitSpecialization)
2467 continue;
2468
Douglas Gregor1d957a32009-10-27 18:42:08 +00002469 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2470 Function,
2471 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002472 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002473 SuppressNew) ||
2474 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002475 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002476
2477 // C++11 [temp.explicit]p8:
2478 // An explicit instantiation definition that names a class template
2479 // specialization explicitly instantiates the class template
2480 // specialization and is only an explicit instantiation definition
2481 // of members whose definition is visible at the point of
2482 // instantiation.
2483 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002484 continue;
2485
Richard Smitheb36ddf2014-04-24 22:45:46 +00002486 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2487
2488 if (Function->isDefined()) {
2489 // Let the ASTConsumer know that this function has been explicitly
2490 // instantiated now, and its linkage might have changed.
2491 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2492 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002493 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002494 } else if (TSK == TSK_ImplicitInstantiation) {
2495 PendingLocalImplicitInstantiations.push_back(
2496 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002497 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002498 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002499 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002500 if (isa<VarTemplateSpecializationDecl>(Var))
2501 continue;
2502
Douglas Gregor86d142a2009-10-08 07:24:58 +00002503 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002504 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2505 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002506 if (MSInfo->getTemplateSpecializationKind()
2507 == TSK_ExplicitSpecialization)
2508 continue;
2509
Douglas Gregor1d957a32009-10-27 18:42:08 +00002510 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2511 Var,
2512 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002513 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002514 SuppressNew) ||
2515 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002516 continue;
2517
Douglas Gregor1d957a32009-10-27 18:42:08 +00002518 if (TSK == TSK_ExplicitInstantiationDefinition) {
2519 // C++0x [temp.explicit]p8:
2520 // An explicit instantiation definition that names a class template
2521 // specialization explicitly instantiates the class template
2522 // specialization and is only an explicit instantiation definition
2523 // of members whose definition is visible at the point of
2524 // instantiation.
2525 if (!Var->getInstantiatedFromStaticDataMember()
2526 ->getOutOfLineDefinition())
2527 continue;
2528
2529 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002530 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002531 } else {
2532 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2533 }
2534 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002535 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002536 // Always skip the injected-class-name, along with any
2537 // redeclarations of nested classes, since both would cause us
2538 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002539 // Skip closure types; they'll get instantiated when we instantiate
2540 // the corresponding lambda-expression.
2541 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2542 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002543 continue;
2544
Douglas Gregor1d957a32009-10-27 18:42:08 +00002545 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2546 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002547
2548 if (MSInfo->getTemplateSpecializationKind()
2549 == TSK_ExplicitSpecialization)
2550 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002551
Hans Wennborga86a83b2016-05-26 19:42:56 +00002552 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2553 TSK == TSK_ExplicitInstantiationDeclaration) {
2554 // In MSVC mode, explicit instantiation decl of the outer class doesn't
2555 // affect the inner class.
2556 continue;
2557 }
2558
Douglas Gregor1d957a32009-10-27 18:42:08 +00002559 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2560 Record,
2561 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002562 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002563 SuppressNew) ||
2564 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002565 continue;
2566
Douglas Gregor1d957a32009-10-27 18:42:08 +00002567 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2568 assert(Pattern && "Missing instantiated-from-template information");
2569
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002570 if (!Record->getDefinition()) {
2571 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002572 // C++0x [temp.explicit]p8:
2573 // An explicit instantiation definition that names a class template
2574 // specialization explicitly instantiates the class template
2575 // specialization and is only an explicit instantiation definition
2576 // of members whose definition is visible at the point of
2577 // instantiation.
2578 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2579 MSInfo->setTemplateSpecializationKind(TSK);
2580 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2581 }
2582
2583 continue;
2584 }
2585
2586 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002587 TemplateArgs,
2588 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002589 } else {
2590 if (TSK == TSK_ExplicitInstantiationDefinition &&
2591 Record->getTemplateSpecializationKind() ==
2592 TSK_ExplicitInstantiationDeclaration) {
2593 Record->setTemplateSpecializationKind(TSK);
2594 MarkVTableUsed(PointOfInstantiation, Record, true);
2595 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002596 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002597
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002598 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002599 if (Pattern)
2600 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2601 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002602 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002603 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2604 assert(MSInfo && "No member specialization information?");
2605
2606 if (MSInfo->getTemplateSpecializationKind()
2607 == TSK_ExplicitSpecialization)
2608 continue;
2609
2610 if (CheckSpecializationInstantiationRedecl(
2611 PointOfInstantiation, TSK, Enum,
2612 MSInfo->getTemplateSpecializationKind(),
2613 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2614 SuppressNew)
2615 continue;
2616
2617 if (Enum->getDefinition())
2618 continue;
2619
Richard Smith6739a102016-05-05 00:56:12 +00002620 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002621 assert(Pattern && "Missing instantiated-from-template information");
2622
2623 if (TSK == TSK_ExplicitInstantiationDefinition) {
2624 if (!Pattern->getDefinition())
2625 continue;
2626
2627 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2628 } else {
2629 MSInfo->setTemplateSpecializationKind(TSK);
2630 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2631 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002632 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2633 // No need to instantiate in-class initializers during explicit
2634 // instantiation.
2635 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2636 CXXRecordDecl *ClassPattern =
2637 Instantiation->getTemplateInstantiationPattern();
2638 DeclContext::lookup_result Lookup =
2639 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002640 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002641 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2642 TemplateArgs);
2643 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002644 }
2645 }
2646}
2647
2648/// \brief Instantiate the definitions of all of the members of the
2649/// given class template specialization, which was named as part of an
2650/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002651void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002652Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002653 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002654 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2655 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002656 // C++0x [temp.explicit]p7:
2657 // An explicit instantiation that names a class template
2658 // specialization is an explicit instantion of the same kind
2659 // (declaration or definition) of each of its members (not
2660 // including members inherited from base classes) that has not
2661 // been previously explicitly specialized in the translation unit
2662 // containing the explicit instantiation, except as described
2663 // below.
2664 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002665 getTemplateInstantiationArgs(ClassTemplateSpec),
2666 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002667}
2668
John McCalldadc5752010-08-24 06:29:42 +00002669StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002670Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002671 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002672 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002673
2674 TemplateInstantiator Instantiator(*this, TemplateArgs,
2675 SourceLocation(),
2676 DeclarationName());
2677 return Instantiator.TransformStmt(S);
2678}
2679
John McCalldadc5752010-08-24 06:29:42 +00002680ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002681Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002682 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002683 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002684
Douglas Gregora16548e2009-08-11 05:31:07 +00002685 TemplateInstantiator Instantiator(*this, TemplateArgs,
2686 SourceLocation(),
2687 DeclarationName());
2688 return Instantiator.TransformExpr(E);
2689}
2690
Richard Smithd59b8322012-12-19 01:39:02 +00002691ExprResult Sema::SubstInitializer(Expr *Init,
2692 const MultiLevelTemplateArgumentList &TemplateArgs,
2693 bool CXXDirectInit) {
2694 TemplateInstantiator Instantiator(*this, TemplateArgs,
2695 SourceLocation(),
2696 DeclarationName());
2697 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2698}
2699
Craig Topper99d23532015-12-24 23:58:29 +00002700bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002701 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002702 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002703 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002704 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002705
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002706 TemplateInstantiator Instantiator(*this, TemplateArgs,
2707 SourceLocation(),
2708 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002709 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2710 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002711}
2712
Douglas Gregor14454802011-02-25 02:25:35 +00002713NestedNameSpecifierLoc
2714Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2715 const MultiLevelTemplateArgumentList &TemplateArgs) {
2716 if (!NNS)
2717 return NestedNameSpecifierLoc();
2718
2719 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2720 DeclarationName());
2721 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2722}
2723
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002724/// \brief Do template substitution on declaration name info.
2725DeclarationNameInfo
2726Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2727 const MultiLevelTemplateArgumentList &TemplateArgs) {
2728 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2729 NameInfo.getName());
2730 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2731}
2732
Douglas Gregoraa594892009-03-31 18:38:02 +00002733TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002734Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2735 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002736 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002737 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2738 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002739 CXXScopeSpec SS;
2740 SS.Adopt(QualifierLoc);
2741 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002742}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002743
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002744bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2745 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002746 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002747 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2748 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002749
2750 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002751}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002752
Richard Smith70b13042015-01-09 01:19:56 +00002753static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002754 // When storing ParmVarDecls in the local instantiation scope, we always
2755 // want to use the ParmVarDecl from the canonical function declaration,
2756 // since the map is then valid for any redeclaration or definition of that
2757 // function.
2758 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2759 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2760 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002761 // This parameter might be from a freestanding function type within the
2762 // function and isn't necessarily referring to one of FD's parameters.
2763 if (FD->getParamDecl(i) == PV)
2764 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002765 }
2766 }
2767 return D;
2768}
2769
2770
Douglas Gregorf3010112011-01-07 16:43:16 +00002771llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2772LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002773 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002774 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002775 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002776
Douglas Gregor14cf7522010-04-30 18:55:50 +00002777 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002778 const Decl *CheckD = D;
2779 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002780 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002781 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002782 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002783
2784 // If this is a tag declaration, it's possible that we need to look for
2785 // a previous declaration.
2786 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002787 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002788 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002789 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002790 } while (CheckD);
2791
Douglas Gregor14cf7522010-04-30 18:55:50 +00002792 // If we aren't combined with our outer scope, we're done.
2793 if (!Current->CombineWithOuterScope)
2794 break;
2795 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002796
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002797 // If we're performing a partial substitution during template argument
2798 // deduction, we may not have values for template parameters yet.
2799 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2800 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002801 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002802
Serge Pavlove7ad8312015-05-15 10:10:28 +00002803 // Local types referenced prior to definition may require instantiation.
2804 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2805 if (RD->isLocalClass())
2806 return nullptr;
2807
2808 // Enumeration types referenced prior to definition may appear as a result of
2809 // error recovery.
2810 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002811 return nullptr;
2812
Chris Lattnercab02a62011-02-17 20:34:02 +00002813 // If we didn't find the decl, then we either have a sema bug, or we have a
2814 // forward reference to a label declaration. Return null to indicate that
2815 // we have an uninstantiated label.
2816 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002817 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002818}
2819
John McCall19c1bfd2010-08-25 05:32:35 +00002820void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002821 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002822 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002823 if (Stored.isNull()) {
2824#ifndef NDEBUG
2825 // It should not be present in any surrounding scope either.
2826 LocalInstantiationScope *Current = this;
2827 while (Current->CombineWithOuterScope && Current->Outer) {
2828 Current = Current->Outer;
2829 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2830 "Instantiated local in inner and outer scopes");
2831 }
2832#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002833 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002834 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002835 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002836 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002837 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002838 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002839}
Douglas Gregorf3010112011-01-07 16:43:16 +00002840
James Y Knight48fefa32015-09-30 14:04:23 +00002841void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2842 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002843 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002844 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2845 Pack->push_back(Inst);
2846}
2847
2848void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002849#ifndef NDEBUG
2850 // This should be the first time we've been told about this decl.
2851 for (LocalInstantiationScope *Current = this;
2852 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2853 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2854 "Creating local pack after instantiation of local");
2855#endif
2856
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002857 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002858 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002859 DeclArgumentPack *Pack = new DeclArgumentPack;
2860 Stored = Pack;
2861 ArgumentPacks.push_back(Pack);
2862}
2863
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002864void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2865 const TemplateArgument *ExplicitArgs,
2866 unsigned NumExplicitArgs) {
2867 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2868 "Already have a partially-substituted pack");
2869 assert((!PartiallySubstitutedPack
2870 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2871 "Wrong number of arguments in partially-substituted pack");
2872 PartiallySubstitutedPack = Pack;
2873 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2874 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2875}
2876
2877NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2878 const TemplateArgument **ExplicitArgs,
2879 unsigned *NumExplicitArgs) const {
2880 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002881 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002882 if (NumExplicitArgs)
2883 *NumExplicitArgs = 0;
2884
2885 for (const LocalInstantiationScope *Current = this; Current;
2886 Current = Current->Outer) {
2887 if (Current->PartiallySubstitutedPack) {
2888 if (ExplicitArgs)
2889 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2890 if (NumExplicitArgs)
2891 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2892
2893 return Current->PartiallySubstitutedPack;
2894 }
2895
2896 if (!Current->CombineWithOuterScope)
2897 break;
2898 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002899
2900 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002901}