blob: ed0d5a54e80d457ebde5f552c041b7e727a808d3 [file] [log] [blame]
Douglas Gregor99ebf652009-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 McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregor577f75a2009-08-04 16:50:30 +000014#include "TreeTransform.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
Faisal Valia3d311e2013-10-23 06:44:28 +000017#include "clang/AST/ASTLambda.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/Basic/LangOptions.h"
John McCall19510852010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
Richard Smith7a614d82011-06-11 17:19:42 +000022#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000023#include "clang/Sema/Lookup.h"
John McCall7cd088e2010-08-24 07:21:54 +000024#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000025#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000026
27using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000028using namespace sema;
Douglas Gregor99ebf652009-02-27 19:31:52 +000029
Douglas Gregoree1828a2009-03-10 18:03:33 +000030//===----------------------------------------------------------------------===/
31// Template Instantiation Support
32//===----------------------------------------------------------------------===/
33
Douglas Gregord6350ae2009-08-28 20:31:08 +000034/// \brief Retrieve the template argument list(s) that should be used to
35/// instantiate the definition of the given declaration.
Douglas Gregor0f8716b2009-11-09 19:17:50 +000036///
37/// \param D the declaration for which we are computing template instantiation
38/// arguments.
39///
40/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor525f96c2010-02-05 07:33:43 +000041///
42/// \param RelativeToPrimary true if we should get the template
43/// arguments relative to the primary template, even when we're
44/// dealing with a specialization. This is only relevant for function
45/// template specializations.
Douglas Gregore7089b02010-05-03 23:29:10 +000046///
47/// \param Pattern If non-NULL, indicates the pattern from which we will be
48/// instantiating the definition of the given declaration, \p D. This is
49/// used to determine the proper set of template instantiation arguments for
50/// friend function template specializations.
Douglas Gregord1102432009-08-28 17:37:35 +000051MultiLevelTemplateArgumentList
Douglas Gregor0f8716b2009-11-09 19:17:50 +000052Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor525f96c2010-02-05 07:33:43 +000053 const TemplateArgumentList *Innermost,
Douglas Gregore7089b02010-05-03 23:29:10 +000054 bool RelativeToPrimary,
55 const FunctionDecl *Pattern) {
Douglas Gregord1102432009-08-28 17:37:35 +000056 // Accumulate the set of template argument lists in this structure.
57 MultiLevelTemplateArgumentList Result;
Mike Stump1eb44332009-09-09 15:08:12 +000058
Douglas Gregor0f8716b2009-11-09 19:17:50 +000059 if (Innermost)
60 Result.addOuterTemplateArguments(Innermost);
61
Douglas Gregord1102432009-08-28 17:37:35 +000062 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregor93104c12011-05-22 00:21:10 +000063 if (!Ctx) {
Douglas Gregord1102432009-08-28 17:37:35 +000064 Ctx = D->getDeclContext();
Larisse Voufoef4579c2013-08-06 01:03:05 +000065
66 // Add template arguments from a variable template instantiation.
67 if (VarTemplateSpecializationDecl *Spec =
68 dyn_cast<VarTemplateSpecializationDecl>(D)) {
69 // We're done when we hit an explicit specialization.
70 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
71 !isa<VarTemplatePartialSpecializationDecl>(Spec))
72 return Result;
73
74 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
75
76 // If this variable template specialization was instantiated from a
77 // specialized member that is a variable template, we're done.
78 assert(Spec->getSpecializedTemplate() && "No variable template?");
Stephen Hines651f13c2014-04-23 16:59:28 -070079 llvm::PointerUnion<VarTemplateDecl*,
80 VarTemplatePartialSpecializationDecl*> Specialized
81 = Spec->getSpecializedTemplateOrPartial();
82 if (VarTemplatePartialSpecializationDecl *Partial =
83 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
84 if (Partial->isMemberSpecialization())
85 return Result;
86 } else {
87 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
88 if (Tmpl->isMemberSpecialization())
89 return Result;
90 }
Larisse Voufoef4579c2013-08-06 01:03:05 +000091 }
92
Douglas Gregor383041d2011-06-15 14:20:42 +000093 // If we have a template template parameter with translation unit context,
94 // then we're performing substitution into a default template argument of
95 // this template template parameter before we've constructed the template
96 // that will own this template template parameter. In this case, we
97 // use empty template parameter lists for all of the outer templates
98 // to avoid performing any substitutions.
99 if (Ctx->isTranslationUnit()) {
100 if (TemplateTemplateParmDecl *TTP
101 = dyn_cast<TemplateTemplateParmDecl>(D)) {
102 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith7a9f7c72013-05-17 03:04:50 +0000103 Result.addOuterTemplateArguments(None);
Douglas Gregor383041d2011-06-15 14:20:42 +0000104 return Result;
105 }
106 }
Douglas Gregor93104c12011-05-22 00:21:10 +0000107 }
108
John McCallf181d8a2009-08-29 03:16:09 +0000109 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +0000110 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +0000111 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +0000112 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
113 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +0000114 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
115 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +0000116 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Douglas Gregord1102432009-08-28 17:37:35 +0000118 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000119
120 // If this class template specialization was instantiated from a
121 // specialized member that is a class template, we're done.
122 assert(Spec->getSpecializedTemplate() && "No class template?");
123 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
124 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000125 }
Douglas Gregord1102432009-08-28 17:37:35 +0000126 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +0000127 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000128 if (!RelativeToPrimary &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000129 (Function->getTemplateSpecializationKind() ==
130 TSK_ExplicitSpecialization &&
131 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000132 break;
133
Douglas Gregord1102432009-08-28 17:37:35 +0000134 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000135 = Function->getTemplateSpecializationArgs()) {
136 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000137 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000138
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000139 // If this function was instantiated from a specialized member that is
140 // a function template, we're done.
141 assert(Function->getPrimaryTemplate() && "No function template?");
142 if (Function->getPrimaryTemplate()->isMemberSpecialization())
143 break;
Faisal Valia3d311e2013-10-23 06:44:28 +0000144
145 // If this function is a generic lambda specialization, we are done.
146 if (isGenericLambdaCallOperatorSpecialization(Function))
147 break;
148
Douglas Gregorc494f772011-03-05 17:54:25 +0000149 } else if (FunctionTemplateDecl *FunTmpl
150 = Function->getDescribedFunctionTemplate()) {
151 // Add the "injected" template arguments.
Richard Smith7a9f7c72013-05-17 03:04:50 +0000152 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000153 }
154
John McCallf181d8a2009-08-29 03:16:09 +0000155 // If this is a friend declaration and it declares an entity at
156 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000157 // instead of its semantic parent, unless of course the pattern we're
158 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000159 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000160 Function->getDeclContext()->isFileContext() &&
161 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000162 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000163 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000164 continue;
165 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000166 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
167 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
168 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith7a9f7c72013-05-17 03:04:50 +0000169 const TemplateSpecializationType *TST =
170 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
171 Result.addOuterTemplateArguments(
172 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor24bae922010-07-08 18:37:38 +0000173 if (ClassTemplate->isMemberSpecialization())
174 break;
175 }
Douglas Gregord1102432009-08-28 17:37:35 +0000176 }
John McCallf181d8a2009-08-29 03:16:09 +0000177
178 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000179 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000180 }
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Douglas Gregord1102432009-08-28 17:37:35 +0000182 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000183}
184
Douglas Gregorf35f8282009-11-11 21:54:23 +0000185bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
186 switch (Kind) {
187 case TemplateInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000188 case ExceptionSpecInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000189 case DefaultTemplateArgumentInstantiation:
190 case DefaultFunctionArgumentInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000191 case ExplicitTemplateArgumentSubstitution:
192 case DeducedTemplateArgumentSubstitution:
193 case PriorTemplateArgumentSubstitution:
Richard Smithab91ef12012-07-08 02:38:24 +0000194 return true;
195
Douglas Gregorf35f8282009-11-11 21:54:23 +0000196 case DefaultTemplateArgumentChecking:
197 return false;
198 }
David Blaikie7530c032012-01-17 06:56:22 +0000199
200 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000201}
202
Stephen Hines651f13c2014-04-23 16:59:28 -0700203void Sema::InstantiatingTemplate::Initialize(
204 ActiveTemplateInstantiation::InstantiationKind Kind,
205 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
206 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
207 sema::TemplateDeductionInfo *DeductionInfo) {
208 SavedInNonInstantiationSFINAEContext =
209 SemaRef.InNonInstantiationSFINAEContext;
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700210 // Don't allow further instantiation if a fatal error has occcured. Any
211 // diagnostics we might have raised will not be visible.
212 if (SemaRef.Diags.hasFatalErrorOccurred()) {
213 Invalid = true;
214 return;
215 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700216 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
217 if (!Invalid) {
218 ActiveTemplateInstantiation Inst;
219 Inst.Kind = Kind;
220 Inst.PointOfInstantiation = PointOfInstantiation;
221 Inst.Entity = Entity;
222 Inst.Template = Template;
223 Inst.TemplateArgs = TemplateArgs.data();
224 Inst.NumTemplateArgs = TemplateArgs.size();
225 Inst.DeductionInfo = DeductionInfo;
226 Inst.InstantiationRange = InstantiationRange;
227 SemaRef.InNonInstantiationSFINAEContext = false;
228 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
229 if (!Inst.isInstantiationRecord())
230 ++SemaRef.NonInstantiationEntries;
231 }
232}
233
Douglas Gregor26dce442009-03-10 00:06:19 +0000234Sema::InstantiatingTemplate::
235InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000236 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000237 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700238 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000239{
Stephen Hines651f13c2014-04-23 16:59:28 -0700240 Initialize(ActiveTemplateInstantiation::TemplateInstantiation,
241 PointOfInstantiation, InstantiationRange, Entity);
Douglas Gregordf667e72009-03-10 20:44:00 +0000242}
243
Richard Smithe6975e92012-04-17 00:58:00 +0000244Sema::InstantiatingTemplate::
245InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
246 FunctionDecl *Entity, ExceptionSpecification,
247 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700248 : SemaRef(SemaRef)
Richard Smithe6975e92012-04-17 00:58:00 +0000249{
Stephen Hines651f13c2014-04-23 16:59:28 -0700250 Initialize(ActiveTemplateInstantiation::ExceptionSpecInstantiation,
251 PointOfInstantiation, InstantiationRange, Entity);
Richard Smithe6975e92012-04-17 00:58:00 +0000252}
253
Richard Smith7e54fb52012-07-16 01:09:10 +0000254Sema::InstantiatingTemplate::
255InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
256 TemplateDecl *Template,
257 ArrayRef<TemplateArgument> TemplateArgs,
258 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700259 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000260{
Stephen Hines651f13c2014-04-23 16:59:28 -0700261 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
262 PointOfInstantiation, InstantiationRange,
263 Template, nullptr, TemplateArgs);
Douglas Gregor26dce442009-03-10 00:06:19 +0000264}
265
Richard Smith7e54fb52012-07-16 01:09:10 +0000266Sema::InstantiatingTemplate::
267InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
268 FunctionTemplateDecl *FunctionTemplate,
269 ArrayRef<TemplateArgument> TemplateArgs,
270 ActiveTemplateInstantiation::InstantiationKind Kind,
271 sema::TemplateDeductionInfo &DeductionInfo,
272 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700273 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000274{
Stephen Hines651f13c2014-04-23 16:59:28 -0700275 Initialize(Kind, PointOfInstantiation, InstantiationRange,
276 FunctionTemplate, nullptr, TemplateArgs, &DeductionInfo);
Douglas Gregorcca9e962009-07-01 22:01:06 +0000277}
278
Richard Smith7e54fb52012-07-16 01:09:10 +0000279Sema::InstantiatingTemplate::
280InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
281 ClassTemplatePartialSpecializationDecl *PartialSpec,
282 ArrayRef<TemplateArgument> TemplateArgs,
283 sema::TemplateDeductionInfo &DeductionInfo,
284 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700285 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000286{
Stephen Hines651f13c2014-04-23 16:59:28 -0700287 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
288 PointOfInstantiation, InstantiationRange,
289 PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
Douglas Gregor637a4092009-06-10 23:47:09 +0000290}
291
Larisse Voufoef4579c2013-08-06 01:03:05 +0000292Sema::InstantiatingTemplate::InstantiatingTemplate(
293 Sema &SemaRef, SourceLocation PointOfInstantiation,
294 VarTemplatePartialSpecializationDecl *PartialSpec,
295 ArrayRef<TemplateArgument> TemplateArgs,
296 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700297 : SemaRef(SemaRef)
298{
299 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
300 PointOfInstantiation, InstantiationRange,
301 PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000302}
303
Richard Smith7e54fb52012-07-16 01:09:10 +0000304Sema::InstantiatingTemplate::
305InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
306 ParmVarDecl *Param,
307 ArrayRef<TemplateArgument> TemplateArgs,
308 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700309 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000310{
Stephen Hines651f13c2014-04-23 16:59:28 -0700311 Initialize(ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
312 PointOfInstantiation, InstantiationRange,
313 Param, nullptr, TemplateArgs);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000314}
315
Stephen Hines651f13c2014-04-23 16:59:28 -0700316
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000317Sema::InstantiatingTemplate::
318InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000319 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
320 ArrayRef<TemplateArgument> TemplateArgs,
321 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700322 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000323{
Stephen Hines651f13c2014-04-23 16:59:28 -0700324 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
325 PointOfInstantiation, InstantiationRange,
326 Param, Template, TemplateArgs);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000327}
328
329Sema::InstantiatingTemplate::
330InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000331 NamedDecl *Template, TemplateTemplateParmDecl *Param,
332 ArrayRef<TemplateArgument> TemplateArgs,
333 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700334 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000335{
Stephen Hines651f13c2014-04-23 16:59:28 -0700336 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
337 PointOfInstantiation, InstantiationRange,
338 Param, Template, TemplateArgs);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000339}
340
341Sema::InstantiatingTemplate::
342InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000343 TemplateDecl *Template, NamedDecl *Param,
344 ArrayRef<TemplateArgument> TemplateArgs,
345 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700346 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000347{
Stephen Hines651f13c2014-04-23 16:59:28 -0700348 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
349 PointOfInstantiation, InstantiationRange,
350 Param, Template, TemplateArgs);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000351}
352
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000353void Sema::InstantiatingTemplate::Clear() {
354 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000355 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
356 assert(SemaRef.NonInstantiationEntries > 0);
357 --SemaRef.NonInstantiationEntries;
358 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000359 SemaRef.InNonInstantiationSFINAEContext
360 = SavedInNonInstantiationSFINAEContext;
Richard Smithb7751002013-07-25 23:08:39 +0000361
362 // Name lookup no longer looks in this template's defining module.
363 assert(SemaRef.ActiveTemplateInstantiations.size() >=
364 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
365 "forgot to remove a lookup module for a template instantiation");
366 if (SemaRef.ActiveTemplateInstantiations.size() ==
367 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
368 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
369 SemaRef.LookupModulesCache.erase(M);
370 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
371 }
372
Douglas Gregor26dce442009-03-10 00:06:19 +0000373 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000374 Invalid = true;
375 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000376}
377
Douglas Gregordf667e72009-03-10 20:44:00 +0000378bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
379 SourceLocation PointOfInstantiation,
380 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000381 assert(SemaRef.NonInstantiationEntries <=
382 SemaRef.ActiveTemplateInstantiations.size());
383 if ((SemaRef.ActiveTemplateInstantiations.size() -
384 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000385 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000386 return false;
387
Mike Stump1eb44332009-09-09 15:08:12 +0000388 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000389 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000390 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000391 << InstantiationRange;
392 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000393 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000394 return true;
395}
396
Douglas Gregoree1828a2009-03-10 18:03:33 +0000397/// \brief Prints the current instantiation stack through a series of
398/// notes.
399void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000400 // Determine which template instantiations to skip, if any.
401 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
402 unsigned Limit = Diags.getTemplateBacktraceLimit();
403 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
404 SkipStart = Limit / 2 + Limit % 2;
405 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
406 }
407
Douglas Gregorcca9e962009-07-01 22:01:06 +0000408 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000409 unsigned InstantiationIdx = 0;
Craig Topper09d19ef2013-07-04 03:08:24 +0000410 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000411 Active = ActiveTemplateInstantiations.rbegin(),
412 ActiveEnd = ActiveTemplateInstantiations.rend();
413 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000414 ++Active, ++InstantiationIdx) {
415 // Skip this instantiation?
416 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
417 if (InstantiationIdx == SkipStart) {
418 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000419 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000420 diag::note_instantiation_contexts_suppressed)
421 << unsigned(ActiveTemplateInstantiations.size() - Limit);
422 }
423 continue;
424 }
425
Douglas Gregordf667e72009-03-10 20:44:00 +0000426 switch (Active->Kind) {
427 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000428 Decl *D = Active->Entity;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000429 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
430 unsigned DiagID = diag::note_template_member_class_here;
431 if (isa<ClassTemplateSpecializationDecl>(Record))
432 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000433 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000434 << Context.getTypeDeclType(Record)
435 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000436 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000437 unsigned DiagID;
438 if (Function->getPrimaryTemplate())
439 DiagID = diag::note_function_template_spec_here;
440 else
441 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000442 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000443 << Function
444 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000445 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000446 Diags.Report(Active->PointOfInstantiation,
Larisse Voufo933c66b2013-08-14 20:15:02 +0000447 VD->isStaticDataMember()?
448 diag::note_template_static_data_member_def_here
449 : diag::note_template_variable_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000450 << VD
451 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000452 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
453 Diags.Report(Active->PointOfInstantiation,
454 diag::note_template_enum_def_here)
455 << ED
456 << Active->InstantiationRange;
Stephen Hines176edba2014-12-01 14:53:08 -0800457 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
458 Diags.Report(Active->PointOfInstantiation,
459 diag::note_template_nsdmi_here)
460 << FD << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000461 } else {
462 Diags.Report(Active->PointOfInstantiation,
463 diag::note_template_type_alias_instantiation_here)
464 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000465 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000466 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000467 break;
468 }
469
470 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000471 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000472 SmallVector<char, 128> TemplateArgsStr;
473 llvm::raw_svector_ostream OS(TemplateArgsStr);
474 Template->printName(OS);
475 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000476 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000477 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000478 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000479 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000480 diag::note_default_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000481 << OS.str()
Douglas Gregordf667e72009-03-10 20:44:00 +0000482 << Active->InstantiationRange;
483 break;
484 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000485
Douglas Gregorcca9e962009-07-01 22:01:06 +0000486 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000487 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000488 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000489 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000490 << FnTmpl
491 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
492 Active->TemplateArgs,
493 Active->NumTemplateArgs)
494 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000495 break;
496 }
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Douglas Gregorcca9e962009-07-01 22:01:06 +0000498 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000499 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
500 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000501 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000502 diag::note_partial_spec_deduct_instantiation_here)
503 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000504 << getTemplateArgumentBindingsText(
505 PartialSpec->getTemplateParameters(),
506 Active->TemplateArgs,
507 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000508 << Active->InstantiationRange;
509 } else {
510 FunctionTemplateDecl *FnTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000511 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000512 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000513 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000514 << FnTmpl
515 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
516 Active->TemplateArgs,
517 Active->NumTemplateArgs)
518 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000519 }
520 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000521
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000522 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000523 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000524 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Benjamin Kramer5eada842013-02-22 15:46:01 +0000526 SmallVector<char, 128> TemplateArgsStr;
527 llvm::raw_svector_ostream OS(TemplateArgsStr);
528 FD->printName(OS);
529 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000530 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000531 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000532 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000533 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000534 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000535 << OS.str()
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000536 << Active->InstantiationRange;
537 break;
538 }
Mike Stump1eb44332009-09-09 15:08:12 +0000539
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000540 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000541 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000542 std::string Name;
543 if (!Parm->getName().empty())
544 Name = std::string(" '") + Parm->getName().str() + "'";
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700545
546 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000547 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
548 TemplateParams = Template->getTemplateParameters();
549 else
550 TemplateParams =
551 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
552 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000553 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000554 diag::note_prior_template_arg_substitution)
555 << isa<TemplateTemplateParmDecl>(Parm)
556 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000557 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000558 Active->TemplateArgs,
559 Active->NumTemplateArgs)
560 << Active->InstantiationRange;
561 break;
562 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000563
564 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700565 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000566 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
567 TemplateParams = Template->getTemplateParameters();
568 else
569 TemplateParams =
570 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
571 ->getTemplateParameters();
572
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000573 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000574 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000575 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000576 Active->TemplateArgs,
577 Active->NumTemplateArgs)
578 << Active->InstantiationRange;
579 break;
580 }
Richard Smithe6975e92012-04-17 00:58:00 +0000581
582 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
583 Diags.Report(Active->PointOfInstantiation,
584 diag::note_template_exception_spec_instantiation_here)
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000585 << cast<FunctionDecl>(Active->Entity)
Richard Smithe6975e92012-04-17 00:58:00 +0000586 << Active->InstantiationRange;
587 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000588 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000589 }
590}
591
David Blaikiedc84cd52013-02-20 22:23:23 +0000592Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000593 if (InNonInstantiationSFINAEContext)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700594 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000595
Craig Topper09d19ef2013-07-04 03:08:24 +0000596 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000597 Active = ActiveTemplateInstantiations.rbegin(),
598 ActiveEnd = ActiveTemplateInstantiations.rend();
599 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000600 ++Active)
601 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000602 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000603 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000604 // An instantiation of an alias template may or may not be a SFINAE
605 // context, depending on what else is on the stack.
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000606 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smitha43ea642012-04-26 07:24:08 +0000607 break;
608 // Fall through.
609 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000610 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000611 // This is a template instantiation, so there is no SFINAE.
David Blaikie66874fb2013-02-21 01:47:18 +0000612 return None;
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000614 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000615 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000616 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000617 // A default template argument instantiation and substitution into
618 // template parameters with arguments for prior parameters may or may
619 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000620 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Douglas Gregorcca9e962009-07-01 22:01:06 +0000622 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
623 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
624 // We're either substitution explicitly-specified template arguments
625 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000626 assert(Active->DeductionInfo && "Missing deduction info pointer");
627 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000628 }
629 }
630
David Blaikie66874fb2013-02-21 01:47:18 +0000631 return None;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000632}
633
Douglas Gregord3731192011-01-10 07:32:04 +0000634/// \brief Retrieve the depth and index of a parameter pack.
635static std::pair<unsigned, unsigned>
636getDepthAndIndex(NamedDecl *ND) {
637 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
638 return std::make_pair(TTP->getDepth(), TTP->getIndex());
639
640 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
641 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
642
643 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
644 return std::make_pair(TTP->getDepth(), TTP->getIndex());
645}
646
Douglas Gregor99ebf652009-02-27 19:31:52 +0000647//===----------------------------------------------------------------------===/
648// Template Instantiation for Types
649//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000650namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000651 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000652 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000653 SourceLocation Loc;
654 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000655
Douglas Gregorcd281c32009-02-28 00:25:32 +0000656 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000657 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000658
659 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000660 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000661 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000662 DeclarationName Entity)
663 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000664 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000665
Mike Stump1eb44332009-09-09 15:08:12 +0000666 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000667 /// transformed.
668 ///
669 /// For the purposes of template instantiation, a type has already been
670 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000671 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Douglas Gregor577f75a2009-08-04 16:50:30 +0000673 /// \brief Returns the location of the entity being instantiated, if known.
674 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000675
Douglas Gregor577f75a2009-08-04 16:50:30 +0000676 /// \brief Returns the name of the entity being instantiated, if any.
677 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000679 /// \brief Sets the "base" location and entity when that
680 /// information is known based on another transformation.
681 void setBase(SourceLocation Loc, DeclarationName Entity) {
682 this->Loc = Loc;
683 this->Entity = Entity;
684 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000685
686 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
687 SourceRange PatternRange,
Robert Wilhelm834c0582013-08-09 18:02:13 +0000688 ArrayRef<UnexpandedParameterPack> Unexpanded,
689 bool &ShouldExpand, bool &RetainExpansion,
David Blaikiedc84cd52013-02-20 22:23:23 +0000690 Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000691 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
692 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000693 TemplateArgs,
694 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000695 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000696 NumExpansions);
697 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000698
Douglas Gregor12c9c002011-01-07 16:43:16 +0000699 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
700 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
701 }
702
Douglas Gregord3731192011-01-10 07:32:04 +0000703 TemplateArgument ForgetPartiallySubstitutedPack() {
704 TemplateArgument Result;
705 if (NamedDecl *PartialPack
706 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
707 MultiLevelTemplateArgumentList &TemplateArgs
708 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
709 unsigned Depth, Index;
Stephen Hines651f13c2014-04-23 16:59:28 -0700710 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregord3731192011-01-10 07:32:04 +0000711 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
712 Result = TemplateArgs(Depth, Index);
713 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
714 }
715 }
716
717 return Result;
718 }
719
720 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
721 if (Arg.isNull())
722 return;
723
724 if (NamedDecl *PartialPack
725 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
726 MultiLevelTemplateArgumentList &TemplateArgs
727 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
728 unsigned Depth, Index;
Stephen Hines651f13c2014-04-23 16:59:28 -0700729 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregord3731192011-01-10 07:32:04 +0000730 TemplateArgs.setArgument(Depth, Index, Arg);
731 }
732 }
733
Douglas Gregor577f75a2009-08-04 16:50:30 +0000734 /// \brief Transform the given declaration by instantiating a reference to
735 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000736 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000737
Douglas Gregordfca6f52012-02-13 22:00:16 +0000738 void transformAttrs(Decl *Old, Decl *New) {
739 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
740 }
741
742 void transformedLocalDecl(Decl *Old, Decl *New) {
743 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
744 }
745
Mike Stump1eb44332009-09-09 15:08:12 +0000746 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000747 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000748 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000750 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000751 /// declaration.
752 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
753
Douglas Gregor43959a92009-08-20 07:17:43 +0000754 /// \brief Rebuild the exception declaration and register the declaration
755 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000756 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000757 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000758 SourceLocation StartLoc,
759 SourceLocation NameLoc,
760 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Douglas Gregorbe270a02010-04-26 17:57:08 +0000762 /// \brief Rebuild the Objective-C exception declaration and register the
763 /// declaration as an instantiated local.
764 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
765 TypeSourceInfo *TSInfo, QualType T);
766
John McCallc4e70192009-09-11 04:59:25 +0000767 /// \brief Check for tag mismatches when instantiating an
768 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000769 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
770 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000771 NestedNameSpecifierLoc QualifierLoc,
772 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000773
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700774 TemplateName
775 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
776 SourceLocation NameLoc,
777 QualType ObjectType = QualType(),
778 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000779
Stephen Hines176edba2014-12-01 14:53:08 -0800780 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
781
John McCall60d7b3a2010-08-24 06:29:42 +0000782 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
783 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
784 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000785
John McCall60d7b3a2010-08-24 06:29:42 +0000786 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000787 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000788 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
789 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000790
791 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
792 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
793
794 /// \brief Transform a reference to a function parameter pack.
795 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
796 ParmVarDecl *PD);
797
798 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
799 /// expand a function parameter pack reference which refers to an expanded
800 /// pack.
801 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
802
Douglas Gregor895162d2010-04-30 18:55:50 +0000803 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Stephen Hines176edba2014-12-01 14:53:08 -0800804 FunctionProtoTypeLoc TL) {
805 // Call the base version; it will forward to our overridden version below.
806 return inherited::TransformFunctionProtoType(TLB, TL);
807 }
808
809 template<typename Fn>
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000810 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
811 FunctionProtoTypeLoc TL,
812 CXXRecordDecl *ThisContext,
Stephen Hines176edba2014-12-01 14:53:08 -0800813 unsigned ThisTypeQuals,
814 Fn TransformExceptionSpec);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000815
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000816 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000817 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +0000818 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000819 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000820
Mike Stump1eb44332009-09-09 15:08:12 +0000821 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000822 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000823 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000824 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000825
Douglas Gregorc3069d62011-01-14 02:55:32 +0000826 /// \brief Transforms an already-substituted template type parameter pack
827 /// into either itself (if we aren't substituting into its pack expansion)
828 /// or the appropriate substituted argument.
829 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
830 SubstTemplateTypeParmPackTypeLoc TL);
831
John McCall60d7b3a2010-08-24 06:29:42 +0000832 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000833 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000834 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000835 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
836 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000837 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000838 }
John McCall91a57552011-07-15 05:09:51 +0000839
Richard Smith612409e2012-07-25 03:56:55 +0000840 ExprResult TransformLambdaExpr(LambdaExpr *E) {
841 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
842 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
843 }
844
845 ExprResult TransformLambdaScope(LambdaExpr *E,
Bill Wendling2434dcf2013-12-05 05:25:04 +0000846 CXXMethodDecl *NewCallOperator,
847 ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) {
Faisal Valia3d311e2013-10-23 06:44:28 +0000848 CXXMethodDecl *const OldCallOperator = E->getCallOperator();
849 // In the generic lambda case, we set the NewTemplate to be considered
850 // an "instantiation" of the OldTemplate.
851 if (FunctionTemplateDecl *const NewCallOperatorTemplate =
852 NewCallOperator->getDescribedFunctionTemplate()) {
853
854 FunctionTemplateDecl *const OldCallOperatorTemplate =
855 OldCallOperator->getDescribedFunctionTemplate();
856 NewCallOperatorTemplate->setInstantiatedFromMemberTemplate(
857 OldCallOperatorTemplate);
Faisal Valia3d311e2013-10-23 06:44:28 +0000858 } else
859 // For a non-generic lambda we set the NewCallOperator to
860 // be an instantiation of the OldCallOperator.
861 NewCallOperator->setInstantiationOfMemberFunction(OldCallOperator,
862 TSK_ImplicitInstantiation);
863
Bill Wendling2434dcf2013-12-05 05:25:04 +0000864 return inherited::TransformLambdaScope(E, NewCallOperator,
865 InitCaptureExprsAndTypes);
Rafael Espindolaf003acd2013-10-04 14:28:51 +0000866 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700867 TemplateParameterList *TransformTemplateParameterList(
Faisal Valia3d311e2013-10-23 06:44:28 +0000868 TemplateParameterList *OrigTPL) {
869 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
870
871 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
872 TemplateDeclInstantiator DeclInstantiator(getSema(),
873 /* DeclContext *Owner */ Owner, TemplateArgs);
874 return DeclInstantiator.SubstTemplateParams(OrigTPL);
875 }
John McCall91a57552011-07-15 05:09:51 +0000876 private:
877 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
878 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000879 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000880 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000881}
882
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000883bool TemplateInstantiator::AlreadyTransformed(QualType T) {
884 if (T.isNull())
885 return true;
886
Douglas Gregor561f8122011-07-01 01:22:09 +0000887 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000888 return false;
889
890 getSema().MarkDeclarationsReferencedInType(Loc, T);
891 return true;
892}
893
Eli Friedman10ec0e42013-07-19 19:40:38 +0000894static TemplateArgument
895getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
896 assert(S.ArgumentPackSubstitutionIndex >= 0);
897 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
898 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
899 if (Arg.isPackExpansion())
900 Arg = Arg.getPackExpansionPattern();
901 return Arg;
902}
903
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000904Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000905 if (!D)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700906 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000907
Douglas Gregorc68afe22009-09-03 21:38:09 +0000908 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000909 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000910 // If the corresponding template argument is NULL or non-existent, it's
911 // because we are performing instantiation from explicitly-specified
912 // template arguments in a function template, but there were some
913 // arguments left unspecified.
914 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
915 TTP->getPosition()))
916 return D;
917
Douglas Gregor61c4d282011-01-05 15:48:55 +0000918 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
919
920 if (TTP->isParameterPack()) {
921 assert(Arg.getKind() == TemplateArgument::Pack &&
922 "Missing argument pack");
Eli Friedman10ec0e42013-07-19 19:40:38 +0000923 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000924 }
925
926 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000927 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000928 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000929 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000930 }
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Douglas Gregor788cd062009-11-11 01:00:40 +0000932 // Fall through to find the instantiated declaration for this template
933 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000936 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000937}
938
Douglas Gregoraac571c2010-03-01 17:25:41 +0000939Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000940 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000941 if (!Inst)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700942 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Douglas Gregor43959a92009-08-20 07:17:43 +0000944 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
945 return Inst;
946}
947
Douglas Gregor6cd21982009-10-20 05:58:46 +0000948NamedDecl *
949TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
950 SourceLocation Loc) {
951 // If the first part of the nested-name-specifier was a template type
952 // parameter, instantiate that type parameter down to a tag type.
953 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
954 const TemplateTypeParmType *TTP
955 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000956
Douglas Gregor6cd21982009-10-20 05:58:46 +0000957 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000958 // FIXME: This needs testing w/ member access expressions.
959 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
960
961 if (TTP->isParameterPack()) {
962 assert(Arg.getKind() == TemplateArgument::Pack &&
963 "Missing argument pack");
964
Douglas Gregor2be29f42011-01-14 23:41:42 +0000965 if (getSema().ArgumentPackSubstitutionIndex == -1)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700966 return nullptr;
967
Eli Friedman10ec0e42013-07-19 19:40:38 +0000968 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor984a58b2010-12-20 22:48:17 +0000969 }
970
971 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000972 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000973 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000974
975 if (const TagType *Tag = T->getAs<TagType>())
976 return Tag->getDecl();
977
978 // The resulting type is not a tag; complain.
979 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700980 return nullptr;
Douglas Gregor6cd21982009-10-20 05:58:46 +0000981 }
982 }
983
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000984 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000985}
986
Douglas Gregor43959a92009-08-20 07:17:43 +0000987VarDecl *
988TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000989 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000990 SourceLocation StartLoc,
991 SourceLocation NameLoc,
992 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000993 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000994 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000995 if (Var)
996 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
997 return Var;
998}
999
1000VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1001 TypeSourceInfo *TSInfo,
1002 QualType T) {
1003 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1004 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +00001005 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1006 return Var;
1007}
1008
John McCallc4e70192009-09-11 04:59:25 +00001009QualType
John McCall21e413f2010-11-04 19:04:38 +00001010TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1011 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001012 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001013 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +00001014 if (const TagType *TT = T->getAs<TagType>()) {
1015 TagDecl* TD = TT->getDecl();
1016
John McCall21e413f2010-11-04 19:04:38 +00001017 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001018
John McCallc4e70192009-09-11 04:59:25 +00001019 IdentifierInfo *Id = TD->getIdentifier();
1020
1021 // TODO: should we even warn on struct/class mismatches for this? Seems
1022 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001023 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001024 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001025 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1026 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001027 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1028 << Id
1029 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1030 TD->getKindName());
1031 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1032 }
John McCallc4e70192009-09-11 04:59:25 +00001033 }
1034 }
1035
John McCall21e413f2010-11-04 19:04:38 +00001036 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1037 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001038 QualifierLoc,
1039 T);
John McCallc4e70192009-09-11 04:59:25 +00001040}
1041
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001042TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1043 TemplateName Name,
Stephen Hines176edba2014-12-01 14:53:08 -08001044 SourceLocation NameLoc,
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001045 QualType ObjectType,
1046 NamedDecl *FirstQualifierInScope) {
1047 if (TemplateTemplateParmDecl *TTP
1048 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1049 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1050 // If the corresponding template argument is NULL or non-existent, it's
1051 // because we are performing instantiation from explicitly-specified
1052 // template arguments in a function template, but there were some
1053 // arguments left unspecified.
1054 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1055 TTP->getPosition()))
1056 return Name;
1057
1058 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1059
1060 if (TTP->isParameterPack()) {
1061 assert(Arg.getKind() == TemplateArgument::Pack &&
1062 "Missing argument pack");
1063
1064 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1065 // We have the template argument pack to substitute, but we're not
1066 // actually expanding the enclosing pack expansion yet. So, just
1067 // keep the entire argument pack.
1068 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1069 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001070
1071 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001072 }
1073
1074 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001075 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001076
Douglas Gregor58750382011-03-05 20:06:51 +00001077 // We don't ever want to substitute for a qualified template name, since
1078 // the qualifier is handled separately. So, look through the qualified
1079 // template name to its underlying declaration.
1080 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1081 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001082
1083 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001084 return Template;
1085 }
1086 }
1087
1088 if (SubstTemplateTemplateParmPackStorage *SubstPack
1089 = Name.getAsSubstTemplateTemplateParmPack()) {
1090 if (getSema().ArgumentPackSubstitutionIndex == -1)
1091 return Name;
1092
Eli Friedman10ec0e42013-07-19 19:40:38 +00001093 TemplateArgument Arg = SubstPack->getArgumentPack();
1094 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1095 return Arg.getAsTemplate();
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001096 }
1097
1098 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1099 FirstQualifierInScope);
1100}
1101
John McCall60d7b3a2010-08-24 06:29:42 +00001102ExprResult
John McCall454feb92009-12-08 09:21:05 +00001103TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001104 if (!E->isTypeDependent())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001105 return E;
Anders Carlsson773f3972009-09-11 01:22:35 +00001106
Wei Pan33129332013-09-16 13:57:27 +00001107 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson773f3972009-09-11 01:22:35 +00001108}
1109
John McCall60d7b3a2010-08-24 06:29:42 +00001110ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001111TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001112 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001113 // If the corresponding template argument is NULL or non-existent, it's
1114 // because we are performing instantiation from explicitly-specified
1115 // template arguments in a function template, but there were some
1116 // arguments left unspecified.
1117 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1118 NTTP->getPosition()))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001119 return E;
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Douglas Gregor56bc9832010-12-24 00:15:10 +00001121 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1122 if (NTTP->isParameterPack()) {
1123 assert(Arg.getKind() == TemplateArgument::Pack &&
1124 "Missing argument pack");
1125
1126 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001127 // We have an argument pack, but we can't select a particular argument
1128 // out of it yet. Therefore, we'll build an expression to hold on to that
1129 // argument pack.
1130 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1131 E->getLocation(),
1132 NTTP->getDeclName());
1133 if (TargetType.isNull())
1134 return ExprError();
1135
1136 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1137 NTTP,
1138 E->getLocation(),
1139 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001140 }
1141
Eli Friedman10ec0e42013-07-19 19:40:38 +00001142 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001143 }
Mike Stump1eb44332009-09-09 15:08:12 +00001144
John McCall91a57552011-07-15 05:09:51 +00001145 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1146}
1147
Stephen Hines176edba2014-12-01 14:53:08 -08001148const LoopHintAttr *
1149TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1150 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1151
1152 if (TransformedExpr == LH->getValue())
1153 return LH;
1154
1155 // Generate error if there is a problem with the value.
1156 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1157 return LH;
1158
1159 // Create new LoopHintValueAttr with integral expression in place of the
1160 // non-type template parameter.
1161 return LoopHintAttr::CreateImplicit(
1162 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1163 LH->getState(), TransformedExpr, LH->getRange());
1164}
1165
John McCall91a57552011-07-15 05:09:51 +00001166ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1167 NonTypeTemplateParmDecl *parm,
1168 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001169 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001170 ExprResult result;
1171 QualType type;
1172
John McCallb8fc0532010-02-06 08:42:39 +00001173 // The template argument itself might be an expression, in which
1174 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001175 if (arg.getKind() == TemplateArgument::Expression) {
1176 Expr *argExpr = arg.getAsExpr();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001177 result = argExpr;
John McCall91a57552011-07-15 05:09:51 +00001178 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Eli Friedmand7a6b162012-09-26 02:36:12 +00001180 } else if (arg.getKind() == TemplateArgument::Declaration ||
1181 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001182 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001183 if (arg.getKind() == TemplateArgument::Declaration) {
1184 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001185
Douglas Gregord2008e22012-04-06 22:40:38 +00001186 // Find the instantiation of the template argument. This is
1187 // required for nested templates.
1188 VD = cast_or_null<ValueDecl>(
1189 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1190 if (!VD)
1191 return ExprError();
1192 } else {
1193 // Propagate NULL template argument.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001194 VD = nullptr;
Douglas Gregord2008e22012-04-06 22:40:38 +00001195 }
1196
John McCall645cf442010-02-06 10:23:53 +00001197 // Derive the type we want the substituted decl to have. This had
1198 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001199 if (parm->isExpandedParameterPack()) {
1200 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1201 } else if (parm->isParameterPack() &&
1202 isa<PackExpansionType>(parm->getType())) {
1203 type = SemaRef.SubstType(
1204 cast<PackExpansionType>(parm->getType())->getPattern(),
1205 TemplateArgs, loc, parm->getDeclName());
1206 } else {
1207 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1208 loc, parm->getDeclName());
1209 }
1210 assert(!type.isNull() && "type substitution failed for param type");
1211 assert(!type->isDependentType() && "param type still dependent");
1212 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001213
John McCall91a57552011-07-15 05:09:51 +00001214 if (!result.isInvalid()) type = result.get()->getType();
1215 } else {
1216 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1217
1218 // Note that this type can be different from the type of 'result',
1219 // e.g. if it's an enum type.
1220 type = arg.getIntegralType();
1221 }
1222 if (result.isInvalid()) return ExprError();
1223
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001224 Expr *resultExpr = result.get();
1225 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1226 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCallb8fc0532010-02-06 08:42:39 +00001227}
1228
Douglas Gregorc7793c72011-01-15 01:15:58 +00001229ExprResult
1230TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1231 SubstNonTypeTemplateParmPackExpr *E) {
1232 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1233 // We aren't expanding the parameter pack, so just return ourselves.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001234 return E;
Douglas Gregorc7793c72011-01-15 01:15:58 +00001235 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001236
1237 TemplateArgument Arg = E->getArgumentPack();
1238 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall91a57552011-07-15 05:09:51 +00001239 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1240 E->getParameterPackLocation(),
1241 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001242}
John McCallb8fc0532010-02-06 08:42:39 +00001243
John McCall60d7b3a2010-08-24 06:29:42 +00001244ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001245TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1246 SourceLocation Loc) {
1247 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1248 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1249}
1250
1251ExprResult
1252TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1253 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1254 // We can expand this parameter pack now.
1255 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1256 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1257 if (!VD)
1258 return ExprError();
1259 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1260 }
1261
1262 QualType T = TransformType(E->getType());
1263 if (T.isNull())
1264 return ExprError();
1265
1266 // Transform each of the parameter expansions into the corresponding
1267 // parameters in the instantiation of the function decl.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001268 SmallVector<Decl *, 8> Parms;
Richard Smith9a4db032012-09-12 00:56:43 +00001269 Parms.reserve(E->getNumExpansions());
1270 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1271 I != End; ++I) {
1272 ParmVarDecl *D =
1273 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1274 if (!D)
1275 return ExprError();
1276 Parms.push_back(D);
1277 }
1278
1279 return FunctionParmPackExpr::Create(getSema().Context, T,
1280 E->getParameterPack(),
1281 E->getParameterPackLocation(), Parms);
1282}
1283
1284ExprResult
1285TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1286 ParmVarDecl *PD) {
1287 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1288 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1289 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1290 assert(Found && "no instantiation for parameter pack");
1291
1292 Decl *TransformedDecl;
1293 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Stephen Hines176edba2014-12-01 14:53:08 -08001294 // If this is a reference to a function parameter pack which we can
1295 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smith9a4db032012-09-12 00:56:43 +00001296 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1297 QualType T = TransformType(E->getType());
1298 if (T.isNull())
1299 return ExprError();
1300 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1301 E->getExprLoc(), *Pack);
1302 }
1303
1304 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1305 } else {
1306 TransformedDecl = Found->get<Decl*>();
1307 }
1308
1309 // We have either an unexpanded pack or a specific expansion.
1310 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1311 E->getExprLoc());
1312}
1313
1314ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001315TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1316 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001317
1318 // Handle references to non-type template parameters and non-type template
1319 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001320 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1321 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1322 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001323
1324 // We have a non-type template parameter that isn't fully substituted;
1325 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001326 }
Mike Stump1eb44332009-09-09 15:08:12 +00001327
Richard Smith9a4db032012-09-12 00:56:43 +00001328 // Handle references to function parameter packs.
1329 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1330 if (PD->isParameterPack())
1331 return TransformFunctionParmPackRefExpr(E, PD);
1332
John McCall454feb92009-12-08 09:21:05 +00001333 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001334}
1335
John McCall60d7b3a2010-08-24 06:29:42 +00001336ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001337 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001338 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1339 getDescribedFunctionTemplate() &&
1340 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001341 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1342 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1343 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001344}
1345
Stephen Hines176edba2014-12-01 14:53:08 -08001346template<typename Fn>
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001347QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1348 FunctionProtoTypeLoc TL,
1349 CXXRecordDecl *ThisContext,
Stephen Hines176edba2014-12-01 14:53:08 -08001350 unsigned ThisTypeQuals,
1351 Fn TransformExceptionSpec) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001352 // We need a local instantiation scope for this function prototype.
1353 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Stephen Hines176edba2014-12-01 14:53:08 -08001354 return inherited::TransformFunctionProtoType(
1355 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001356}
1357
John McCall21ef0fa2010-03-11 09:03:00 +00001358ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001359TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001360 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001361 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001362 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001363 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001364 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001365}
1366
Mike Stump1eb44332009-09-09 15:08:12 +00001367QualType
John McCalla2becad2009-10-21 00:40:46 +00001368TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001369 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001370 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001371 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001372 // Replace the template type parameter with its corresponding
1373 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001374
1375 // If the corresponding template argument is NULL or doesn't exist, it's
1376 // because we are performing instantiation from explicitly-specified
1377 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001378 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001379 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1380 TemplateTypeParmTypeLoc NewTL
1381 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1382 NewTL.setNameLoc(TL.getNameLoc());
1383 return TL.getType();
1384 }
Mike Stump1eb44332009-09-09 15:08:12 +00001385
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001386 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1387
1388 if (T->isParameterPack()) {
1389 assert(Arg.getKind() == TemplateArgument::Pack &&
1390 "Missing argument pack");
1391
1392 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001393 // We have the template argument pack, but we're not expanding the
1394 // enclosing pack expansion yet. Just save the template argument
1395 // pack for later substitution.
1396 QualType Result
1397 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1398 SubstTemplateTypeParmPackTypeLoc NewTL
1399 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1400 NewTL.setNameLoc(TL.getNameLoc());
1401 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001402 }
1403
Eli Friedman10ec0e42013-07-19 19:40:38 +00001404 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001405 }
1406
1407 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001408 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001409
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001410 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001411
1412 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001413 QualType Result
1414 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1415 SubstTemplateTypeParmTypeLoc NewTL
1416 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1417 NewTL.setNameLoc(TL.getNameLoc());
1418 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001419 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001420
1421 // The template type parameter comes from an inner template (e.g.,
1422 // the template parameter list of a member template inside the
1423 // template we are instantiating). Create a new template type
1424 // parameter with the template "level" reduced by one.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001425 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001426 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1427 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1428 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1429
John McCalla2becad2009-10-21 00:40:46 +00001430 QualType Result
1431 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1432 - TemplateArgs.getNumLevels(),
1433 T->getIndex(),
1434 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001435 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001436 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1437 NewTL.setNameLoc(TL.getNameLoc());
1438 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001439}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001440
Douglas Gregorc3069d62011-01-14 02:55:32 +00001441QualType
1442TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1443 TypeLocBuilder &TLB,
1444 SubstTemplateTypeParmPackTypeLoc TL) {
1445 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1446 // We aren't expanding the parameter pack, so just return ourselves.
1447 SubstTemplateTypeParmPackTypeLoc NewTL
1448 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1449 NewTL.setNameLoc(TL.getNameLoc());
1450 return TL.getType();
1451 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001452
1453 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1454 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1455 QualType Result = Arg.getAsType();
1456
Douglas Gregorc3069d62011-01-14 02:55:32 +00001457 Result = getSema().Context.getSubstTemplateTypeParmType(
1458 TL.getTypePtr()->getReplacedParameter(),
1459 Result);
1460 SubstTemplateTypeParmTypeLoc NewTL
1461 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1462 NewTL.setNameLoc(TL.getNameLoc());
1463 return Result;
1464}
1465
John McCallce3ff2b2009-08-25 22:02:44 +00001466/// \brief Perform substitution on the type T with a given set of template
1467/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001468///
1469/// This routine substitutes the given template arguments into the
1470/// type T and produces the instantiated type.
1471///
1472/// \param T the type into which the template arguments will be
1473/// substituted. If this type is not dependent, it will be returned
1474/// immediately.
1475///
James Dennett1dfbd922012-06-14 21:40:34 +00001476/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001477/// substituted for the top-level template parameters within T.
1478///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001479/// \param Loc the location in the source code where this substitution
1480/// is being performed. It will typically be the location of the
1481/// declarator (if we're instantiating the type of some declaration)
1482/// or the location of the type in the source code (if, e.g., we're
1483/// instantiating the type of a cast expression).
1484///
1485/// \param Entity the name of the entity associated with a declaration
1486/// being instantiated (if any). May be empty to indicate that there
1487/// is no such entity (if, e.g., this is a type that occurs as part of
1488/// a cast expression) or that the entity has no name (e.g., an
1489/// unnamed function parameter).
1490///
1491/// \returns If the instantiation succeeds, the instantiated
1492/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001493TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001494 const MultiLevelTemplateArgumentList &Args,
1495 SourceLocation Loc,
1496 DeclarationName Entity) {
1497 assert(!ActiveTemplateInstantiations.empty() &&
1498 "Cannot perform an instantiation without some context on the "
1499 "instantiation stack");
1500
Douglas Gregor561f8122011-07-01 01:22:09 +00001501 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001502 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001503 return T;
1504
1505 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1506 return Instantiator.TransformType(T);
1507}
1508
Douglas Gregor603cfb42011-01-05 23:12:31 +00001509TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1510 const MultiLevelTemplateArgumentList &Args,
1511 SourceLocation Loc,
1512 DeclarationName Entity) {
1513 assert(!ActiveTemplateInstantiations.empty() &&
1514 "Cannot perform an instantiation without some context on the "
1515 "instantiation stack");
1516
1517 if (TL.getType().isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001518 return nullptr;
Douglas Gregor603cfb42011-01-05 23:12:31 +00001519
Douglas Gregor561f8122011-07-01 01:22:09 +00001520 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001521 !TL.getType()->isVariablyModifiedType()) {
1522 // FIXME: Make a copy of the TypeLoc data here, so that we can
1523 // return a new TypeSourceInfo. Inefficient!
1524 TypeLocBuilder TLB;
1525 TLB.pushFullCopy(TL);
1526 return TLB.getTypeSourceInfo(Context, TL.getType());
1527 }
1528
1529 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1530 TypeLocBuilder TLB;
1531 TLB.reserve(TL.getFullDataSize());
1532 QualType Result = Instantiator.TransformType(TLB, TL);
1533 if (Result.isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001534 return nullptr;
Douglas Gregor603cfb42011-01-05 23:12:31 +00001535
1536 return TLB.getTypeSourceInfo(Context, Result);
1537}
1538
John McCallcd7ba1c2009-10-21 00:58:09 +00001539/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001540QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001541 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001542 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001543 assert(!ActiveTemplateInstantiations.empty() &&
1544 "Cannot perform an instantiation without some context on the "
1545 "instantiation stack");
1546
Douglas Gregor836adf62010-05-24 17:22:01 +00001547 // If T is not a dependent type or a variably-modified type, there
1548 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001549 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001550 return T;
1551
Douglas Gregor577f75a2009-08-04 16:50:30 +00001552 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1553 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001554}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001555
John McCall6cd3b9f2010-04-09 17:38:44 +00001556static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001557 if (T->getType()->isInstantiationDependentType() ||
1558 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001559 return true;
1560
Abramo Bagnara723df242010-12-14 22:11:44 +00001561 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00001562 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCall6cd3b9f2010-04-09 17:38:44 +00001563 return false;
1564
David Blaikie39e6ab42013-02-18 22:06:02 +00001565 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001566 for (unsigned I = 0, E = FP.getNumParams(); I != E; ++I) {
1567 ParmVarDecl *P = FP.getParam(I);
John McCall6cd3b9f2010-04-09 17:38:44 +00001568
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001569 // This must be synthesized from a typedef.
1570 if (!P) continue;
1571
Douglas Gregorc056c172011-05-09 20:45:16 +00001572 // The parameter's type as written might be dependent even if the
1573 // decayed type was not dependent.
1574 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001575 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001576 return true;
1577
John McCall6cd3b9f2010-04-09 17:38:44 +00001578 // TODO: currently we always rebuild expressions. When we
1579 // properly get lazier about this, we should use the same
1580 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001581 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001582 return true;
1583 }
1584
1585 return false;
1586}
1587
1588/// A form of SubstType intended specifically for instantiating the
1589/// type of a FunctionDecl. Its purpose is solely to force the
Stephen Hines176edba2014-12-01 14:53:08 -08001590/// instantiation of default-argument expressions and to avoid
1591/// instantiating an exception-specification.
John McCall6cd3b9f2010-04-09 17:38:44 +00001592TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1593 const MultiLevelTemplateArgumentList &Args,
1594 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001595 DeclarationName Entity,
1596 CXXRecordDecl *ThisContext,
1597 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001598 assert(!ActiveTemplateInstantiations.empty() &&
1599 "Cannot perform an instantiation without some context on the "
1600 "instantiation stack");
1601
1602 if (!NeedsInstantiationAsFunctionType(T))
1603 return T;
1604
1605 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1606
1607 TypeLocBuilder TLB;
1608
1609 TypeLoc TL = T->getTypeLoc();
1610 TLB.reserve(TL.getFullDataSize());
1611
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001612 QualType Result;
David Blaikie39e6ab42013-02-18 22:06:02 +00001613
Stephen Hines176edba2014-12-01 14:53:08 -08001614 if (FunctionProtoTypeLoc Proto =
1615 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1616 // Instantiate the type, other than its exception specification. The
1617 // exception specification is instantiated in InitFunctionInstantiation
1618 // once we've built the FunctionDecl.
1619 // FIXME: Set the exception specification to EST_Uninstantiated here,
1620 // instead of rebuilding the function type again later.
1621 Result = Instantiator.TransformFunctionProtoType(
1622 TLB, Proto, ThisContext, ThisTypeQuals,
1623 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1624 bool &Changed) { return false; });
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001625 } else {
1626 Result = Instantiator.TransformType(TLB, TL);
1627 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001628 if (Result.isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001629 return nullptr;
John McCall6cd3b9f2010-04-09 17:38:44 +00001630
1631 return TLB.getTypeSourceInfo(Context, Result);
1632}
1633
Stephen Hines176edba2014-12-01 14:53:08 -08001634void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1635 const MultiLevelTemplateArgumentList &Args) {
1636 FunctionProtoType::ExceptionSpecInfo ESI =
1637 Proto->getExtProtoInfo().ExceptionSpec;
1638 assert(ESI.Type != EST_Uninstantiated);
1639
1640 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1641 New->getDeclName());
1642
1643 SmallVector<QualType, 4> ExceptionStorage;
1644 bool Changed = false;
1645 if (Instantiator.TransformExceptionSpec(
1646 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1647 ExceptionStorage, Changed))
1648 // On error, recover by dropping the exception specification.
1649 ESI.Type = EST_None;
1650
1651 UpdateExceptionSpec(New, ESI);
1652}
1653
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001654ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001655 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001656 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001657 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001658 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001659 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001660 TypeSourceInfo *NewDI = nullptr;
1661
Douglas Gregor603cfb42011-01-05 23:12:31 +00001662 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00001663 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1664
Douglas Gregor603cfb42011-01-05 23:12:31 +00001665 // We have a function parameter pack. Substitute into the pattern of the
1666 // expansion.
1667 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1668 OldParm->getLocation(), OldParm->getDeclName());
1669 if (!NewDI)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001670 return nullptr;
1671
Douglas Gregor603cfb42011-01-05 23:12:31 +00001672 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1673 // We still have unexpanded parameter packs, which means that
1674 // our function parameter is still a function parameter pack.
1675 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001676 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001677 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001678 } else if (ExpectParameterPack) {
1679 // We expected to get a parameter pack but didn't (because the type
1680 // itself is not a pack expansion type), so complain. This can occur when
1681 // the substitution goes through an alias template that "loses" the
1682 // pack expansion.
1683 Diag(OldParm->getLocation(),
1684 diag::err_function_parameter_pack_without_parameter_packs)
1685 << NewDI->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001686 return nullptr;
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001687 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001688 } else {
1689 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1690 OldParm->getDeclName());
1691 }
1692
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001693 if (!NewDI)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001694 return nullptr;
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001695
1696 if (NewDI->getType()->isVoidType()) {
1697 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001698 return nullptr;
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001699 }
1700
1701 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001702 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001703 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001704 OldParm->getIdentifier(),
1705 NewDI->getType(), NewDI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001706 OldParm->getStorageClass());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001707 if (!NewParm)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001708 return nullptr;
1709
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001710 // Mark the (new) default argument as uninstantiated (if any).
1711 if (OldParm->hasUninstantiatedDefaultArg()) {
1712 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1713 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001714 } else if (OldParm->hasUnparsedDefaultArg()) {
1715 NewParm->setUnparsedDefaultArg();
1716 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001717 } else if (Expr *Arg = OldParm->getDefaultArg())
1718 // FIXME: if we non-lazily instantiated non-dependent default args for
1719 // non-dependent parameter types we could remove a bunch of duplicate
1720 // conversion warnings for such arguments.
1721 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001722
1723 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001724
Douglas Gregor12c9c002011-01-07 16:43:16 +00001725 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001726 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001727 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1728 } else {
1729 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001730 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001731 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001732
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001733 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1734 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001735 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001736
1737 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1738 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rose09189892013-03-08 22:25:36 +00001739
1740 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1741
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001742 return NewParm;
1743}
1744
Douglas Gregora009b592011-01-07 00:20:55 +00001745/// \brief Substitute the given template arguments into the given set of
1746/// parameters, producing the set of parameter types that would be generated
1747/// from such a substitution.
1748bool Sema::SubstParmTypes(SourceLocation Loc,
1749 ParmVarDecl **Params, unsigned NumParams,
1750 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001751 SmallVectorImpl<QualType> &ParamTypes,
1752 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001753 assert(!ActiveTemplateInstantiations.empty() &&
1754 "Cannot perform an instantiation without some context on the "
1755 "instantiation stack");
1756
1757 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1758 DeclarationName());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001759 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams,
1760 nullptr, ParamTypes,
1761 OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001762}
1763
John McCallce3ff2b2009-08-25 22:02:44 +00001764/// \brief Perform substitution on the base class specifiers of the
1765/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001766///
1767/// Produces a diagnostic and returns true on error, returns false and
1768/// attaches the instantiated base classes to the class template
1769/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001770bool
John McCallce3ff2b2009-08-25 22:02:44 +00001771Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1772 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001773 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001774 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001775 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07001776 for (const auto Base : Pattern->bases()) {
1777 if (!Base.getType()->isDependentType()) {
1778 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay538fccb2013-06-21 18:58:32 +00001779 if (RD->isInvalidDecl())
1780 Instantiation->setInvalidDecl();
1781 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001782 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001783 continue;
1784 }
1785
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001786 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001787 TypeSourceInfo *BaseTypeLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001788 if (Base.isPackExpansion()) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001789 // This is a pack expansion. See whether we should expand it now, or
1790 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001791 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Stephen Hines651f13c2014-04-23 16:59:28 -07001792 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001793 Unexpanded);
1794 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001795 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001796 Optional<unsigned> NumExpansions;
Stephen Hines651f13c2014-04-23 16:59:28 -07001797 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1798 Base.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001799 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001800 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001801 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001802 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001803 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001804 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001805 }
1806
1807 // If we should expand this pack expansion now, do so.
1808 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001809 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001810 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1811
Stephen Hines651f13c2014-04-23 16:59:28 -07001812 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001813 TemplateArgs,
Stephen Hines651f13c2014-04-23 16:59:28 -07001814 Base.getSourceRange().getBegin(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001815 DeclarationName());
1816 if (!BaseTypeLoc) {
1817 Invalid = true;
1818 continue;
1819 }
1820
1821 if (CXXBaseSpecifier *InstantiatedBase
1822 = CheckBaseSpecifier(Instantiation,
Stephen Hines651f13c2014-04-23 16:59:28 -07001823 Base.getSourceRange(),
1824 Base.isVirtual(),
1825 Base.getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001826 BaseTypeLoc,
1827 SourceLocation()))
1828 InstantiatedBases.push_back(InstantiatedBase);
1829 else
1830 Invalid = true;
1831 }
1832
1833 continue;
1834 }
1835
1836 // The resulting base specifier will (still) be a pack expansion.
Stephen Hines651f13c2014-04-23 16:59:28 -07001837 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001838 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Stephen Hines651f13c2014-04-23 16:59:28 -07001839 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001840 TemplateArgs,
Stephen Hines651f13c2014-04-23 16:59:28 -07001841 Base.getSourceRange().getBegin(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001842 DeclarationName());
1843 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07001844 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001845 TemplateArgs,
Stephen Hines651f13c2014-04-23 16:59:28 -07001846 Base.getSourceRange().getBegin(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001847 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001848 }
1849
Nick Lewycky56062202010-07-26 16:56:01 +00001850 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001851 Invalid = true;
1852 continue;
1853 }
1854
1855 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001856 = CheckBaseSpecifier(Instantiation,
Stephen Hines651f13c2014-04-23 16:59:28 -07001857 Base.getSourceRange(),
1858 Base.isVirtual(),
1859 Base.getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001860 BaseTypeLoc,
1861 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001862 InstantiatedBases.push_back(InstantiatedBase);
1863 else
1864 Invalid = true;
1865 }
1866
Douglas Gregor27b152f2009-03-10 18:52:44 +00001867 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001868 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001869 InstantiatedBases.size()))
1870 Invalid = true;
1871
1872 return Invalid;
1873}
1874
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001875// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001876namespace clang {
1877 namespace sema {
1878 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1879 const MultiLevelTemplateArgumentList &TemplateArgs);
1880 }
1881}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001882
Richard Smithf1c66b42012-03-14 23:13:10 +00001883/// Determine whether we would be unable to instantiate this template (because
1884/// it either has no definition, or is in the process of being instantiated).
1885static bool DiagnoseUninstantiableTemplate(Sema &S,
1886 SourceLocation PointOfInstantiation,
1887 TagDecl *Instantiation,
1888 bool InstantiatedFromMember,
1889 TagDecl *Pattern,
1890 TagDecl *PatternDef,
1891 TemplateSpecializationKind TSK,
1892 bool Complain = true) {
1893 if (PatternDef && !PatternDef->isBeingDefined())
1894 return false;
1895
1896 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1897 // Say nothing
1898 } else if (PatternDef) {
1899 assert(PatternDef->isBeingDefined());
1900 S.Diag(PointOfInstantiation,
1901 diag::err_template_instantiate_within_definition)
1902 << (TSK != TSK_ImplicitInstantiation)
1903 << S.Context.getTypeDeclType(Instantiation);
1904 // Not much point in noting the template declaration here, since
1905 // we're lexically inside it.
1906 Instantiation->setInvalidDecl();
1907 } else if (InstantiatedFromMember) {
1908 S.Diag(PointOfInstantiation,
1909 diag::err_implicit_instantiate_member_undefined)
1910 << S.Context.getTypeDeclType(Instantiation);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001911 S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
Richard Smithf1c66b42012-03-14 23:13:10 +00001912 } else {
1913 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1914 << (TSK != TSK_ImplicitInstantiation)
1915 << S.Context.getTypeDeclType(Instantiation);
1916 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1917 }
1918
1919 // In general, Instantiation isn't marked invalid to get more than one
1920 // error for multiple undefined instantiations. But the code that does
1921 // explicit declaration -> explicit definition conversion can't handle
1922 // invalid declarations, so mark as invalid in that case.
1923 if (TSK == TSK_ExplicitInstantiationDeclaration)
1924 Instantiation->setInvalidDecl();
1925 return true;
1926}
1927
Douglas Gregord475b8d2009-03-25 21:17:03 +00001928/// \brief Instantiate the definition of a class from a given pattern.
1929///
1930/// \param PointOfInstantiation The point of instantiation within the
1931/// source code.
1932///
1933/// \param Instantiation is the declaration whose definition is being
1934/// instantiated. This will be either a class template specialization
1935/// or a member class of a class template specialization.
1936///
1937/// \param Pattern is the pattern from which the instantiation
1938/// occurs. This will be either the declaration of a class template or
1939/// the declaration of a member class of a class template.
1940///
1941/// \param TemplateArgs The template arguments to be substituted into
1942/// the pattern.
1943///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001944/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001945///
1946/// \param Complain whether to complain if the class cannot be instantiated due
1947/// to the lack of a definition.
1948///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001949/// \returns true if an error occurred, false otherwise.
1950bool
1951Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1952 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001953 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001954 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001955 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00001956 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001957 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001958 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1959 Instantiation->getInstantiatedFromMemberClass(),
1960 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001961 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001962 Pattern = PatternDef;
1963
Douglas Gregor454885e2009-10-15 15:54:05 +00001964 // \brief Record the point of instantiation.
1965 if (MemberSpecializationInfo *MSInfo
1966 = Instantiation->getMemberSpecializationInfo()) {
1967 MSInfo->setTemplateSpecializationKind(TSK);
1968 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001969 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001970 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001971 Spec->setTemplateSpecializationKind(TSK);
1972 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001973 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001974
Douglas Gregord048bb72009-03-25 21:23:52 +00001975 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd69f37b2013-10-08 08:09:04 +00001976 if (Inst.isInvalid())
Douglas Gregord475b8d2009-03-25 21:17:03 +00001977 return true;
1978
1979 // Enter the scope of this instantiation. We don't use
1980 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001981 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001982 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001983 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001984
Douglas Gregor05030bb2010-03-24 01:33:17 +00001985 // If this is an instantiation of a local class, merge this local
1986 // instantiation scope with the enclosing scope. Otherwise, every
1987 // instantiation of a class has its own local instantiation scope.
1988 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001989 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001990
John McCall1d8d1cc2010-08-01 02:01:53 +00001991 // Pull attributes from the pattern onto the instantiation.
1992 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1993
Douglas Gregord475b8d2009-03-25 21:17:03 +00001994 // Start the definition of this instantiation.
1995 Instantiation->startDefinition();
Stephen Hines651f13c2014-04-23 16:59:28 -07001996
1997 // The instantiation is visible here, even if it was first declared in an
1998 // unimported module.
1999 Instantiation->setHidden(false);
2000
2001 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregor13c85772010-05-06 00:28:52 +00002002 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00002003
John McCallce3ff2b2009-08-25 22:02:44 +00002004 // Do substitution on the base class specifiers.
2005 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002006 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002007
Douglas Gregord65587f2010-11-10 19:44:59 +00002008 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002009 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002010 // Delay instantiation of late parsed attributes.
2011 LateInstantiatedAttrVec LateAttrs;
2012 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2013
Stephen Hines651f13c2014-04-23 16:59:28 -07002014 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00002015 // Don't instantiate members not belonging in this semantic context.
2016 // e.g. for:
2017 // @code
2018 // template <int i> class A {
2019 // class B *g;
2020 // };
2021 // @endcode
2022 // 'class B' has the template as lexical context but semantically it is
2023 // introduced in namespace scope.
Stephen Hines651f13c2014-04-23 16:59:28 -07002024 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00002025 continue;
2026
Stephen Hines651f13c2014-04-23 16:59:28 -07002027 if (Member->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00002028 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002029 continue;
2030 }
2031
Stephen Hines651f13c2014-04-23 16:59:28 -07002032 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002033 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00002034 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00002035 Fields.push_back(Field);
Richard Smith1af83c42012-03-23 03:33:32 +00002036 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2037 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2038 // specialization causes the implicit instantiation of the definitions
2039 // of unscoped member enumerations.
2040 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00002041 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2042 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00002043 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2044 assert(MSInfo && "no spec info for member enum specialization");
2045 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2046 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2047 }
Richard Smithe3f470a2012-07-11 22:37:56 +00002048 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2049 if (SA->isFailed()) {
2050 // A static_assert failed. Bail out; instantiating this
2051 // class is probably not meaningful.
2052 Instantiation->setInvalidDecl();
2053 break;
2054 }
Richard Smith1af83c42012-03-23 03:33:32 +00002055 }
2056
2057 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002058 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002059 } else {
2060 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002061 // instantiations was a semantic disaster, and we'll want to mark the
2062 // declaration invalid.
2063 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002064 }
2065 }
2066
2067 // Finish checking fields.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002068 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2069 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002070 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002071
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002072 // Instantiate late parsed attributes, and attach them to their decls.
2073 // See Sema::InstantiateAttrs
2074 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2075 E = LateAttrs.end(); I != E; ++I) {
2076 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2077 CurrentInstantiationScope = I->Scope;
Richard Smithcafeb942013-06-07 02:33:37 +00002078
2079 // Allow 'this' within late-parsed attributes.
2080 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2081 CXXRecordDecl *ThisContext =
2082 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2083 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2084 ND && ND->isCXXInstanceMember());
2085
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002086 Attr *NewAttr =
2087 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2088 I->NewDecl->addAttr(NewAttr);
2089 LocalInstantiationScope::deleteScopes(I->Scope,
2090 Instantiator.getStartingScope());
2091 }
2092 Instantiator.disableLateAttributeInstantiation();
2093 LateAttrs.clear();
2094
Richard Smithb9d0b762012-07-27 04:22:15 +00002095 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002096
Stephen Hines651f13c2014-04-23 16:59:28 -07002097 // FIXME: We should do something similar for explicit instantiations so they
2098 // end up in the right module.
Abramo Bagnarae9946242011-11-18 08:08:52 +00002099 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002100 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002101 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002102 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002103 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002104
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002105 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002106 // Perform any dependent diagnostics from the pattern.
2107 PerformDependentDiagnostics(Pattern, TemplateArgs);
2108
Douglas Gregord65587f2010-11-10 19:44:59 +00002109 // Instantiate any out-of-line class template partial
2110 // specializations now.
Richard Smithe688ddf2013-09-26 03:49:48 +00002111 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregord65587f2010-11-10 19:44:59 +00002112 P = Instantiator.delayed_partial_spec_begin(),
2113 PEnd = Instantiator.delayed_partial_spec_end();
2114 P != PEnd; ++P) {
2115 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smithe688ddf2013-09-26 03:49:48 +00002116 P->first, P->second)) {
2117 Instantiation->setInvalidDecl();
2118 break;
2119 }
2120 }
2121
2122 // Instantiate any out-of-line variable template partial
2123 // specializations now.
2124 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2125 P = Instantiator.delayed_var_partial_spec_begin(),
2126 PEnd = Instantiator.delayed_var_partial_spec_end();
2127 P != PEnd; ++P) {
2128 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2129 P->first, P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002130 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002131 break;
2132 }
2133 }
2134 }
2135
Douglas Gregord475b8d2009-03-25 21:17:03 +00002136 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002137 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002138
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002139 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002140 Consumer.HandleTagDeclDefinition(Instantiation);
2141
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002142 // Always emit the vtable for an explicit instantiation definition
2143 // of a polymorphic class template specialization.
2144 if (TSK == TSK_ExplicitInstantiationDefinition)
2145 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2146 }
2147
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002148 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002149}
2150
Richard Smithf1c66b42012-03-14 23:13:10 +00002151/// \brief Instantiate the definition of an enum from a given pattern.
2152///
2153/// \param PointOfInstantiation The point of instantiation within the
2154/// source code.
2155/// \param Instantiation is the declaration whose definition is being
2156/// instantiated. This will be a member enumeration of a class
2157/// temploid specialization, or a local enumeration within a
2158/// function temploid specialization.
2159/// \param Pattern The templated declaration from which the instantiation
2160/// occurs.
2161/// \param TemplateArgs The template arguments to be substituted into
2162/// the pattern.
2163/// \param TSK The kind of implicit or explicit instantiation to perform.
2164///
2165/// \return \c true if an error occurred, \c false otherwise.
2166bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2167 EnumDecl *Instantiation, EnumDecl *Pattern,
2168 const MultiLevelTemplateArgumentList &TemplateArgs,
2169 TemplateSpecializationKind TSK) {
2170 EnumDecl *PatternDef = Pattern->getDefinition();
2171 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2172 Instantiation->getInstantiatedFromMemberEnum(),
2173 Pattern, PatternDef, TSK,/*Complain*/true))
2174 return true;
2175 Pattern = PatternDef;
2176
2177 // Record the point of instantiation.
2178 if (MemberSpecializationInfo *MSInfo
2179 = Instantiation->getMemberSpecializationInfo()) {
2180 MSInfo->setTemplateSpecializationKind(TSK);
2181 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2182 }
2183
2184 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd69f37b2013-10-08 08:09:04 +00002185 if (Inst.isInvalid())
Richard Smithf1c66b42012-03-14 23:13:10 +00002186 return true;
2187
Stephen Hines651f13c2014-04-23 16:59:28 -07002188 // The instantiation is visible here, even if it was first declared in an
2189 // unimported module.
2190 Instantiation->setHidden(false);
2191
Richard Smithf1c66b42012-03-14 23:13:10 +00002192 // Enter the scope of this instantiation. We don't use
2193 // PushDeclContext because we don't have a scope.
2194 ContextRAII SavedContext(*this, Instantiation);
2195 EnterExpressionEvaluationContext EvalContext(*this,
2196 Sema::PotentiallyEvaluated);
2197
2198 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2199
2200 // Pull attributes from the pattern onto the instantiation.
2201 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2202
2203 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2204 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2205
2206 // Exit the scope of this instantiation.
2207 SavedContext.pop();
2208
2209 return Instantiation->isInvalidDecl();
2210}
2211
Stephen Hines176edba2014-12-01 14:53:08 -08002212
2213/// \brief Instantiate the definition of a field from the given pattern.
2214///
2215/// \param PointOfInstantiation The point of instantiation within the
2216/// source code.
2217/// \param Instantiation is the declaration whose definition is being
2218/// instantiated. This will be a class of a class temploid
2219/// specialization, or a local enumeration within a function temploid
2220/// specialization.
2221/// \param Pattern The templated declaration from which the instantiation
2222/// occurs.
2223/// \param TemplateArgs The template arguments to be substituted into
2224/// the pattern.
2225///
2226/// \return \c true if an error occurred, \c false otherwise.
2227bool Sema::InstantiateInClassInitializer(
2228 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2229 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2230 // If there is no initializer, we don't need to do anything.
2231 if (!Pattern->hasInClassInitializer())
2232 return false;
2233
2234 assert(Instantiation->getInClassInitStyle() ==
2235 Pattern->getInClassInitStyle() &&
2236 "pattern and instantiation disagree about init style");
2237
2238 // Error out if we haven't parsed the initializer of the pattern yet because
2239 // we are waiting for the closing brace of the outer class.
2240 Expr *OldInit = Pattern->getInClassInitializer();
2241 if (!OldInit) {
2242 RecordDecl *PatternRD = Pattern->getParent();
2243 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2244 if (OutermostClass == PatternRD) {
2245 Diag(Pattern->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
2246 << PatternRD << Pattern;
2247 } else {
2248 Diag(Pattern->getLocEnd(),
2249 diag::err_in_class_initializer_not_yet_parsed_outer_class)
2250 << PatternRD << OutermostClass << Pattern;
2251 }
2252 Instantiation->setInvalidDecl();
2253 return true;
2254 }
2255
2256 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2257 if (Inst.isInvalid())
2258 return true;
2259
2260 // Enter the scope of this instantiation. We don't use PushDeclContext because
2261 // we don't have a scope.
2262 ContextRAII SavedContext(*this, Instantiation->getParent());
2263 EnterExpressionEvaluationContext EvalContext(*this,
2264 Sema::PotentiallyEvaluated);
2265
2266 LocalInstantiationScope Scope(*this);
2267
2268 // Instantiate the initializer.
2269 ActOnStartCXXInClassMemberInitializer();
2270 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2271
2272 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2273 /*CXXDirectInit=*/false);
2274 Expr *Init = NewInit.get();
2275 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2276 ActOnFinishCXXInClassMemberInitializer(
2277 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2278
2279 // Exit the scope of this instantiation.
2280 SavedContext.pop();
2281
2282 // Return true if the in-class initializer is still missing.
2283 return !Instantiation->getInClassInitializer();
2284}
2285
Douglas Gregor9b623632010-10-12 23:32:35 +00002286namespace {
2287 /// \brief A partial specialization whose template arguments have matched
2288 /// a given template-id.
2289 struct PartialSpecMatchResult {
2290 ClassTemplatePartialSpecializationDecl *Partial;
2291 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002292 };
2293}
2294
Larisse Voufo567f9172013-08-22 00:59:14 +00002295bool Sema::InstantiateClassTemplateSpecialization(
2296 SourceLocation PointOfInstantiation,
2297 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2298 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002299 // Perform the actual instantiation on the canonical declaration.
2300 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002301 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002302
Douglas Gregor52604ab2009-09-11 21:19:12 +00002303 // Check whether we have already instantiated or specialized this class
2304 // template specialization.
2305 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2306 if (ClassTemplateSpec->getSpecializationKind() ==
2307 TSK_ExplicitInstantiationDeclaration &&
2308 TSK == TSK_ExplicitInstantiationDefinition) {
2309 // An explicit instantiation definition follows an explicit instantiation
2310 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2311 // explicit instantiation.
2312 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002313
2314 // If this is an explicit instantiation definition, mark the
2315 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002316 if (TSK == TSK_ExplicitInstantiationDefinition &&
2317 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002318 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2319
Douglas Gregor52604ab2009-09-11 21:19:12 +00002320 return false;
2321 }
2322
2323 // We can only instantiate something that hasn't already been
2324 // instantiated or specialized. Fail without any diagnostics: our
2325 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002326 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002327 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002328
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002329 if (ClassTemplateSpec->isInvalidDecl())
2330 return true;
2331
Douglas Gregor2943aed2009-03-03 04:44:36 +00002332 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002333 CXXRecordDecl *Pattern = nullptr;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002334
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002335 // C++ [temp.class.spec.match]p1:
2336 // When a class template is used in a context that requires an
2337 // instantiation of the class, it is necessary to determine
2338 // whether the instantiation is to be generated using the primary
2339 // template or one of the partial specializations. This is done by
2340 // matching the template arguments of the class template
2341 // specialization with the template argument lists of the partial
2342 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002343 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002344 SmallVector<MatchResult, 4> Matched;
2345 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002346 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo43847122013-07-19 23:00:19 +00002347 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002348 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2349 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo43847122013-07-19 23:00:19 +00002350 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorf67875d2009-06-12 18:26:56 +00002351 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002352 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002353 ClassTemplateSpec->getTemplateArgs(),
2354 Info)) {
Larisse Voufo43847122013-07-19 23:00:19 +00002355 // Store the failed-deduction information for use in diagnostics, later.
2356 // TODO: Actually use the failed-deduction info?
2357 FailedCandidates.addCandidate()
2358 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorf67875d2009-06-12 18:26:56 +00002359 (void)Result;
2360 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002361 Matched.push_back(PartialSpecMatchResult());
2362 Matched.back().Partial = Partial;
2363 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002364 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002365 }
2366
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002367 // If we're dealing with a member template where the template parameters
2368 // have been instantiated, this provides the original template parameters
2369 // from which the member template's parameters were instantiated.
Stephen Hines651f13c2014-04-23 16:59:28 -07002370
Douglas Gregored9c0f92009-10-29 00:04:11 +00002371 if (Matched.size() >= 1) {
Craig Topper09d19ef2013-07-04 03:08:24 +00002372 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002373 if (Matched.size() == 1) {
2374 // -- If exactly one matching specialization is found, the
2375 // instantiation is generated from that specialization.
2376 // We don't need to do anything for this.
2377 } else {
2378 // -- If more than one matching specialization is found, the
2379 // partial order rules (14.5.4.2) are used to determine
2380 // whether one of the specializations is more specialized
2381 // than the others. If none of the specializations is more
2382 // specialized than all of the other matching
2383 // specializations, then the use of the class template is
2384 // ambiguous and the program is ill-formed.
Craig Topper09d19ef2013-07-04 03:08:24 +00002385 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2386 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002387 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002388 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002389 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002390 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002391 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002392 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002393
Douglas Gregored9c0f92009-10-29 00:04:11 +00002394 // Determine if the best partial specialization is more specialized than
2395 // the others.
2396 bool Ambiguous = false;
Craig Topper09d19ef2013-07-04 03:08:24 +00002397 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2398 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002399 P != PEnd; ++P) {
2400 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002401 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002402 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002403 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002404 Ambiguous = true;
2405 break;
2406 }
2407 }
2408
2409 if (Ambiguous) {
2410 // Partial ordering did not produce a clear winner. Complain.
2411 ClassTemplateSpec->setInvalidDecl();
2412 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2413 << ClassTemplateSpec;
2414
2415 // Print the matching partial specializations.
Craig Topper09d19ef2013-07-04 03:08:24 +00002416 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2417 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002418 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002419 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2420 << getTemplateArgumentBindingsText(
2421 P->Partial->getTemplateParameters(),
2422 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002423
Douglas Gregored9c0f92009-10-29 00:04:11 +00002424 return true;
2425 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002426 }
2427
2428 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002429 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002430 while (OrigPartialSpec->getInstantiatedFromMember()) {
2431 // If we've found an explicit specialization of this class template,
2432 // stop here and use that as the pattern.
2433 if (OrigPartialSpec->isMemberSpecialization())
2434 break;
2435
2436 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2437 }
2438
2439 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002440 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002441 } else {
2442 // -- If no matches are found, the instantiation is generated
2443 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002444 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002445 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2446 // If we've found an explicit specialization of this class template,
2447 // stop here and use that as the pattern.
2448 if (OrigTemplate->isMemberSpecialization())
2449 break;
2450
Douglas Gregord6350ae2009-08-28 20:31:08 +00002451 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002452 }
2453
Douglas Gregord6350ae2009-08-28 20:31:08 +00002454 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002455 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002456
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002457 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2458 Pattern,
2459 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002460 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002461 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002462
Douglas Gregor199d9912009-06-05 00:53:49 +00002463 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002464}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002465
John McCallce3ff2b2009-08-25 22:02:44 +00002466/// \brief Instantiates the definitions of all of the member
2467/// of the given class, which is an instantiation of a class template
2468/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002469void
2470Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002471 CXXRecordDecl *Instantiation,
2472 const MultiLevelTemplateArgumentList &TemplateArgs,
2473 TemplateSpecializationKind TSK) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002474 // FIXME: We need to notify the ASTMutationListener that we did all of these
2475 // things, in case we have an explicit instantiation definition in a PCM, a
2476 // module, or preamble, and the declaration is in an imported AST.
Bill Wendling57907e52013-11-28 00:34:08 +00002477 assert(
2478 (TSK == TSK_ExplicitInstantiationDefinition ||
2479 TSK == TSK_ExplicitInstantiationDeclaration ||
2480 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2481 "Unexpected template specialization kind!");
Stephen Hines651f13c2014-04-23 16:59:28 -07002482 for (auto *D : Instantiation->decls()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002483 bool SuppressNew = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07002484 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002485 if (FunctionDecl *Pattern
2486 = Function->getInstantiatedFromMemberFunction()) {
2487 MemberSpecializationInfo *MSInfo
2488 = Function->getMemberSpecializationInfo();
2489 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002490 if (MSInfo->getTemplateSpecializationKind()
2491 == TSK_ExplicitSpecialization)
2492 continue;
2493
Douglas Gregor0d035142009-10-27 18:42:08 +00002494 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2495 Function,
2496 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002497 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002498 SuppressNew) ||
2499 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002500 continue;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002501
2502 // C++11 [temp.explicit]p8:
2503 // An explicit instantiation definition that names a class template
2504 // specialization explicitly instantiates the class template
2505 // specialization and is only an explicit instantiation definition
2506 // of members whose definition is visible at the point of
2507 // instantiation.
2508 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002509 continue;
2510
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002511 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2512
2513 if (Function->isDefined()) {
2514 // Let the ASTConsumer know that this function has been explicitly
2515 // instantiated now, and its linkage might have changed.
2516 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2517 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002518 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002519 } else if (TSK == TSK_ImplicitInstantiation) {
2520 PendingLocalImplicitInstantiations.push_back(
2521 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor0d035142009-10-27 18:42:08 +00002522 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002523 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002524 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smithd0629eb2013-09-27 20:14:12 +00002525 if (isa<VarTemplateSpecializationDecl>(Var))
2526 continue;
2527
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002528 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002529 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2530 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002531 if (MSInfo->getTemplateSpecializationKind()
2532 == TSK_ExplicitSpecialization)
2533 continue;
2534
Douglas Gregor0d035142009-10-27 18:42:08 +00002535 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2536 Var,
2537 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002538 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002539 SuppressNew) ||
2540 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002541 continue;
2542
Douglas Gregor0d035142009-10-27 18:42:08 +00002543 if (TSK == TSK_ExplicitInstantiationDefinition) {
2544 // C++0x [temp.explicit]p8:
2545 // An explicit instantiation definition that names a class template
2546 // specialization explicitly instantiates the class template
2547 // specialization and is only an explicit instantiation definition
2548 // of members whose definition is visible at the point of
2549 // instantiation.
2550 if (!Var->getInstantiatedFromStaticDataMember()
2551 ->getOutOfLineDefinition())
2552 continue;
2553
2554 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002555 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002556 } else {
2557 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2558 }
2559 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002560 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002561 // Always skip the injected-class-name, along with any
2562 // redeclarations of nested classes, since both would cause us
2563 // to try to instantiate the members of a class twice.
Stephen Hines176edba2014-12-01 14:53:08 -08002564 // Skip closure types; they'll get instantiated when we instantiate
2565 // the corresponding lambda-expression.
2566 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2567 Record->isLambda())
Douglas Gregor2db32322009-10-07 23:56:10 +00002568 continue;
2569
Douglas Gregor0d035142009-10-27 18:42:08 +00002570 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2571 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002572
2573 if (MSInfo->getTemplateSpecializationKind()
2574 == TSK_ExplicitSpecialization)
2575 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002576
Douglas Gregor0d035142009-10-27 18:42:08 +00002577 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2578 Record,
2579 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002580 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002581 SuppressNew) ||
2582 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002583 continue;
2584
Douglas Gregor0d035142009-10-27 18:42:08 +00002585 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2586 assert(Pattern && "Missing instantiated-from-template information");
2587
Douglas Gregor952b0172010-02-11 01:04:33 +00002588 if (!Record->getDefinition()) {
2589 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002590 // C++0x [temp.explicit]p8:
2591 // An explicit instantiation definition that names a class template
2592 // specialization explicitly instantiates the class template
2593 // specialization and is only an explicit instantiation definition
2594 // of members whose definition is visible at the point of
2595 // instantiation.
2596 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2597 MSInfo->setTemplateSpecializationKind(TSK);
2598 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2599 }
2600
2601 continue;
2602 }
2603
2604 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002605 TemplateArgs,
2606 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002607 } else {
2608 if (TSK == TSK_ExplicitInstantiationDefinition &&
2609 Record->getTemplateSpecializationKind() ==
2610 TSK_ExplicitInstantiationDeclaration) {
2611 Record->setTemplateSpecializationKind(TSK);
2612 MarkVTableUsed(PointOfInstantiation, Record, true);
2613 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002614 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002615
Douglas Gregor952b0172010-02-11 01:04:33 +00002616 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002617 if (Pattern)
2618 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2619 TSK);
Stephen Hines651f13c2014-04-23 16:59:28 -07002620 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smithf1c66b42012-03-14 23:13:10 +00002621 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2622 assert(MSInfo && "No member specialization information?");
2623
2624 if (MSInfo->getTemplateSpecializationKind()
2625 == TSK_ExplicitSpecialization)
2626 continue;
2627
2628 if (CheckSpecializationInstantiationRedecl(
2629 PointOfInstantiation, TSK, Enum,
2630 MSInfo->getTemplateSpecializationKind(),
2631 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2632 SuppressNew)
2633 continue;
2634
2635 if (Enum->getDefinition())
2636 continue;
2637
2638 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2639 assert(Pattern && "Missing instantiated-from-template information");
2640
2641 if (TSK == TSK_ExplicitInstantiationDefinition) {
2642 if (!Pattern->getDefinition())
2643 continue;
2644
2645 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2646 } else {
2647 MSInfo->setTemplateSpecializationKind(TSK);
2648 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2649 }
Stephen Hines176edba2014-12-01 14:53:08 -08002650 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2651 // No need to instantiate in-class initializers during explicit
2652 // instantiation.
2653 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2654 CXXRecordDecl *ClassPattern =
2655 Instantiation->getTemplateInstantiationPattern();
2656 DeclContext::lookup_result Lookup =
2657 ClassPattern->lookup(Field->getDeclName());
2658 assert(Lookup.size() == 1);
2659 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
2660 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2661 TemplateArgs);
2662 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002663 }
2664 }
2665}
2666
2667/// \brief Instantiate the definitions of all of the members of the
2668/// given class template specialization, which was named as part of an
2669/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002670void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002671Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002672 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002673 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2674 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002675 // C++0x [temp.explicit]p7:
2676 // An explicit instantiation that names a class template
2677 // specialization is an explicit instantion of the same kind
2678 // (declaration or definition) of each of its members (not
2679 // including members inherited from base classes) that has not
2680 // been previously explicitly specialized in the translation unit
2681 // containing the explicit instantiation, except as described
2682 // below.
2683 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002684 getTemplateInstantiationArgs(ClassTemplateSpec),
2685 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002686}
2687
John McCall60d7b3a2010-08-24 06:29:42 +00002688StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002689Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002690 if (!S)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002691 return S;
Douglas Gregor43959a92009-08-20 07:17:43 +00002692
2693 TemplateInstantiator Instantiator(*this, TemplateArgs,
2694 SourceLocation(),
2695 DeclarationName());
2696 return Instantiator.TransformStmt(S);
2697}
2698
John McCall60d7b3a2010-08-24 06:29:42 +00002699ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002700Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002701 if (!E)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002702 return E;
Mike Stump1eb44332009-09-09 15:08:12 +00002703
Douglas Gregorb98b1992009-08-11 05:31:07 +00002704 TemplateInstantiator Instantiator(*this, TemplateArgs,
2705 SourceLocation(),
2706 DeclarationName());
2707 return Instantiator.TransformExpr(E);
2708}
2709
Richard Smithc83c2302012-12-19 01:39:02 +00002710ExprResult Sema::SubstInitializer(Expr *Init,
2711 const MultiLevelTemplateArgumentList &TemplateArgs,
2712 bool CXXDirectInit) {
2713 TemplateInstantiator Instantiator(*this, TemplateArgs,
2714 SourceLocation(),
2715 DeclarationName());
2716 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2717}
2718
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002719bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2720 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002721 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002722 if (NumExprs == 0)
2723 return false;
Richard Smithc83c2302012-12-19 01:39:02 +00002724
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002725 TemplateInstantiator Instantiator(*this, TemplateArgs,
2726 SourceLocation(),
2727 DeclarationName());
2728 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2729}
2730
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002731NestedNameSpecifierLoc
2732Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2733 const MultiLevelTemplateArgumentList &TemplateArgs) {
2734 if (!NNS)
2735 return NestedNameSpecifierLoc();
2736
2737 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2738 DeclarationName());
2739 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2740}
2741
Abramo Bagnara25777432010-08-11 22:01:17 +00002742/// \brief Do template substitution on declaration name info.
2743DeclarationNameInfo
2744Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2745 const MultiLevelTemplateArgumentList &TemplateArgs) {
2746 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2747 NameInfo.getName());
2748 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2749}
2750
Douglas Gregorde650ae2009-03-31 18:38:02 +00002751TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002752Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2753 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002754 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002755 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2756 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002757 CXXScopeSpec SS;
2758 SS.Adopt(QualifierLoc);
2759 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002760}
Douglas Gregor91333002009-06-11 00:06:24 +00002761
Douglas Gregore02e2622010-12-22 21:19:48 +00002762bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2763 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002764 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002765 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2766 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002767
2768 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002769}
Douglas Gregor895162d2010-04-30 18:55:50 +00002770
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002771static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002772 // When storing ParmVarDecls in the local instantiation scope, we always
2773 // want to use the ParmVarDecl from the canonical function declaration,
2774 // since the map is then valid for any redeclaration or definition of that
2775 // function.
2776 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2777 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2778 unsigned i = PV->getFunctionScopeIndex();
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002779 // This parameter might be from a freestanding function type within the
2780 // function and isn't necessarily referring to one of FD's parameters.
2781 if (FD->getParamDecl(i) == PV)
2782 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002783 }
2784 }
2785 return D;
2786}
2787
2788
Douglas Gregor12c9c002011-01-07 16:43:16 +00002789llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2790LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002791 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002792 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002793 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002794
Douglas Gregor895162d2010-04-30 18:55:50 +00002795 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002796 const Decl *CheckD = D;
2797 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002798 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002799 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002800 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002801
2802 // If this is a tag declaration, it's possible that we need to look for
2803 // a previous declaration.
2804 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002805 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002806 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002807 CheckD = nullptr;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002808 } while (CheckD);
2809
Douglas Gregor895162d2010-04-30 18:55:50 +00002810 // If we aren't combined with our outer scope, we're done.
2811 if (!Current->CombineWithOuterScope)
2812 break;
2813 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002814
Serge Pavlovdc49d522013-07-15 06:14:07 +00002815 // If we're performing a partial substitution during template argument
2816 // deduction, we may not have values for template parameters yet.
2817 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2818 isa<TemplateTemplateParmDecl>(D))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002819 return nullptr;
Serge Pavlovdc49d522013-07-15 06:14:07 +00002820
Chris Lattner57ad3782011-02-17 20:34:02 +00002821 // If we didn't find the decl, then we either have a sema bug, or we have a
2822 // forward reference to a label declaration. Return null to indicate that
2823 // we have an uninstantiated label.
2824 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002825 return nullptr;
Douglas Gregor895162d2010-04-30 18:55:50 +00002826}
2827
John McCall2a7fb272010-08-25 05:32:35 +00002828void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002829 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002830 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002831 if (Stored.isNull()) {
2832#ifndef NDEBUG
2833 // It should not be present in any surrounding scope either.
2834 LocalInstantiationScope *Current = this;
2835 while (Current->CombineWithOuterScope && Current->Outer) {
2836 Current = Current->Outer;
2837 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2838 "Instantiated local in inner and outer scopes");
2839 }
2840#endif
Douglas Gregord3731192011-01-10 07:32:04 +00002841 Stored = Inst;
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002842 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
Benjamin Kramer3bbffd52013-04-12 15:22:25 +00002843 Pack->push_back(Inst);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002844 } else {
Douglas Gregord3731192011-01-10 07:32:04 +00002845 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002846 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002847}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002848
2849void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2850 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002851 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002852 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2853 Pack->push_back(Inst);
2854}
2855
2856void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002857#ifndef NDEBUG
2858 // This should be the first time we've been told about this decl.
2859 for (LocalInstantiationScope *Current = this;
2860 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2861 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2862 "Creating local pack after instantiation of local");
2863#endif
2864
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002865 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002866 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregor12c9c002011-01-07 16:43:16 +00002867 DeclArgumentPack *Pack = new DeclArgumentPack;
2868 Stored = Pack;
2869 ArgumentPacks.push_back(Pack);
2870}
2871
Douglas Gregord3731192011-01-10 07:32:04 +00002872void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2873 const TemplateArgument *ExplicitArgs,
2874 unsigned NumExplicitArgs) {
2875 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2876 "Already have a partially-substituted pack");
2877 assert((!PartiallySubstitutedPack
2878 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2879 "Wrong number of arguments in partially-substituted pack");
2880 PartiallySubstitutedPack = Pack;
2881 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2882 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2883}
2884
2885NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2886 const TemplateArgument **ExplicitArgs,
2887 unsigned *NumExplicitArgs) const {
2888 if (ExplicitArgs)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002889 *ExplicitArgs = nullptr;
Douglas Gregord3731192011-01-10 07:32:04 +00002890 if (NumExplicitArgs)
2891 *NumExplicitArgs = 0;
2892
2893 for (const LocalInstantiationScope *Current = this; Current;
2894 Current = Current->Outer) {
2895 if (Current->PartiallySubstitutedPack) {
2896 if (ExplicitArgs)
2897 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2898 if (NumExplicitArgs)
2899 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2900
2901 return Current->PartiallySubstitutedPack;
2902 }
2903
2904 if (!Current->CombineWithOuterScope)
2905 break;
2906 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002907
2908 return nullptr;
Douglas Gregord3731192011-01-10 07:32:04 +00002909}