blob: 4f1879c2dedaee5275bdf965ed7b76b0d4adbea5 [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);
David Majnemer6fbeee32016-07-07 04:43:07 +0000450 TemplateSpecializationType::PrintTemplateArgumentList(
451 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000452 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000453 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000454 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000455 << Active->InstantiationRange;
456 break;
457 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000458
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000459 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000460 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000461 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000462 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000463 << FnTmpl
464 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
465 Active->TemplateArgs,
466 Active->NumTemplateArgs)
467 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000468 break;
469 }
Mike Stump11289f42009-09-09 15:08:12 +0000470
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000471 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000472 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
473 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000474 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000475 diag::note_partial_spec_deduct_instantiation_here)
476 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000477 << getTemplateArgumentBindingsText(
478 PartialSpec->getTemplateParameters(),
479 Active->TemplateArgs,
480 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000481 << Active->InstantiationRange;
482 } else {
483 FunctionTemplateDecl *FnTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000484 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000485 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000486 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000487 << FnTmpl
488 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
489 Active->TemplateArgs,
490 Active->NumTemplateArgs)
491 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000492 }
493 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000494
Anders Carlsson657bad42009-09-05 05:14:19 +0000495 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000496 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000497 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000498
Benjamin Kramer9170e912013-02-22 15:46:01 +0000499 SmallVector<char, 128> TemplateArgsStr;
500 llvm::raw_svector_ostream OS(TemplateArgsStr);
501 FD->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000502 TemplateSpecializationType::PrintTemplateArgumentList(
503 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000504 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000505 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000506 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000507 << Active->InstantiationRange;
508 break;
509 }
Mike Stump11289f42009-09-09 15:08:12 +0000510
Douglas Gregore62e6a02009-11-11 19:13:48 +0000511 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000512 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000513 std::string Name;
514 if (!Parm->getName().empty())
515 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000516
517 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000518 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
519 TemplateParams = Template->getTemplateParameters();
520 else
521 TemplateParams =
522 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
523 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000524 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000525 diag::note_prior_template_arg_substitution)
526 << isa<TemplateTemplateParmDecl>(Parm)
527 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000528 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000529 Active->TemplateArgs,
530 Active->NumTemplateArgs)
531 << Active->InstantiationRange;
532 break;
533 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000534
535 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000536 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000537 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
538 TemplateParams = Template->getTemplateParameters();
539 else
540 TemplateParams =
541 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
542 ->getTemplateParameters();
543
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000544 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000545 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000546 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000547 Active->TemplateArgs,
548 Active->NumTemplateArgs)
549 << Active->InstantiationRange;
550 break;
551 }
Richard Smithf623c962012-04-17 00:58:00 +0000552
553 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
554 Diags.Report(Active->PointOfInstantiation,
555 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000556 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000557 << Active->InstantiationRange;
558 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000559 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000560 }
561}
562
David Blaikie05785d12013-02-20 22:23:23 +0000563Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000564 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000565 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000566
Craig Topper2341c0d2013-07-04 03:08:24 +0000567 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor33834512009-06-14 07:33:30 +0000568 Active = ActiveTemplateInstantiations.rbegin(),
569 ActiveEnd = ActiveTemplateInstantiations.rend();
570 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000571 ++Active)
572 {
Douglas Gregor33834512009-06-14 07:33:30 +0000573 switch(Active->Kind) {
Douglas Gregoredb76852011-01-27 22:31:44 +0000574 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000575 // An instantiation of an alias template may or may not be a SFINAE
576 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000577 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000578 break;
579 // Fall through.
580 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000581 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000582 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000583 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000584
Douglas Gregor33834512009-06-14 07:33:30 +0000585 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000586 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000587 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000588 // A default template argument instantiation and substitution into
589 // template parameters with arguments for prior parameters may or may
590 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000591 break;
Mike Stump11289f42009-09-09 15:08:12 +0000592
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000593 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
594 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
595 // We're either substitution explicitly-specified template arguments
596 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000597 assert(Active->DeductionInfo && "Missing deduction info pointer");
598 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000599 }
600 }
601
David Blaikie7a30dc52013-02-21 01:47:18 +0000602 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000603}
604
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000605/// \brief Retrieve the depth and index of a parameter pack.
606static std::pair<unsigned, unsigned>
607getDepthAndIndex(NamedDecl *ND) {
608 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
609 return std::make_pair(TTP->getDepth(), TTP->getIndex());
610
611 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
612 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
613
614 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
615 return std::make_pair(TTP->getDepth(), TTP->getIndex());
616}
617
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000618//===----------------------------------------------------------------------===/
619// Template Instantiation for Types
620//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000621namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000622 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000623 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000624 SourceLocation Loc;
625 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000626
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000627 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000628 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000629
630 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000631 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000632 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000633 DeclarationName Entity)
634 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000635 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000636
Mike Stump11289f42009-09-09 15:08:12 +0000637 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000638 /// transformed.
639 ///
640 /// For the purposes of template instantiation, a type has already been
641 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000642 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000643
Douglas Gregord6ff3322009-08-04 16:50:30 +0000644 /// \brief Returns the location of the entity being instantiated, if known.
645 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000646
Douglas Gregord6ff3322009-08-04 16:50:30 +0000647 /// \brief Returns the name of the entity being instantiated, if any.
648 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000649
Douglas Gregoref6ab412009-10-27 06:26:26 +0000650 /// \brief Sets the "base" location and entity when that
651 /// information is known based on another transformation.
652 void setBase(SourceLocation Loc, DeclarationName Entity) {
653 this->Loc = Loc;
654 this->Entity = Entity;
655 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000656
657 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
658 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000659 ArrayRef<UnexpandedParameterPack> Unexpanded,
660 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000661 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000662 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
663 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000664 TemplateArgs,
665 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000666 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000667 NumExpansions);
668 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000669
Douglas Gregorf3010112011-01-07 16:43:16 +0000670 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
671 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
672 }
673
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000674 TemplateArgument ForgetPartiallySubstitutedPack() {
675 TemplateArgument Result;
676 if (NamedDecl *PartialPack
677 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
678 MultiLevelTemplateArgumentList &TemplateArgs
679 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
680 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000681 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000682 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
683 Result = TemplateArgs(Depth, Index);
684 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
685 }
686 }
687
688 return Result;
689 }
690
691 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
692 if (Arg.isNull())
693 return;
694
695 if (NamedDecl *PartialPack
696 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
697 MultiLevelTemplateArgumentList &TemplateArgs
698 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
699 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000700 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000701 TemplateArgs.setArgument(Depth, Index, Arg);
702 }
703 }
704
Douglas Gregord6ff3322009-08-04 16:50:30 +0000705 /// \brief Transform the given declaration by instantiating a reference to
706 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000707 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000708
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000709 void transformAttrs(Decl *Old, Decl *New) {
710 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
711 }
712
713 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000714 // If we've instantiated the call operator of a lambda or the call
715 // operator template of a generic lambda, update the "instantiation of"
716 // information.
717 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
718 if (NewMD && isLambdaCallOperator(NewMD)) {
719 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
720 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
721 NewTD->setInstantiatedFromMemberTemplate(
722 OldMD->getDescribedFunctionTemplate());
723 else
724 NewMD->setInstantiationOfMemberFunction(OldMD,
725 TSK_ImplicitInstantiation);
726 }
727
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000728 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000729
730 // We recreated a local declaration, but not by instantiating it. There
731 // may be pending dependent diagnostics to produce.
732 if (auto *DC = dyn_cast<DeclContext>(Old))
733 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000734 }
735
Mike Stump11289f42009-09-09 15:08:12 +0000736 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000737 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000738 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000739
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000740 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000741 /// declaration.
742 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
743
Douglas Gregorebe10102009-08-20 07:17:43 +0000744 /// \brief Rebuild the exception declaration and register the declaration
745 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000746 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000747 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000748 SourceLocation StartLoc,
749 SourceLocation NameLoc,
750 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000751
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000752 /// \brief Rebuild the Objective-C exception declaration and register the
753 /// declaration as an instantiated local.
754 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
755 TypeSourceInfo *TSInfo, QualType T);
756
John McCall7f41d982009-09-11 04:59:25 +0000757 /// \brief Check for tag mismatches when instantiating an
758 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000759 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
760 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000761 NestedNameSpecifierLoc QualifierLoc,
762 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000763
Craig Topperc3ec1492014-05-26 06:22:03 +0000764 TemplateName
765 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
766 SourceLocation NameLoc,
767 QualType ObjectType = QualType(),
768 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregor9db53502011-03-02 18:07:45 +0000769
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000770 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
771
John McCalldadc5752010-08-24 06:29:42 +0000772 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
773 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
774 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000775
John McCalldadc5752010-08-24 06:29:42 +0000776 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000777 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000778 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
779 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000780
781 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
782 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
783
784 /// \brief Transform a reference to a function parameter pack.
785 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
786 ParmVarDecl *PD);
787
788 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
789 /// expand a function parameter pack reference which refers to an expanded
790 /// pack.
791 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
792
Hans Wennborge113c202014-09-18 16:01:32 +0000793 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000794 FunctionProtoTypeLoc TL) {
795 // Call the base version; it will forward to our overridden version below.
796 return inherited::TransformFunctionProtoType(TLB, TL);
797 }
798
799 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000800 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
801 FunctionProtoTypeLoc TL,
802 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000803 unsigned ThisTypeQuals,
804 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000805
Douglas Gregor715e4612011-01-14 22:40:04 +0000806 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000807 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000808 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000809 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000810
Mike Stump11289f42009-09-09 15:08:12 +0000811 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000812 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000813 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000814 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000815
Douglas Gregorada4b792011-01-14 02:55:32 +0000816 /// \brief Transforms an already-substituted template type parameter pack
817 /// into either itself (if we aren't substituting into its pack expansion)
818 /// or the appropriate substituted argument.
819 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
820 SubstTemplateTypeParmPackTypeLoc TL);
821
Richard Smith2589b9802012-07-25 03:56:55 +0000822 ExprResult TransformLambdaExpr(LambdaExpr *E) {
823 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
824 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
825 }
826
David Majnemerb1004102014-03-02 18:46:05 +0000827 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000828 TemplateParameterList *OrigTPL) {
829 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
830
831 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
832 TemplateDeclInstantiator DeclInstantiator(getSema(),
833 /* DeclContext *Owner */ Owner, TemplateArgs);
834 return DeclInstantiator.SubstTemplateParams(OrigTPL);
835 }
John McCall7c454bb2011-07-15 05:09:51 +0000836 private:
837 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
838 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000839 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000840 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000841}
Douglas Gregor04318252009-07-06 15:59:29 +0000842
Douglas Gregor5597ab42010-05-07 23:12:07 +0000843bool TemplateInstantiator::AlreadyTransformed(QualType T) {
844 if (T.isNull())
845 return true;
846
Douglas Gregor678d76c2011-07-01 01:22:09 +0000847 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000848 return false;
849
850 getSema().MarkDeclarationsReferencedInType(Loc, T);
851 return true;
852}
853
Eli Friedman8917ad52013-07-19 19:40:38 +0000854static TemplateArgument
855getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
856 assert(S.ArgumentPackSubstitutionIndex >= 0);
857 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
858 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
859 if (Arg.isPackExpansion())
860 Arg = Arg.getPackExpansionPattern();
861 return Arg;
862}
863
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000864Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000865 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000866 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000867
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000868 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000869 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000870 // If the corresponding template argument is NULL or non-existent, it's
871 // because we are performing instantiation from explicitly-specified
872 // template arguments in a function template, but there were some
873 // arguments left unspecified.
874 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
875 TTP->getPosition()))
876 return D;
877
Douglas Gregorf5500772011-01-05 15:48:55 +0000878 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
879
880 if (TTP->isParameterPack()) {
881 assert(Arg.getKind() == TemplateArgument::Pack &&
882 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000883 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000884 }
885
886 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000887 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000888 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000889 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000890 }
Mike Stump11289f42009-09-09 15:08:12 +0000891
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000892 // Fall through to find the instantiated declaration for this template
893 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000894 }
Mike Stump11289f42009-09-09 15:08:12 +0000895
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000896 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000897}
898
Douglas Gregor25289362010-03-01 17:25:41 +0000899Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000900 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000901 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000902 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000903
Douglas Gregorebe10102009-08-20 07:17:43 +0000904 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
905 return Inst;
906}
907
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000908NamedDecl *
909TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
910 SourceLocation Loc) {
911 // If the first part of the nested-name-specifier was a template type
912 // parameter, instantiate that type parameter down to a tag type.
913 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
914 const TemplateTypeParmType *TTP
915 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000916
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000917 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000918 // FIXME: This needs testing w/ member access expressions.
919 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
920
921 if (TTP->isParameterPack()) {
922 assert(Arg.getKind() == TemplateArgument::Pack &&
923 "Missing argument pack");
924
Douglas Gregore1d60df2011-01-14 23:41:42 +0000925 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +0000926 return nullptr;
927
Eli Friedman8917ad52013-07-19 19:40:38 +0000928 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000929 }
930
931 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000932 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000933 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000934
935 if (const TagType *Tag = T->getAs<TagType>())
936 return Tag->getDecl();
937
938 // The resulting type is not a tag; complain.
939 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +0000940 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000941 }
942 }
943
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000944 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000945}
946
Douglas Gregorebe10102009-08-20 07:17:43 +0000947VarDecl *
948TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000949 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000950 SourceLocation StartLoc,
951 SourceLocation NameLoc,
952 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000953 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000954 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000955 if (Var)
956 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
957 return Var;
958}
959
960VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
961 TypeSourceInfo *TSInfo,
962 QualType T) {
963 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
964 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000965 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
966 return Var;
967}
968
John McCall7f41d982009-09-11 04:59:25 +0000969QualType
John McCall954b5de2010-11-04 19:04:38 +0000970TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
971 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000972 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000973 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +0000974 if (const TagType *TT = T->getAs<TagType>()) {
975 TagDecl* TD = TT->getDecl();
976
John McCall954b5de2010-11-04 19:04:38 +0000977 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +0000978
John McCall7f41d982009-09-11 04:59:25 +0000979 IdentifierInfo *Id = TD->getIdentifier();
980
981 // TODO: should we even warn on struct/class mismatches for this? Seems
982 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +0000983 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000984 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +0000985 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +0000986 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000987 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
988 << Id
989 << FixItHint::CreateReplacement(SourceRange(TagLocation),
990 TD->getKindName());
991 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
992 }
John McCall7f41d982009-09-11 04:59:25 +0000993 }
994 }
995
John McCall954b5de2010-11-04 19:04:38 +0000996 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
997 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000998 QualifierLoc,
999 T);
John McCall7f41d982009-09-11 04:59:25 +00001000}
1001
Douglas Gregor9db53502011-03-02 18:07:45 +00001002TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1003 TemplateName Name,
Nico Weberc153d242014-07-28 00:02:09 +00001004 SourceLocation NameLoc,
Douglas Gregor9db53502011-03-02 18:07:45 +00001005 QualType ObjectType,
1006 NamedDecl *FirstQualifierInScope) {
1007 if (TemplateTemplateParmDecl *TTP
1008 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1009 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1010 // If the corresponding template argument is NULL or non-existent, it's
1011 // because we are performing instantiation from explicitly-specified
1012 // template arguments in a function template, but there were some
1013 // arguments left unspecified.
1014 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1015 TTP->getPosition()))
1016 return Name;
1017
1018 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1019
1020 if (TTP->isParameterPack()) {
1021 assert(Arg.getKind() == TemplateArgument::Pack &&
1022 "Missing argument pack");
1023
1024 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1025 // We have the template argument pack to substitute, but we're not
1026 // actually expanding the enclosing pack expansion yet. So, just
1027 // keep the entire argument pack.
1028 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1029 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001030
1031 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001032 }
1033
1034 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001035 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001036
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001037 // We don't ever want to substitute for a qualified template name, since
1038 // the qualifier is handled separately. So, look through the qualified
1039 // template name to its underlying declaration.
1040 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1041 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001042
1043 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001044 return Template;
1045 }
1046 }
1047
1048 if (SubstTemplateTemplateParmPackStorage *SubstPack
1049 = Name.getAsSubstTemplateTemplateParmPack()) {
1050 if (getSema().ArgumentPackSubstitutionIndex == -1)
1051 return Name;
1052
Eli Friedman8917ad52013-07-19 19:40:38 +00001053 TemplateArgument Arg = SubstPack->getArgumentPack();
1054 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1055 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001056 }
1057
1058 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1059 FirstQualifierInScope);
1060}
1061
John McCalldadc5752010-08-24 06:29:42 +00001062ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001063TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001064 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001065 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001066
Wei Panc354d212013-09-16 13:57:27 +00001067 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001068}
1069
John McCalldadc5752010-08-24 06:29:42 +00001070ExprResult
John McCall13481c52010-02-06 08:42:39 +00001071TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001072 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001073 // If the corresponding template argument is NULL or non-existent, it's
1074 // because we are performing instantiation from explicitly-specified
1075 // template arguments in a function template, but there were some
1076 // arguments left unspecified.
1077 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1078 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001079 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001080
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001081 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1082 if (NTTP->isParameterPack()) {
1083 assert(Arg.getKind() == TemplateArgument::Pack &&
1084 "Missing argument pack");
1085
1086 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001087 // We have an argument pack, but we can't select a particular argument
1088 // out of it yet. Therefore, we'll build an expression to hold on to that
1089 // argument pack.
1090 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1091 E->getLocation(),
1092 NTTP->getDeclName());
1093 if (TargetType.isNull())
1094 return ExprError();
1095
1096 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1097 NTTP,
1098 E->getLocation(),
1099 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001100 }
1101
Eli Friedman8917ad52013-07-19 19:40:38 +00001102 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001103 }
Mike Stump11289f42009-09-09 15:08:12 +00001104
John McCall7c454bb2011-07-15 05:09:51 +00001105 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1106}
1107
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001108const LoopHintAttr *
1109TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1110 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1111
1112 if (TransformedExpr == LH->getValue())
1113 return LH;
1114
1115 // Generate error if there is a problem with the value.
1116 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1117 return LH;
1118
1119 // Create new LoopHintValueAttr with integral expression in place of the
1120 // non-type template parameter.
1121 return LoopHintAttr::CreateImplicit(
1122 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1123 LH->getState(), TransformedExpr, LH->getRange());
1124}
1125
John McCall7c454bb2011-07-15 05:09:51 +00001126ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1127 NonTypeTemplateParmDecl *parm,
1128 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001129 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001130 ExprResult result;
1131 QualType type;
1132
John McCall13481c52010-02-06 08:42:39 +00001133 // The template argument itself might be an expression, in which
1134 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001135 if (arg.getKind() == TemplateArgument::Expression) {
1136 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001137 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001138 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001139
Eli Friedmanb826a002012-09-26 02:36:12 +00001140 } else if (arg.getKind() == TemplateArgument::Declaration ||
1141 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001142 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001143 if (arg.getKind() == TemplateArgument::Declaration) {
1144 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001145
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001146 // Find the instantiation of the template argument. This is
1147 // required for nested templates.
1148 VD = cast_or_null<ValueDecl>(
1149 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1150 if (!VD)
1151 return ExprError();
1152 } else {
1153 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001154 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001155 }
1156
John McCall15dda372010-02-06 10:23:53 +00001157 // Derive the type we want the substituted decl to have. This had
1158 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001159 if (parm->isExpandedParameterPack()) {
1160 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1161 } else if (parm->isParameterPack() &&
1162 isa<PackExpansionType>(parm->getType())) {
1163 type = SemaRef.SubstType(
1164 cast<PackExpansionType>(parm->getType())->getPattern(),
1165 TemplateArgs, loc, parm->getDeclName());
1166 } else {
1167 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1168 loc, parm->getDeclName());
1169 }
1170 assert(!type.isNull() && "type substitution failed for param type");
1171 assert(!type->isDependentType() && "param type still dependent");
1172 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001173
John McCall7c454bb2011-07-15 05:09:51 +00001174 if (!result.isInvalid()) type = result.get()->getType();
1175 } else {
1176 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1177
1178 // Note that this type can be different from the type of 'result',
1179 // e.g. if it's an enum type.
1180 type = arg.getIntegralType();
1181 }
1182 if (result.isInvalid()) return ExprError();
1183
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001184 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001185 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1186 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001187}
1188
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001189ExprResult
1190TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1191 SubstNonTypeTemplateParmPackExpr *E) {
1192 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1193 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001194 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001195 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001196
1197 TemplateArgument Arg = E->getArgumentPack();
1198 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001199 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1200 E->getParameterPackLocation(),
1201 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001202}
John McCall13481c52010-02-06 08:42:39 +00001203
John McCalldadc5752010-08-24 06:29:42 +00001204ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001205TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1206 SourceLocation Loc) {
1207 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1208 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1209}
1210
1211ExprResult
1212TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1213 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1214 // We can expand this parameter pack now.
1215 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1216 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1217 if (!VD)
1218 return ExprError();
1219 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1220 }
1221
1222 QualType T = TransformType(E->getType());
1223 if (T.isNull())
1224 return ExprError();
1225
1226 // Transform each of the parameter expansions into the corresponding
1227 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001228 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001229 Parms.reserve(E->getNumExpansions());
1230 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1231 I != End; ++I) {
1232 ParmVarDecl *D =
1233 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1234 if (!D)
1235 return ExprError();
1236 Parms.push_back(D);
1237 }
1238
1239 return FunctionParmPackExpr::Create(getSema().Context, T,
1240 E->getParameterPack(),
1241 E->getParameterPackLocation(), Parms);
1242}
1243
1244ExprResult
1245TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1246 ParmVarDecl *PD) {
1247 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1248 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1249 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1250 assert(Found && "no instantiation for parameter pack");
1251
1252 Decl *TransformedDecl;
1253 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001254 // If this is a reference to a function parameter pack which we can
1255 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001256 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1257 QualType T = TransformType(E->getType());
1258 if (T.isNull())
1259 return ExprError();
1260 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1261 E->getExprLoc(), *Pack);
1262 }
1263
1264 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1265 } else {
1266 TransformedDecl = Found->get<Decl*>();
1267 }
1268
1269 // We have either an unexpanded pack or a specific expansion.
1270 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1271 E->getExprLoc());
1272}
1273
1274ExprResult
John McCall13481c52010-02-06 08:42:39 +00001275TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1276 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001277
1278 // Handle references to non-type template parameters and non-type template
1279 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001280 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1281 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1282 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001283
1284 // We have a non-type template parameter that isn't fully substituted;
1285 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001286 }
Mike Stump11289f42009-09-09 15:08:12 +00001287
Richard Smithb15fe3a2012-09-12 00:56:43 +00001288 // Handle references to function parameter packs.
1289 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1290 if (PD->isParameterPack())
1291 return TransformFunctionParmPackRefExpr(E, PD);
1292
John McCall47f29ea2009-12-08 09:21:05 +00001293 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001294}
1295
John McCalldadc5752010-08-24 06:29:42 +00001296ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001297 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001298 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1299 getDescribedFunctionTemplate() &&
1300 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001301 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1302 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1303 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001304}
1305
Richard Smith2e321552014-11-12 02:00:47 +00001306template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001307QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1308 FunctionProtoTypeLoc TL,
1309 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001310 unsigned ThisTypeQuals,
1311 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001312 // We need a local instantiation scope for this function prototype.
1313 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001314 return inherited::TransformFunctionProtoType(
1315 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001316}
1317
John McCall58f10c32010-03-11 09:03:00 +00001318ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001319TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001320 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001321 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001322 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001323 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001324 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001325}
1326
Mike Stump11289f42009-09-09 15:08:12 +00001327QualType
John McCall550e0c22009-10-21 00:40:46 +00001328TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001329 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001330 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001331 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001332 // Replace the template type parameter with its corresponding
1333 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001334
1335 // If the corresponding template argument is NULL or doesn't exist, it's
1336 // because we are performing instantiation from explicitly-specified
1337 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001338 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001339 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1340 TemplateTypeParmTypeLoc NewTL
1341 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1342 NewTL.setNameLoc(TL.getNameLoc());
1343 return TL.getType();
1344 }
Mike Stump11289f42009-09-09 15:08:12 +00001345
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001346 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1347
1348 if (T->isParameterPack()) {
1349 assert(Arg.getKind() == TemplateArgument::Pack &&
1350 "Missing argument pack");
1351
1352 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001353 // We have the template argument pack, but we're not expanding the
1354 // enclosing pack expansion yet. Just save the template argument
1355 // pack for later substitution.
1356 QualType Result
1357 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1358 SubstTemplateTypeParmPackTypeLoc NewTL
1359 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1360 NewTL.setNameLoc(TL.getNameLoc());
1361 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001362 }
1363
Eli Friedman8917ad52013-07-19 19:40:38 +00001364 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001365 }
1366
1367 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001368 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001369
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001370 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001371
1372 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001373 QualType Result
1374 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1375 SubstTemplateTypeParmTypeLoc NewTL
1376 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1377 NewTL.setNameLoc(TL.getNameLoc());
1378 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001379 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001380
1381 // The template type parameter comes from an inner template (e.g.,
1382 // the template parameter list of a member template inside the
1383 // template we are instantiating). Create a new template type
1384 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001385 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001386 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1387 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1388 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1389
John McCall550e0c22009-10-21 00:40:46 +00001390 QualType Result
1391 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1392 - TemplateArgs.getNumLevels(),
1393 T->getIndex(),
1394 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001395 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001396 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1397 NewTL.setNameLoc(TL.getNameLoc());
1398 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001399}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001400
Douglas Gregorada4b792011-01-14 02:55:32 +00001401QualType
1402TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1403 TypeLocBuilder &TLB,
1404 SubstTemplateTypeParmPackTypeLoc TL) {
1405 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1406 // We aren't expanding the parameter pack, so just return ourselves.
1407 SubstTemplateTypeParmPackTypeLoc NewTL
1408 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1409 NewTL.setNameLoc(TL.getNameLoc());
1410 return TL.getType();
1411 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001412
1413 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1414 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1415 QualType Result = Arg.getAsType();
1416
Douglas Gregorada4b792011-01-14 02:55:32 +00001417 Result = getSema().Context.getSubstTemplateTypeParmType(
1418 TL.getTypePtr()->getReplacedParameter(),
1419 Result);
1420 SubstTemplateTypeParmTypeLoc NewTL
1421 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1422 NewTL.setNameLoc(TL.getNameLoc());
1423 return Result;
1424}
1425
John McCall76d824f2009-08-25 22:02:44 +00001426/// \brief Perform substitution on the type T with a given set of template
1427/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001428///
1429/// This routine substitutes the given template arguments into the
1430/// type T and produces the instantiated type.
1431///
1432/// \param T the type into which the template arguments will be
1433/// substituted. If this type is not dependent, it will be returned
1434/// immediately.
1435///
James Dennett634962f2012-06-14 21:40:34 +00001436/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001437/// substituted for the top-level template parameters within T.
1438///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001439/// \param Loc the location in the source code where this substitution
1440/// is being performed. It will typically be the location of the
1441/// declarator (if we're instantiating the type of some declaration)
1442/// or the location of the type in the source code (if, e.g., we're
1443/// instantiating the type of a cast expression).
1444///
1445/// \param Entity the name of the entity associated with a declaration
1446/// being instantiated (if any). May be empty to indicate that there
1447/// is no such entity (if, e.g., this is a type that occurs as part of
1448/// a cast expression) or that the entity has no name (e.g., an
1449/// unnamed function parameter).
1450///
1451/// \returns If the instantiation succeeds, the instantiated
1452/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001453TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001454 const MultiLevelTemplateArgumentList &Args,
1455 SourceLocation Loc,
1456 DeclarationName Entity) {
1457 assert(!ActiveTemplateInstantiations.empty() &&
1458 "Cannot perform an instantiation without some context on the "
1459 "instantiation stack");
1460
Douglas Gregor678d76c2011-07-01 01:22:09 +00001461 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001462 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001463 return T;
1464
1465 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1466 return Instantiator.TransformType(T);
1467}
1468
Douglas Gregor5499af42011-01-05 23:12:31 +00001469TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1470 const MultiLevelTemplateArgumentList &Args,
1471 SourceLocation Loc,
1472 DeclarationName Entity) {
1473 assert(!ActiveTemplateInstantiations.empty() &&
1474 "Cannot perform an instantiation without some context on the "
1475 "instantiation stack");
1476
1477 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001478 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001479
Douglas Gregor678d76c2011-07-01 01:22:09 +00001480 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001481 !TL.getType()->isVariablyModifiedType()) {
1482 // FIXME: Make a copy of the TypeLoc data here, so that we can
1483 // return a new TypeSourceInfo. Inefficient!
1484 TypeLocBuilder TLB;
1485 TLB.pushFullCopy(TL);
1486 return TLB.getTypeSourceInfo(Context, TL.getType());
1487 }
1488
1489 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1490 TypeLocBuilder TLB;
1491 TLB.reserve(TL.getFullDataSize());
1492 QualType Result = Instantiator.TransformType(TLB, TL);
1493 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001494 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001495
1496 return TLB.getTypeSourceInfo(Context, Result);
1497}
1498
John McCall609459e2009-10-21 00:58:09 +00001499/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001500QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001501 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001502 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001503 assert(!ActiveTemplateInstantiations.empty() &&
1504 "Cannot perform an instantiation without some context on the "
1505 "instantiation stack");
1506
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001507 // If T is not a dependent type or a variably-modified type, there
1508 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001509 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001510 return T;
1511
Douglas Gregord6ff3322009-08-04 16:50:30 +00001512 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1513 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001514}
Douglas Gregor463421d2009-03-03 04:44:36 +00001515
John McCallb29f78f2010-04-09 17:38:44 +00001516static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001517 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001518 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001519 return true;
1520
Abramo Bagnara6d810632010-12-14 22:11:44 +00001521 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001522 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001523 return false;
1524
David Blaikie6adc78e2013-02-18 22:06:02 +00001525 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001526 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001527 // This must be synthesized from a typedef.
1528 if (!P) continue;
1529
Nico Weberc0973372016-02-01 22:31:51 +00001530 // If there are any parameters, a new TypeSourceInfo that refers to the
1531 // instantiated parameters must be built.
1532 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001533 }
1534
1535 return false;
1536}
1537
1538/// A form of SubstType intended specifically for instantiating the
1539/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001540/// instantiation of default-argument expressions and to avoid
1541/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001542TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1543 const MultiLevelTemplateArgumentList &Args,
1544 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001545 DeclarationName Entity,
1546 CXXRecordDecl *ThisContext,
1547 unsigned ThisTypeQuals) {
John McCallb29f78f2010-04-09 17:38:44 +00001548 assert(!ActiveTemplateInstantiations.empty() &&
1549 "Cannot perform an instantiation without some context on the "
1550 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001551
John McCallb29f78f2010-04-09 17:38:44 +00001552 if (!NeedsInstantiationAsFunctionType(T))
1553 return T;
1554
1555 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1556
1557 TypeLocBuilder TLB;
1558
1559 TypeLoc TL = T->getTypeLoc();
1560 TLB.reserve(TL.getFullDataSize());
1561
Douglas Gregor3024f072012-04-16 07:05:22 +00001562 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001563
Richard Smith2e321552014-11-12 02:00:47 +00001564 if (FunctionProtoTypeLoc Proto =
1565 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1566 // Instantiate the type, other than its exception specification. The
1567 // exception specification is instantiated in InitFunctionInstantiation
1568 // once we've built the FunctionDecl.
1569 // FIXME: Set the exception specification to EST_Uninstantiated here,
1570 // instead of rebuilding the function type again later.
1571 Result = Instantiator.TransformFunctionProtoType(
1572 TLB, Proto, ThisContext, ThisTypeQuals,
1573 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1574 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001575 } else {
1576 Result = Instantiator.TransformType(TLB, TL);
1577 }
John McCallb29f78f2010-04-09 17:38:44 +00001578 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001579 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001580
1581 return TLB.getTypeSourceInfo(Context, Result);
1582}
1583
Richard Smith2e321552014-11-12 02:00:47 +00001584void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1585 const MultiLevelTemplateArgumentList &Args) {
1586 FunctionProtoType::ExceptionSpecInfo ESI =
1587 Proto->getExtProtoInfo().ExceptionSpec;
1588 assert(ESI.Type != EST_Uninstantiated);
1589
1590 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1591 New->getDeclName());
1592
1593 SmallVector<QualType, 4> ExceptionStorage;
1594 bool Changed = false;
1595 if (Instantiator.TransformExceptionSpec(
1596 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1597 ExceptionStorage, Changed))
1598 // On error, recover by dropping the exception specification.
1599 ESI.Type = EST_None;
1600
1601 UpdateExceptionSpec(New, ESI);
1602}
1603
Douglas Gregor940bca72010-04-12 07:48:19 +00001604ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001605 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001606 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001607 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001608 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001609 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001610 TypeSourceInfo *NewDI = nullptr;
1611
Douglas Gregor5499af42011-01-05 23:12:31 +00001612 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001613 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1614
Douglas Gregor5499af42011-01-05 23:12:31 +00001615 // We have a function parameter pack. Substitute into the pattern of the
1616 // expansion.
1617 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1618 OldParm->getLocation(), OldParm->getDeclName());
1619 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001620 return nullptr;
1621
Douglas Gregor5499af42011-01-05 23:12:31 +00001622 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1623 // We still have unexpanded parameter packs, which means that
1624 // our function parameter is still a function parameter pack.
1625 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001626 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001627 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001628 } else if (ExpectParameterPack) {
1629 // We expected to get a parameter pack but didn't (because the type
1630 // itself is not a pack expansion type), so complain. This can occur when
1631 // the substitution goes through an alias template that "loses" the
1632 // pack expansion.
1633 Diag(OldParm->getLocation(),
1634 diag::err_function_parameter_pack_without_parameter_packs)
1635 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001636 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001637 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001638 } else {
1639 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1640 OldParm->getDeclName());
1641 }
1642
Douglas Gregor940bca72010-04-12 07:48:19 +00001643 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001644 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001645
1646 if (NewDI->getType()->isVoidType()) {
1647 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001648 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001649 }
1650
1651 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001652 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001653 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001654 OldParm->getIdentifier(),
1655 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001656 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001657 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001658 return nullptr;
1659
Douglas Gregor940bca72010-04-12 07:48:19 +00001660 // Mark the (new) default argument as uninstantiated (if any).
1661 if (OldParm->hasUninstantiatedDefaultArg()) {
1662 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1663 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001664 } else if (OldParm->hasUnparsedDefaultArg()) {
1665 NewParm->setUnparsedDefaultArg();
1666 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001667 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1668 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001669 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1670 // Instantiate default arguments for methods of local classes (DR1484)
1671 // and non-defining declarations.
1672 Sema::ContextRAII SavedContext(*this, OwningFunc);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001673 LocalInstantiationScope Local(*this);
1674 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001675 if (NewArg.isUsable()) {
1676 // It would be nice if we still had this.
1677 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1678 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1679 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001680 } else {
1681 // FIXME: if we non-lazily instantiated non-dependent default args for
1682 // non-dependent parameter types we could remove a bunch of duplicate
1683 // conversion warnings for such arguments.
1684 NewParm->setUninstantiatedDefaultArg(Arg);
1685 }
1686 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001687
1688 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001689
Douglas Gregorf3010112011-01-07 16:43:16 +00001690 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001691 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001692 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1693 } else {
1694 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001695 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001696 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001697
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001698 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1699 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001700 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001701
1702 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1703 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001704
1705 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1706
Douglas Gregor940bca72010-04-12 07:48:19 +00001707 return NewParm;
1708}
1709
Douglas Gregordd472162011-01-07 00:20:55 +00001710/// \brief Substitute the given template arguments into the given set of
1711/// parameters, producing the set of parameter types that would be generated
1712/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001713bool Sema::SubstParmTypes(
1714 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1715 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1716 const MultiLevelTemplateArgumentList &TemplateArgs,
1717 SmallVectorImpl<QualType> &ParamTypes,
1718 SmallVectorImpl<ParmVarDecl *> *OutParams,
1719 ExtParameterInfoBuilder &ParamInfos) {
Douglas Gregordd472162011-01-07 00:20:55 +00001720 assert(!ActiveTemplateInstantiations.empty() &&
1721 "Cannot perform an instantiation without some context on the "
1722 "instantiation stack");
1723
1724 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1725 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001726 return Instantiator.TransformFunctionTypeParams(
1727 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001728}
1729
John McCall76d824f2009-08-25 22:02:44 +00001730/// \brief Perform substitution on the base class specifiers of the
1731/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001732///
1733/// Produces a diagnostic and returns true on error, returns false and
1734/// attaches the instantiated base classes to the class template
1735/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001736bool
John McCall76d824f2009-08-25 22:02:44 +00001737Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1738 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001739 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001740 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001741 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001742 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001743 if (!Base.getType()->isDependentType()) {
1744 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001745 if (RD->isInvalidDecl())
1746 Instantiation->setInvalidDecl();
1747 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001748 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001749 continue;
1750 }
1751
Douglas Gregor752a5952011-01-03 22:36:02 +00001752 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001753 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001754 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001755 // This is a pack expansion. See whether we should expand it now, or
1756 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001757 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001758 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001759 Unexpanded);
1760 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001761 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001762 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001763 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1764 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001765 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001766 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001767 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001768 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001769 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001770 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001771 }
1772
1773 // If we should expand this pack expansion now, do so.
1774 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001775 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001776 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1777
Aaron Ballman574705e2014-03-13 15:41:46 +00001778 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001779 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001780 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001781 DeclarationName());
1782 if (!BaseTypeLoc) {
1783 Invalid = true;
1784 continue;
1785 }
1786
1787 if (CXXBaseSpecifier *InstantiatedBase
1788 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001789 Base.getSourceRange(),
1790 Base.isVirtual(),
1791 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001792 BaseTypeLoc,
1793 SourceLocation()))
1794 InstantiatedBases.push_back(InstantiatedBase);
1795 else
1796 Invalid = true;
1797 }
1798
1799 continue;
1800 }
1801
1802 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001803 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001804 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001805 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001806 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001807 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001808 DeclarationName());
1809 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001810 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001811 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001812 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001813 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001814 }
1815
Nick Lewycky19b9f952010-07-26 16:56:01 +00001816 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001817 Invalid = true;
1818 continue;
1819 }
1820
1821 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001822 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001823 Base.getSourceRange(),
1824 Base.isVirtual(),
1825 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001826 BaseTypeLoc,
1827 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001828 InstantiatedBases.push_back(InstantiatedBase);
1829 else
1830 Invalid = true;
1831 }
1832
Craig Topperaa700cb2015-12-27 21:55:19 +00001833 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001834 Invalid = true;
1835
1836 return Invalid;
1837}
1838
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001839// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001840namespace clang {
1841 namespace sema {
1842 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1843 const MultiLevelTemplateArgumentList &TemplateArgs);
1844 }
1845}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001846
Richard Smith4b38ded2012-03-14 23:13:10 +00001847/// Determine whether we would be unable to instantiate this template (because
1848/// it either has no definition, or is in the process of being instantiated).
1849static bool DiagnoseUninstantiableTemplate(Sema &S,
1850 SourceLocation PointOfInstantiation,
1851 TagDecl *Instantiation,
1852 bool InstantiatedFromMember,
1853 TagDecl *Pattern,
1854 TagDecl *PatternDef,
1855 TemplateSpecializationKind TSK,
1856 bool Complain = true) {
Richard Smith6739a102016-05-05 00:56:12 +00001857 if (PatternDef && !PatternDef->isBeingDefined()) {
1858 NamedDecl *SuggestedDef = nullptr;
1859 if (!S.hasVisibleDefinition(PatternDef, &SuggestedDef,
1860 /*OnlyNeedComplete*/false)) {
1861 // If we're allowed to diagnose this and recover, do so.
1862 bool Recover = Complain && !S.isSFINAEContext();
1863 if (Complain)
1864 S.diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
1865 Sema::MissingImportKind::Definition, Recover);
1866 return !Recover;
1867 }
Richard Smith4b38ded2012-03-14 23:13:10 +00001868 return false;
Richard Smith6739a102016-05-05 00:56:12 +00001869 }
Richard Smith4b38ded2012-03-14 23:13:10 +00001870
1871 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1872 // Say nothing
1873 } else if (PatternDef) {
1874 assert(PatternDef->isBeingDefined());
1875 S.Diag(PointOfInstantiation,
1876 diag::err_template_instantiate_within_definition)
1877 << (TSK != TSK_ImplicitInstantiation)
1878 << S.Context.getTypeDeclType(Instantiation);
1879 // Not much point in noting the template declaration here, since
1880 // we're lexically inside it.
1881 Instantiation->setInvalidDecl();
1882 } else if (InstantiatedFromMember) {
1883 S.Diag(PointOfInstantiation,
1884 diag::err_implicit_instantiate_member_undefined)
1885 << S.Context.getTypeDeclType(Instantiation);
Alp Toker2afa8782014-05-28 12:20:14 +00001886 S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
Richard Smith4b38ded2012-03-14 23:13:10 +00001887 } else {
1888 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1889 << (TSK != TSK_ImplicitInstantiation)
1890 << S.Context.getTypeDeclType(Instantiation);
1891 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1892 }
1893
1894 // In general, Instantiation isn't marked invalid to get more than one
1895 // error for multiple undefined instantiations. But the code that does
1896 // explicit declaration -> explicit definition conversion can't handle
1897 // invalid declarations, so mark as invalid in that case.
1898 if (TSK == TSK_ExplicitInstantiationDeclaration)
1899 Instantiation->setInvalidDecl();
1900 return true;
1901}
1902
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001903/// \brief Instantiate the definition of a class from a given pattern.
1904///
1905/// \param PointOfInstantiation The point of instantiation within the
1906/// source code.
1907///
1908/// \param Instantiation is the declaration whose definition is being
1909/// instantiated. This will be either a class template specialization
1910/// or a member class of a class template specialization.
1911///
1912/// \param Pattern is the pattern from which the instantiation
1913/// occurs. This will be either the declaration of a class template or
1914/// the declaration of a member class of a class template.
1915///
1916/// \param TemplateArgs The template arguments to be substituted into
1917/// the pattern.
1918///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001919/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001920///
1921/// \param Complain whether to complain if the class cannot be instantiated due
1922/// to the lack of a definition.
1923///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001924/// \returns true if an error occurred, false otherwise.
1925bool
1926Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1927 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001928 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001929 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001930 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001931 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001932 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smith4b38ded2012-03-14 23:13:10 +00001933 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1934 Instantiation->getInstantiatedFromMemberClass(),
1935 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001936 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001937 Pattern = PatternDef;
1938
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001939 // \brief Record the point of instantiation.
1940 if (MemberSpecializationInfo *MSInfo
1941 = Instantiation->getMemberSpecializationInfo()) {
1942 MSInfo->setTemplateSpecializationKind(TSK);
1943 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001944 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001945 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001946 Spec->setTemplateSpecializationKind(TSK);
1947 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001948 }
Richard Smitha1087602014-03-10 00:04:29 +00001949
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001950 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001951 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001952 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00001953 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
1954 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001955
1956 // Enter the scope of this instantiation. We don't use
1957 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001958 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001959 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001960 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001961
Douglas Gregor51121572010-03-24 01:33:17 +00001962 // If this is an instantiation of a local class, merge this local
1963 // instantiation scope with the enclosing scope. Otherwise, every
1964 // instantiation of a class has its own local instantiation scope.
1965 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001966 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001967
Reid Kleckner5b640342016-02-26 19:51:02 +00001968 // All dllexported classes created during instantiation should be fully
1969 // emitted after instantiation completes. We may not be ready to emit any
1970 // delayed classes already on the stack, so save them away and put them back
1971 // later.
1972 decltype(DelayedDllExportClasses) ExportedClasses;
1973 std::swap(ExportedClasses, DelayedDllExportClasses);
1974
John McCall6602bb12010-08-01 02:01:53 +00001975 // Pull attributes from the pattern onto the instantiation.
1976 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1977
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001978 // Start the definition of this instantiation.
1979 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00001980
1981 // The instantiation is visible here, even if it was first declared in an
1982 // unimported module.
1983 Instantiation->setHidden(false);
1984
1985 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00001986 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001987
John McCall76d824f2009-08-25 22:02:44 +00001988 // Do substitution on the base class specifiers.
1989 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001990 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001991
Douglas Gregor869853e2010-11-10 19:44:59 +00001992 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001993 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001994 // Delay instantiation of late parsed attributes.
1995 LateInstantiatedAttrVec LateAttrs;
1996 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1997
Aaron Ballman629afae2014-03-07 19:56:05 +00001998 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001999 // Don't instantiate members not belonging in this semantic context.
2000 // e.g. for:
2001 // @code
2002 // template <int i> class A {
2003 // class B *g;
2004 // };
2005 // @endcode
2006 // 'class B' has the template as lexical context but semantically it is
2007 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002008 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002009 continue;
2010
Aaron Ballman629afae2014-03-07 19:56:05 +00002011 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002012 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002013 continue;
2014 }
2015
Aaron Ballman629afae2014-03-07 19:56:05 +00002016 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002017 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002018 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002019 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002020 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2021 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2022 // specialization causes the implicit instantiation of the definitions
2023 // of unscoped member enumerations.
2024 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002025 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2026 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002027 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2028 assert(MSInfo && "no spec info for member enum specialization");
2029 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2030 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2031 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002032 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2033 if (SA->isFailed()) {
2034 // A static_assert failed. Bail out; instantiating this
2035 // class is probably not meaningful.
2036 Instantiation->setInvalidDecl();
2037 break;
2038 }
Richard Smith7d137e32012-03-23 03:33:32 +00002039 }
2040
2041 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002042 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002043 } else {
2044 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002045 // instantiations was a semantic disaster, and we'll want to mark the
2046 // declaration invalid.
2047 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002048 }
2049 }
2050
2051 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002052 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2053 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002054 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002055
Reid Kleckner93f661a2015-03-17 21:51:43 +00002056 // Default arguments are parsed, if not instantiated. We can go instantiate
2057 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002058 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002059
Reid Kleckner5b640342016-02-26 19:51:02 +00002060 // Put back the delayed exported classes that we moved out of the way.
2061 std::swap(ExportedClasses, DelayedDllExportClasses);
2062
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002063 // Instantiate late parsed attributes, and attach them to their decls.
2064 // See Sema::InstantiateAttrs
2065 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2066 E = LateAttrs.end(); I != E; ++I) {
2067 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2068 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002069
2070 // Allow 'this' within late-parsed attributes.
2071 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2072 CXXRecordDecl *ThisContext =
2073 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2074 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2075 ND && ND->isCXXInstanceMember());
2076
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002077 Attr *NewAttr =
2078 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2079 I->NewDecl->addAttr(NewAttr);
2080 LocalInstantiationScope::deleteScopes(I->Scope,
2081 Instantiator.getStartingScope());
2082 }
2083 Instantiator.disableLateAttributeInstantiation();
2084 LateAttrs.clear();
2085
Richard Smithd3b5c9082012-07-27 04:22:15 +00002086 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002087
Richard Smitha1087602014-03-10 00:04:29 +00002088 // FIXME: We should do something similar for explicit instantiations so they
2089 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002090 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002091 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002092 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002093 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002094 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002095
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002096 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002097 // Perform any dependent diagnostics from the pattern.
2098 PerformDependentDiagnostics(Pattern, TemplateArgs);
2099
Douglas Gregor869853e2010-11-10 19:44:59 +00002100 // Instantiate any out-of-line class template partial
2101 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002102 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002103 P = Instantiator.delayed_partial_spec_begin(),
2104 PEnd = Instantiator.delayed_partial_spec_end();
2105 P != PEnd; ++P) {
2106 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002107 P->first, P->second)) {
2108 Instantiation->setInvalidDecl();
2109 break;
2110 }
2111 }
2112
2113 // Instantiate any out-of-line variable template partial
2114 // specializations now.
2115 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2116 P = Instantiator.delayed_var_partial_spec_begin(),
2117 PEnd = Instantiator.delayed_var_partial_spec_end();
2118 P != PEnd; ++P) {
2119 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2120 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002121 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002122 break;
2123 }
2124 }
2125 }
2126
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002127 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002128 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002129
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002130 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002131 Consumer.HandleTagDeclDefinition(Instantiation);
2132
Douglas Gregor88d292c2010-05-13 16:44:06 +00002133 // Always emit the vtable for an explicit instantiation definition
2134 // of a polymorphic class template specialization.
2135 if (TSK == TSK_ExplicitInstantiationDefinition)
2136 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2137 }
2138
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002139 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002140}
2141
Richard Smith4b38ded2012-03-14 23:13:10 +00002142/// \brief Instantiate the definition of an enum from a given pattern.
2143///
2144/// \param PointOfInstantiation The point of instantiation within the
2145/// source code.
2146/// \param Instantiation is the declaration whose definition is being
2147/// instantiated. This will be a member enumeration of a class
2148/// temploid specialization, or a local enumeration within a
2149/// function temploid specialization.
2150/// \param Pattern The templated declaration from which the instantiation
2151/// occurs.
2152/// \param TemplateArgs The template arguments to be substituted into
2153/// the pattern.
2154/// \param TSK The kind of implicit or explicit instantiation to perform.
2155///
2156/// \return \c true if an error occurred, \c false otherwise.
2157bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2158 EnumDecl *Instantiation, EnumDecl *Pattern,
2159 const MultiLevelTemplateArgumentList &TemplateArgs,
2160 TemplateSpecializationKind TSK) {
2161 EnumDecl *PatternDef = Pattern->getDefinition();
2162 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2163 Instantiation->getInstantiatedFromMemberEnum(),
2164 Pattern, PatternDef, TSK,/*Complain*/true))
2165 return true;
2166 Pattern = PatternDef;
2167
2168 // Record the point of instantiation.
2169 if (MemberSpecializationInfo *MSInfo
2170 = Instantiation->getMemberSpecializationInfo()) {
2171 MSInfo->setTemplateSpecializationKind(TSK);
2172 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2173 }
2174
2175 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002176 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002177 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00002178 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2179 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002180
Richard Smitha1087602014-03-10 00:04:29 +00002181 // The instantiation is visible here, even if it was first declared in an
2182 // unimported module.
2183 Instantiation->setHidden(false);
2184
Richard Smith4b38ded2012-03-14 23:13:10 +00002185 // Enter the scope of this instantiation. We don't use
2186 // PushDeclContext because we don't have a scope.
2187 ContextRAII SavedContext(*this, Instantiation);
2188 EnterExpressionEvaluationContext EvalContext(*this,
2189 Sema::PotentiallyEvaluated);
2190
2191 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2192
2193 // Pull attributes from the pattern onto the instantiation.
2194 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2195
2196 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2197 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2198
2199 // Exit the scope of this instantiation.
2200 SavedContext.pop();
2201
2202 return Instantiation->isInvalidDecl();
2203}
2204
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002205
2206/// \brief Instantiate the definition of a field from the given pattern.
2207///
2208/// \param PointOfInstantiation The point of instantiation within the
2209/// source code.
2210/// \param Instantiation is the declaration whose definition is being
2211/// instantiated. This will be a class of a class temploid
2212/// specialization, or a local enumeration within a function temploid
2213/// specialization.
2214/// \param Pattern The templated declaration from which the instantiation
2215/// occurs.
2216/// \param TemplateArgs The template arguments to be substituted into
2217/// the pattern.
2218///
2219/// \return \c true if an error occurred, \c false otherwise.
2220bool Sema::InstantiateInClassInitializer(
2221 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2222 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2223 // If there is no initializer, we don't need to do anything.
2224 if (!Pattern->hasInClassInitializer())
2225 return false;
2226
2227 assert(Instantiation->getInClassInitStyle() ==
2228 Pattern->getInClassInitStyle() &&
2229 "pattern and instantiation disagree about init style");
2230
2231 // Error out if we haven't parsed the initializer of the pattern yet because
2232 // we are waiting for the closing brace of the outer class.
2233 Expr *OldInit = Pattern->getInClassInitializer();
2234 if (!OldInit) {
2235 RecordDecl *PatternRD = Pattern->getParent();
2236 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2237 if (OutermostClass == PatternRD) {
2238 Diag(Pattern->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
2239 << PatternRD << Pattern;
2240 } else {
2241 Diag(Pattern->getLocEnd(),
2242 diag::err_in_class_initializer_not_yet_parsed_outer_class)
2243 << PatternRD << OutermostClass << Pattern;
2244 }
2245 Instantiation->setInvalidDecl();
2246 return true;
2247 }
2248
2249 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2250 if (Inst.isInvalid())
2251 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00002252 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2253 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002254
2255 // Enter the scope of this instantiation. We don't use PushDeclContext because
2256 // we don't have a scope.
2257 ContextRAII SavedContext(*this, Instantiation->getParent());
2258 EnterExpressionEvaluationContext EvalContext(*this,
2259 Sema::PotentiallyEvaluated);
2260
Serge Pavlov907233f2015-04-28 17:58:47 +00002261 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002262
2263 // Instantiate the initializer.
2264 ActOnStartCXXInClassMemberInitializer();
2265 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2266
2267 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2268 /*CXXDirectInit=*/false);
2269 Expr *Init = NewInit.get();
2270 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2271 ActOnFinishCXXInClassMemberInitializer(
2272 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2273
2274 // Exit the scope of this instantiation.
2275 SavedContext.pop();
2276
2277 // Return true if the in-class initializer is still missing.
2278 return !Instantiation->getInClassInitializer();
2279}
2280
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002281namespace {
2282 /// \brief A partial specialization whose template arguments have matched
2283 /// a given template-id.
2284 struct PartialSpecMatchResult {
2285 ClassTemplatePartialSpecializationDecl *Partial;
2286 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002287 };
2288}
2289
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002290bool Sema::InstantiateClassTemplateSpecialization(
2291 SourceLocation PointOfInstantiation,
2292 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2293 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002294 // Perform the actual instantiation on the canonical declaration.
2295 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002296 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor00a511f2009-09-15 16:51:42 +00002297 if (ClassTemplateSpec->isInvalidDecl())
2298 return true;
2299
Douglas Gregor463421d2009-03-03 04:44:36 +00002300 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002301 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002302
Douglas Gregor170bc422009-06-12 22:31:52 +00002303 // C++ [temp.class.spec.match]p1:
2304 // When a class template is used in a context that requires an
2305 // instantiation of the class, it is necessary to determine
2306 // whether the instantiation is to be generated using the primary
2307 // template or one of the partial specializations. This is done by
2308 // matching the template arguments of the class template
2309 // specialization with the template argument lists of the partial
2310 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002311 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002312 SmallVector<MatchResult, 4> Matched;
2313 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002314 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002315 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002316 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2317 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002318 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002319 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002320 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002321 ClassTemplateSpec->getTemplateArgs(),
2322 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002323 // Store the failed-deduction information for use in diagnostics, later.
2324 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002325 FailedCandidates.addCandidate().set(
2326 DeclAccessPair::make(Template, AS_public), Partial,
2327 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002328 (void)Result;
2329 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002330 Matched.push_back(PartialSpecMatchResult());
2331 Matched.back().Partial = Partial;
2332 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002333 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002334 }
2335
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002336 // If we're dealing with a member template where the template parameters
2337 // have been instantiated, this provides the original template parameters
2338 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002339
Douglas Gregor21610382009-10-29 00:04:11 +00002340 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002341 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002342 if (Matched.size() == 1) {
2343 // -- If exactly one matching specialization is found, the
2344 // instantiation is generated from that specialization.
2345 // We don't need to do anything for this.
2346 } else {
2347 // -- If more than one matching specialization is found, the
2348 // partial order rules (14.5.4.2) are used to determine
2349 // whether one of the specializations is more specialized
2350 // than the others. If none of the specializations is more
2351 // specialized than all of the other matching
2352 // specializations, then the use of the class template is
2353 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002354 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2355 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002356 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002357 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002358 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002359 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002360 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002361 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002362
Douglas Gregor21610382009-10-29 00:04:11 +00002363 // Determine if the best partial specialization is more specialized than
2364 // the others.
2365 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002366 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2367 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002368 P != PEnd; ++P) {
2369 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002370 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002371 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002372 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002373 Ambiguous = true;
2374 break;
2375 }
2376 }
2377
2378 if (Ambiguous) {
2379 // Partial ordering did not produce a clear winner. Complain.
2380 ClassTemplateSpec->setInvalidDecl();
2381 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2382 << ClassTemplateSpec;
2383
2384 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002385 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2386 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002387 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002388 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2389 << getTemplateArgumentBindingsText(
2390 P->Partial->getTemplateParameters(),
2391 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002392
Douglas Gregor21610382009-10-29 00:04:11 +00002393 return true;
2394 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002395 }
2396
2397 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002398 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002399 while (OrigPartialSpec->getInstantiatedFromMember()) {
2400 // If we've found an explicit specialization of this class template,
2401 // stop here and use that as the pattern.
2402 if (OrigPartialSpec->isMemberSpecialization())
2403 break;
2404
2405 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2406 }
2407
2408 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002409 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002410 } else {
2411 // -- If no matches are found, the instantiation is generated
2412 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002413 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002414 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2415 // If we've found an explicit specialization of this class template,
2416 // stop here and use that as the pattern.
2417 if (OrigTemplate->isMemberSpecialization())
2418 break;
2419
Douglas Gregor01afeef2009-08-28 20:31:08 +00002420 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002421 }
2422
Douglas Gregor01afeef2009-08-28 20:31:08 +00002423 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002424 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002425
Douglas Gregoref6ab412009-10-27 06:26:26 +00002426 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2427 Pattern,
2428 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002429 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002430 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002431
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002432 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002433}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002434
John McCall76d824f2009-08-25 22:02:44 +00002435/// \brief Instantiates the definitions of all of the member
2436/// of the given class, which is an instantiation of a class template
2437/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002438void
2439Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002440 CXXRecordDecl *Instantiation,
2441 const MultiLevelTemplateArgumentList &TemplateArgs,
2442 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002443 // FIXME: We need to notify the ASTMutationListener that we did all of these
2444 // things, in case we have an explicit instantiation definition in a PCM, a
2445 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002446 assert(
2447 (TSK == TSK_ExplicitInstantiationDefinition ||
2448 TSK == TSK_ExplicitInstantiationDeclaration ||
2449 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2450 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002451 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002452 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002453 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002454 if (FunctionDecl *Pattern
2455 = Function->getInstantiatedFromMemberFunction()) {
2456 MemberSpecializationInfo *MSInfo
2457 = Function->getMemberSpecializationInfo();
2458 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002459 if (MSInfo->getTemplateSpecializationKind()
2460 == TSK_ExplicitSpecialization)
2461 continue;
2462
Douglas Gregor1d957a32009-10-27 18:42:08 +00002463 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2464 Function,
2465 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002466 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002467 SuppressNew) ||
2468 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002469 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002470
2471 // C++11 [temp.explicit]p8:
2472 // An explicit instantiation definition that names a class template
2473 // specialization explicitly instantiates the class template
2474 // specialization and is only an explicit instantiation definition
2475 // of members whose definition is visible at the point of
2476 // instantiation.
2477 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002478 continue;
2479
Richard Smitheb36ddf2014-04-24 22:45:46 +00002480 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2481
2482 if (Function->isDefined()) {
2483 // Let the ASTConsumer know that this function has been explicitly
2484 // instantiated now, and its linkage might have changed.
2485 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2486 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002487 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002488 } else if (TSK == TSK_ImplicitInstantiation) {
2489 PendingLocalImplicitInstantiations.push_back(
2490 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002491 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002492 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002493 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002494 if (isa<VarTemplateSpecializationDecl>(Var))
2495 continue;
2496
Douglas Gregor86d142a2009-10-08 07:24:58 +00002497 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002498 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2499 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002500 if (MSInfo->getTemplateSpecializationKind()
2501 == TSK_ExplicitSpecialization)
2502 continue;
2503
Douglas Gregor1d957a32009-10-27 18:42:08 +00002504 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2505 Var,
2506 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002507 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002508 SuppressNew) ||
2509 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002510 continue;
2511
Douglas Gregor1d957a32009-10-27 18:42:08 +00002512 if (TSK == TSK_ExplicitInstantiationDefinition) {
2513 // C++0x [temp.explicit]p8:
2514 // An explicit instantiation definition that names a class template
2515 // specialization explicitly instantiates the class template
2516 // specialization and is only an explicit instantiation definition
2517 // of members whose definition is visible at the point of
2518 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002519 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002520 continue;
2521
2522 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002523 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002524 } else {
2525 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2526 }
2527 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002528 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002529 // Always skip the injected-class-name, along with any
2530 // redeclarations of nested classes, since both would cause us
2531 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002532 // Skip closure types; they'll get instantiated when we instantiate
2533 // the corresponding lambda-expression.
2534 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2535 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002536 continue;
2537
Douglas Gregor1d957a32009-10-27 18:42:08 +00002538 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2539 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002540
2541 if (MSInfo->getTemplateSpecializationKind()
2542 == TSK_ExplicitSpecialization)
2543 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002544
Hans Wennborga86a83b2016-05-26 19:42:56 +00002545 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2546 TSK == TSK_ExplicitInstantiationDeclaration) {
2547 // In MSVC mode, explicit instantiation decl of the outer class doesn't
2548 // affect the inner class.
2549 continue;
2550 }
2551
Douglas Gregor1d957a32009-10-27 18:42:08 +00002552 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2553 Record,
2554 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002555 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002556 SuppressNew) ||
2557 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002558 continue;
2559
Douglas Gregor1d957a32009-10-27 18:42:08 +00002560 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2561 assert(Pattern && "Missing instantiated-from-template information");
2562
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002563 if (!Record->getDefinition()) {
2564 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002565 // C++0x [temp.explicit]p8:
2566 // An explicit instantiation definition that names a class template
2567 // specialization explicitly instantiates the class template
2568 // specialization and is only an explicit instantiation definition
2569 // of members whose definition is visible at the point of
2570 // instantiation.
2571 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2572 MSInfo->setTemplateSpecializationKind(TSK);
2573 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2574 }
2575
2576 continue;
2577 }
2578
2579 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002580 TemplateArgs,
2581 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002582 } else {
2583 if (TSK == TSK_ExplicitInstantiationDefinition &&
2584 Record->getTemplateSpecializationKind() ==
2585 TSK_ExplicitInstantiationDeclaration) {
2586 Record->setTemplateSpecializationKind(TSK);
2587 MarkVTableUsed(PointOfInstantiation, Record, true);
2588 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002589 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002590
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002591 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002592 if (Pattern)
2593 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2594 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002595 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002596 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2597 assert(MSInfo && "No member specialization information?");
2598
2599 if (MSInfo->getTemplateSpecializationKind()
2600 == TSK_ExplicitSpecialization)
2601 continue;
2602
2603 if (CheckSpecializationInstantiationRedecl(
2604 PointOfInstantiation, TSK, Enum,
2605 MSInfo->getTemplateSpecializationKind(),
2606 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2607 SuppressNew)
2608 continue;
2609
2610 if (Enum->getDefinition())
2611 continue;
2612
Richard Smith6739a102016-05-05 00:56:12 +00002613 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002614 assert(Pattern && "Missing instantiated-from-template information");
2615
2616 if (TSK == TSK_ExplicitInstantiationDefinition) {
2617 if (!Pattern->getDefinition())
2618 continue;
2619
2620 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2621 } else {
2622 MSInfo->setTemplateSpecializationKind(TSK);
2623 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2624 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002625 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2626 // No need to instantiate in-class initializers during explicit
2627 // instantiation.
2628 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2629 CXXRecordDecl *ClassPattern =
2630 Instantiation->getTemplateInstantiationPattern();
2631 DeclContext::lookup_result Lookup =
2632 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002633 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002634 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2635 TemplateArgs);
2636 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002637 }
2638 }
2639}
2640
2641/// \brief Instantiate the definitions of all of the members of the
2642/// given class template specialization, which was named as part of an
2643/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002644void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002645Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002646 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002647 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2648 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002649 // C++0x [temp.explicit]p7:
2650 // An explicit instantiation that names a class template
2651 // specialization is an explicit instantion of the same kind
2652 // (declaration or definition) of each of its members (not
2653 // including members inherited from base classes) that has not
2654 // been previously explicitly specialized in the translation unit
2655 // containing the explicit instantiation, except as described
2656 // below.
2657 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002658 getTemplateInstantiationArgs(ClassTemplateSpec),
2659 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002660}
2661
John McCalldadc5752010-08-24 06:29:42 +00002662StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002663Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002664 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002665 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002666
2667 TemplateInstantiator Instantiator(*this, TemplateArgs,
2668 SourceLocation(),
2669 DeclarationName());
2670 return Instantiator.TransformStmt(S);
2671}
2672
John McCalldadc5752010-08-24 06:29:42 +00002673ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002674Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002675 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002676 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002677
Douglas Gregora16548e2009-08-11 05:31:07 +00002678 TemplateInstantiator Instantiator(*this, TemplateArgs,
2679 SourceLocation(),
2680 DeclarationName());
2681 return Instantiator.TransformExpr(E);
2682}
2683
Richard Smithd59b8322012-12-19 01:39:02 +00002684ExprResult Sema::SubstInitializer(Expr *Init,
2685 const MultiLevelTemplateArgumentList &TemplateArgs,
2686 bool CXXDirectInit) {
2687 TemplateInstantiator Instantiator(*this, TemplateArgs,
2688 SourceLocation(),
2689 DeclarationName());
2690 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2691}
2692
Craig Topper99d23532015-12-24 23:58:29 +00002693bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002694 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002695 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002696 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002697 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002698
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002699 TemplateInstantiator Instantiator(*this, TemplateArgs,
2700 SourceLocation(),
2701 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002702 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2703 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002704}
2705
Douglas Gregor14454802011-02-25 02:25:35 +00002706NestedNameSpecifierLoc
2707Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2708 const MultiLevelTemplateArgumentList &TemplateArgs) {
2709 if (!NNS)
2710 return NestedNameSpecifierLoc();
2711
2712 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2713 DeclarationName());
2714 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2715}
2716
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002717/// \brief Do template substitution on declaration name info.
2718DeclarationNameInfo
2719Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2720 const MultiLevelTemplateArgumentList &TemplateArgs) {
2721 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2722 NameInfo.getName());
2723 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2724}
2725
Douglas Gregoraa594892009-03-31 18:38:02 +00002726TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002727Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2728 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002729 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002730 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2731 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002732 CXXScopeSpec SS;
2733 SS.Adopt(QualifierLoc);
2734 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002735}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002736
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002737bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2738 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002739 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002740 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2741 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002742
2743 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002744}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002745
Richard Smith70b13042015-01-09 01:19:56 +00002746static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002747 // When storing ParmVarDecls in the local instantiation scope, we always
2748 // want to use the ParmVarDecl from the canonical function declaration,
2749 // since the map is then valid for any redeclaration or definition of that
2750 // function.
2751 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2752 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2753 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002754 // This parameter might be from a freestanding function type within the
2755 // function and isn't necessarily referring to one of FD's parameters.
2756 if (FD->getParamDecl(i) == PV)
2757 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002758 }
2759 }
2760 return D;
2761}
2762
2763
Douglas Gregorf3010112011-01-07 16:43:16 +00002764llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2765LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002766 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002767 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002768 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002769
Douglas Gregor14cf7522010-04-30 18:55:50 +00002770 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002771 const Decl *CheckD = D;
2772 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002773 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002774 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002775 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002776
2777 // If this is a tag declaration, it's possible that we need to look for
2778 // a previous declaration.
2779 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002780 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002781 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002782 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002783 } while (CheckD);
2784
Douglas Gregor14cf7522010-04-30 18:55:50 +00002785 // If we aren't combined with our outer scope, we're done.
2786 if (!Current->CombineWithOuterScope)
2787 break;
2788 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002789
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002790 // If we're performing a partial substitution during template argument
2791 // deduction, we may not have values for template parameters yet.
2792 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2793 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002794 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002795
Serge Pavlove7ad8312015-05-15 10:10:28 +00002796 // Local types referenced prior to definition may require instantiation.
2797 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2798 if (RD->isLocalClass())
2799 return nullptr;
2800
2801 // Enumeration types referenced prior to definition may appear as a result of
2802 // error recovery.
2803 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002804 return nullptr;
2805
Chris Lattnercab02a62011-02-17 20:34:02 +00002806 // If we didn't find the decl, then we either have a sema bug, or we have a
2807 // forward reference to a label declaration. Return null to indicate that
2808 // we have an uninstantiated label.
2809 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002810 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002811}
2812
John McCall19c1bfd2010-08-25 05:32:35 +00002813void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002814 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002815 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002816 if (Stored.isNull()) {
2817#ifndef NDEBUG
2818 // It should not be present in any surrounding scope either.
2819 LocalInstantiationScope *Current = this;
2820 while (Current->CombineWithOuterScope && Current->Outer) {
2821 Current = Current->Outer;
2822 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2823 "Instantiated local in inner and outer scopes");
2824 }
2825#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002826 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002827 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002828 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002829 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002830 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002831 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002832}
Douglas Gregorf3010112011-01-07 16:43:16 +00002833
James Y Knight48fefa32015-09-30 14:04:23 +00002834void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2835 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002836 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002837 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2838 Pack->push_back(Inst);
2839}
2840
2841void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002842#ifndef NDEBUG
2843 // This should be the first time we've been told about this decl.
2844 for (LocalInstantiationScope *Current = this;
2845 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2846 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2847 "Creating local pack after instantiation of local");
2848#endif
2849
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002850 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002851 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002852 DeclArgumentPack *Pack = new DeclArgumentPack;
2853 Stored = Pack;
2854 ArgumentPacks.push_back(Pack);
2855}
2856
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002857void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2858 const TemplateArgument *ExplicitArgs,
2859 unsigned NumExplicitArgs) {
2860 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2861 "Already have a partially-substituted pack");
2862 assert((!PartiallySubstitutedPack
2863 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2864 "Wrong number of arguments in partially-substituted pack");
2865 PartiallySubstitutedPack = Pack;
2866 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2867 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2868}
2869
2870NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2871 const TemplateArgument **ExplicitArgs,
2872 unsigned *NumExplicitArgs) const {
2873 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002874 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002875 if (NumExplicitArgs)
2876 *NumExplicitArgs = 0;
2877
2878 for (const LocalInstantiationScope *Current = this; Current;
2879 Current = Current->Outer) {
2880 if (Current->PartiallySubstitutedPack) {
2881 if (ExplicitArgs)
2882 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2883 if (NumExplicitArgs)
2884 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2885
2886 return Current->PartiallySubstitutedPack;
2887 }
2888
2889 if (!Current->CombineWithOuterScope)
2890 break;
2891 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002892
2893 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002894}