blob: 25eb72ce1cb95173ce58201459aaaff78a436b2c [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"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/Basic/LangOptions.h"
John McCall19510852010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
Richard Smith7a614d82011-06-11 17:19:42 +000021#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000022#include "clang/Sema/Lookup.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000024#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000025
26using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000027using namespace sema;
Douglas Gregor99ebf652009-02-27 19:31:52 +000028
Douglas Gregoree1828a2009-03-10 18:03:33 +000029//===----------------------------------------------------------------------===/
30// Template Instantiation Support
31//===----------------------------------------------------------------------===/
32
Douglas Gregord6350ae2009-08-28 20:31:08 +000033/// \brief Retrieve the template argument list(s) that should be used to
34/// instantiate the definition of the given declaration.
Douglas Gregor0f8716b2009-11-09 19:17:50 +000035///
36/// \param D the declaration for which we are computing template instantiation
37/// arguments.
38///
39/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor525f96c2010-02-05 07:33:43 +000040///
41/// \param RelativeToPrimary true if we should get the template
42/// arguments relative to the primary template, even when we're
43/// dealing with a specialization. This is only relevant for function
44/// template specializations.
Douglas Gregore7089b02010-05-03 23:29:10 +000045///
46/// \param Pattern If non-NULL, indicates the pattern from which we will be
47/// instantiating the definition of the given declaration, \p D. This is
48/// used to determine the proper set of template instantiation arguments for
49/// friend function template specializations.
Douglas Gregord1102432009-08-28 17:37:35 +000050MultiLevelTemplateArgumentList
Douglas Gregor0f8716b2009-11-09 19:17:50 +000051Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor525f96c2010-02-05 07:33:43 +000052 const TemplateArgumentList *Innermost,
Douglas Gregore7089b02010-05-03 23:29:10 +000053 bool RelativeToPrimary,
54 const FunctionDecl *Pattern) {
Douglas Gregord1102432009-08-28 17:37:35 +000055 // Accumulate the set of template argument lists in this structure.
56 MultiLevelTemplateArgumentList Result;
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor0f8716b2009-11-09 19:17:50 +000058 if (Innermost)
59 Result.addOuterTemplateArguments(Innermost);
60
Douglas Gregord1102432009-08-28 17:37:35 +000061 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregor93104c12011-05-22 00:21:10 +000062 if (!Ctx) {
Douglas Gregord1102432009-08-28 17:37:35 +000063 Ctx = D->getDeclContext();
Larisse Voufoef4579c2013-08-06 01:03:05 +000064
65 // Add template arguments from a variable template instantiation.
66 if (VarTemplateSpecializationDecl *Spec =
67 dyn_cast<VarTemplateSpecializationDecl>(D)) {
68 // We're done when we hit an explicit specialization.
69 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
70 !isa<VarTemplatePartialSpecializationDecl>(Spec))
71 return Result;
72
73 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
74
75 // If this variable template specialization was instantiated from a
76 // specialized member that is a variable template, we're done.
77 assert(Spec->getSpecializedTemplate() && "No variable template?");
78 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
79 return Result;
80 }
81
Douglas Gregor383041d2011-06-15 14:20:42 +000082 // If we have a template template parameter with translation unit context,
83 // then we're performing substitution into a default template argument of
84 // this template template parameter before we've constructed the template
85 // that will own this template template parameter. In this case, we
86 // use empty template parameter lists for all of the outer templates
87 // to avoid performing any substitutions.
88 if (Ctx->isTranslationUnit()) {
89 if (TemplateTemplateParmDecl *TTP
90 = dyn_cast<TemplateTemplateParmDecl>(D)) {
91 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith7a9f7c72013-05-17 03:04:50 +000092 Result.addOuterTemplateArguments(None);
Douglas Gregor383041d2011-06-15 14:20:42 +000093 return Result;
94 }
95 }
Douglas Gregor93104c12011-05-22 00:21:10 +000096 }
97
John McCallf181d8a2009-08-29 03:16:09 +000098 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +000099 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +0000100 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +0000101 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
102 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +0000103 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
104 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +0000105 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Douglas Gregord1102432009-08-28 17:37:35 +0000107 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000108
109 // If this class template specialization was instantiated from a
110 // specialized member that is a class template, we're done.
111 assert(Spec->getSpecializedTemplate() && "No class template?");
112 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
113 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000114 }
Douglas Gregord1102432009-08-28 17:37:35 +0000115 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +0000116 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000117 if (!RelativeToPrimary &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000118 (Function->getTemplateSpecializationKind() ==
119 TSK_ExplicitSpecialization &&
120 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000121 break;
122
Douglas Gregord1102432009-08-28 17:37:35 +0000123 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000124 = Function->getTemplateSpecializationArgs()) {
125 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000126 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000127
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000128 // If this function was instantiated from a specialized member that is
129 // a function template, we're done.
130 assert(Function->getPrimaryTemplate() && "No function template?");
131 if (Function->getPrimaryTemplate()->isMemberSpecialization())
132 break;
Douglas Gregorc494f772011-03-05 17:54:25 +0000133 } else if (FunctionTemplateDecl *FunTmpl
134 = Function->getDescribedFunctionTemplate()) {
135 // Add the "injected" template arguments.
Richard Smith7a9f7c72013-05-17 03:04:50 +0000136 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000137 }
138
John McCallf181d8a2009-08-29 03:16:09 +0000139 // If this is a friend declaration and it declares an entity at
140 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000141 // instead of its semantic parent, unless of course the pattern we're
142 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000143 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000144 Function->getDeclContext()->isFileContext() &&
145 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000146 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000147 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000148 continue;
149 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000150 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
151 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
152 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith7a9f7c72013-05-17 03:04:50 +0000153 const TemplateSpecializationType *TST =
154 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
155 Result.addOuterTemplateArguments(
156 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor24bae922010-07-08 18:37:38 +0000157 if (ClassTemplate->isMemberSpecialization())
158 break;
159 }
Douglas Gregord1102432009-08-28 17:37:35 +0000160 }
John McCallf181d8a2009-08-29 03:16:09 +0000161
162 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000163 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000164 }
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Douglas Gregord1102432009-08-28 17:37:35 +0000166 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000167}
168
Douglas Gregorf35f8282009-11-11 21:54:23 +0000169bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
170 switch (Kind) {
171 case TemplateInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000172 case ExceptionSpecInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000173 case DefaultTemplateArgumentInstantiation:
174 case DefaultFunctionArgumentInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000175 case ExplicitTemplateArgumentSubstitution:
176 case DeducedTemplateArgumentSubstitution:
177 case PriorTemplateArgumentSubstitution:
Richard Smithab91ef12012-07-08 02:38:24 +0000178 return true;
179
Douglas Gregorf35f8282009-11-11 21:54:23 +0000180 case DefaultTemplateArgumentChecking:
181 return false;
182 }
David Blaikie7530c032012-01-17 06:56:22 +0000183
184 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000185}
186
Douglas Gregor26dce442009-03-10 00:06:19 +0000187Sema::InstantiatingTemplate::
188InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000189 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000190 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000191 : SemaRef(SemaRef),
192 SavedInNonInstantiationSFINAEContext(
193 SemaRef.InNonInstantiationSFINAEContext)
194{
Douglas Gregordf667e72009-03-10 20:44:00 +0000195 Invalid = CheckInstantiationDepth(PointOfInstantiation,
196 InstantiationRange);
197 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000198 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +0000199 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +0000200 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000201 Inst.Entity = Entity;
Douglas Gregor313a81d2009-03-12 18:36:18 +0000202 Inst.TemplateArgs = 0;
203 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +0000204 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000205 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregordf667e72009-03-10 20:44:00 +0000206 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregordf667e72009-03-10 20:44:00 +0000207 }
208}
209
Richard Smithe6975e92012-04-17 00:58:00 +0000210Sema::InstantiatingTemplate::
211InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
212 FunctionDecl *Entity, ExceptionSpecification,
213 SourceRange InstantiationRange)
214 : SemaRef(SemaRef),
215 SavedInNonInstantiationSFINAEContext(
216 SemaRef.InNonInstantiationSFINAEContext)
217{
218 Invalid = CheckInstantiationDepth(PointOfInstantiation,
219 InstantiationRange);
220 if (!Invalid) {
221 ActiveTemplateInstantiation Inst;
222 Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
223 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000224 Inst.Entity = Entity;
Richard Smithe6975e92012-04-17 00:58:00 +0000225 Inst.TemplateArgs = 0;
226 Inst.NumTemplateArgs = 0;
227 Inst.InstantiationRange = InstantiationRange;
228 SemaRef.InNonInstantiationSFINAEContext = false;
229 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
230 }
231}
232
Richard Smith7e54fb52012-07-16 01:09:10 +0000233Sema::InstantiatingTemplate::
234InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
235 TemplateDecl *Template,
236 ArrayRef<TemplateArgument> TemplateArgs,
237 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000238 : SemaRef(SemaRef),
239 SavedInNonInstantiationSFINAEContext(
240 SemaRef.InNonInstantiationSFINAEContext)
241{
Douglas Gregordf667e72009-03-10 20:44:00 +0000242 Invalid = CheckInstantiationDepth(PointOfInstantiation,
243 InstantiationRange);
244 if (!Invalid) {
245 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000246 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000247 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
248 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000249 Inst.Entity = Template;
Richard Smith7e54fb52012-07-16 01:09:10 +0000250 Inst.TemplateArgs = TemplateArgs.data();
251 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor26dce442009-03-10 00:06:19 +0000252 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000253 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000254 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000255 }
256}
257
Richard Smith7e54fb52012-07-16 01:09:10 +0000258Sema::InstantiatingTemplate::
259InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
260 FunctionTemplateDecl *FunctionTemplate,
261 ArrayRef<TemplateArgument> TemplateArgs,
262 ActiveTemplateInstantiation::InstantiationKind Kind,
263 sema::TemplateDeductionInfo &DeductionInfo,
264 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000265 : SemaRef(SemaRef),
266 SavedInNonInstantiationSFINAEContext(
267 SemaRef.InNonInstantiationSFINAEContext)
268{
Richard Smithab91ef12012-07-08 02:38:24 +0000269 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Douglas Gregorcca9e962009-07-01 22:01:06 +0000270 if (!Invalid) {
271 ActiveTemplateInstantiation Inst;
272 Inst.Kind = Kind;
273 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000274 Inst.Entity = FunctionTemplate;
Richard Smith7e54fb52012-07-16 01:09:10 +0000275 Inst.TemplateArgs = TemplateArgs.data();
276 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor9b623632010-10-12 23:32:35 +0000277 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000278 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000279 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000280 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000281
282 if (!Inst.isInstantiationRecord())
283 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000284 }
285}
286
Richard Smith7e54fb52012-07-16 01:09:10 +0000287Sema::InstantiatingTemplate::
288InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
289 ClassTemplatePartialSpecializationDecl *PartialSpec,
290 ArrayRef<TemplateArgument> TemplateArgs,
291 sema::TemplateDeductionInfo &DeductionInfo,
292 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000293 : SemaRef(SemaRef),
294 SavedInNonInstantiationSFINAEContext(
295 SemaRef.InNonInstantiationSFINAEContext)
296{
Richard Smithab91ef12012-07-08 02:38:24 +0000297 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
298 if (!Invalid) {
299 ActiveTemplateInstantiation Inst;
300 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
301 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000302 Inst.Entity = PartialSpec;
Richard Smith7e54fb52012-07-16 01:09:10 +0000303 Inst.TemplateArgs = TemplateArgs.data();
304 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000305 Inst.DeductionInfo = &DeductionInfo;
306 Inst.InstantiationRange = InstantiationRange;
307 SemaRef.InNonInstantiationSFINAEContext = false;
308 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
309 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000310}
311
Larisse Voufoef4579c2013-08-06 01:03:05 +0000312Sema::InstantiatingTemplate::InstantiatingTemplate(
313 Sema &SemaRef, SourceLocation PointOfInstantiation,
314 VarTemplatePartialSpecializationDecl *PartialSpec,
315 ArrayRef<TemplateArgument> TemplateArgs,
316 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
317 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
318 SemaRef.InNonInstantiationSFINAEContext) {
319 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
320 if (!Invalid) {
321 ActiveTemplateInstantiation Inst;
322 Inst.Kind =
323 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
324 Inst.PointOfInstantiation = PointOfInstantiation;
325 Inst.Entity = PartialSpec;
326 Inst.TemplateArgs = TemplateArgs.data();
327 Inst.NumTemplateArgs = TemplateArgs.size();
328 Inst.DeductionInfo = &DeductionInfo;
329 Inst.InstantiationRange = InstantiationRange;
330 SemaRef.InNonInstantiationSFINAEContext = false;
331 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
332 }
333}
334
Richard Smith7e54fb52012-07-16 01:09:10 +0000335Sema::InstantiatingTemplate::
336InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
337 ParmVarDecl *Param,
338 ArrayRef<TemplateArgument> TemplateArgs,
339 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000340 : SemaRef(SemaRef),
341 SavedInNonInstantiationSFINAEContext(
342 SemaRef.InNonInstantiationSFINAEContext)
343{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000344 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000345 if (!Invalid) {
346 ActiveTemplateInstantiation Inst;
347 Inst.Kind
348 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000349 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000350 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000351 Inst.TemplateArgs = TemplateArgs.data();
352 Inst.NumTemplateArgs = TemplateArgs.size();
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000353 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000354 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000355 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000356 }
357}
358
359Sema::InstantiatingTemplate::
360InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000361 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
362 ArrayRef<TemplateArgument> TemplateArgs,
363 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000364 : SemaRef(SemaRef),
365 SavedInNonInstantiationSFINAEContext(
366 SemaRef.InNonInstantiationSFINAEContext)
367{
Richard Smithab91ef12012-07-08 02:38:24 +0000368 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
369 if (!Invalid) {
370 ActiveTemplateInstantiation Inst;
371 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
372 Inst.PointOfInstantiation = PointOfInstantiation;
373 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000374 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000375 Inst.TemplateArgs = TemplateArgs.data();
376 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000377 Inst.InstantiationRange = InstantiationRange;
378 SemaRef.InNonInstantiationSFINAEContext = false;
379 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
380 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000381}
382
383Sema::InstantiatingTemplate::
384InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000385 NamedDecl *Template, TemplateTemplateParmDecl *Param,
386 ArrayRef<TemplateArgument> TemplateArgs,
387 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000388 : SemaRef(SemaRef),
389 SavedInNonInstantiationSFINAEContext(
390 SemaRef.InNonInstantiationSFINAEContext)
391{
Richard Smithab91ef12012-07-08 02:38:24 +0000392 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
393 if (!Invalid) {
394 ActiveTemplateInstantiation Inst;
395 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
396 Inst.PointOfInstantiation = PointOfInstantiation;
397 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000398 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000399 Inst.TemplateArgs = TemplateArgs.data();
400 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000401 Inst.InstantiationRange = InstantiationRange;
402 SemaRef.InNonInstantiationSFINAEContext = false;
403 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
404 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000405}
406
407Sema::InstantiatingTemplate::
408InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000409 TemplateDecl *Template, NamedDecl *Param,
410 ArrayRef<TemplateArgument> TemplateArgs,
411 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000412 : SemaRef(SemaRef),
413 SavedInNonInstantiationSFINAEContext(
414 SemaRef.InNonInstantiationSFINAEContext)
415{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000416 Invalid = false;
417
418 ActiveTemplateInstantiation Inst;
419 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
420 Inst.PointOfInstantiation = PointOfInstantiation;
421 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000422 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000423 Inst.TemplateArgs = TemplateArgs.data();
424 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregorf35f8282009-11-11 21:54:23 +0000425 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000426 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000427 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
428
429 assert(!Inst.isInstantiationRecord());
430 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000431}
432
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000433void Sema::InstantiatingTemplate::Clear() {
434 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000435 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
436 assert(SemaRef.NonInstantiationEntries > 0);
437 --SemaRef.NonInstantiationEntries;
438 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000439 SemaRef.InNonInstantiationSFINAEContext
440 = SavedInNonInstantiationSFINAEContext;
Richard Smithb7751002013-07-25 23:08:39 +0000441
442 // Name lookup no longer looks in this template's defining module.
443 assert(SemaRef.ActiveTemplateInstantiations.size() >=
444 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
445 "forgot to remove a lookup module for a template instantiation");
446 if (SemaRef.ActiveTemplateInstantiations.size() ==
447 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
448 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
449 SemaRef.LookupModulesCache.erase(M);
450 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
451 }
452
Douglas Gregor26dce442009-03-10 00:06:19 +0000453 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000454 Invalid = true;
455 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000456}
457
Douglas Gregordf667e72009-03-10 20:44:00 +0000458bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
459 SourceLocation PointOfInstantiation,
460 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000461 assert(SemaRef.NonInstantiationEntries <=
462 SemaRef.ActiveTemplateInstantiations.size());
463 if ((SemaRef.ActiveTemplateInstantiations.size() -
464 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000465 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000466 return false;
467
Mike Stump1eb44332009-09-09 15:08:12 +0000468 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000469 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000470 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000471 << InstantiationRange;
472 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000473 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000474 return true;
475}
476
Douglas Gregoree1828a2009-03-10 18:03:33 +0000477/// \brief Prints the current instantiation stack through a series of
478/// notes.
479void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000480 // Determine which template instantiations to skip, if any.
481 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
482 unsigned Limit = Diags.getTemplateBacktraceLimit();
483 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
484 SkipStart = Limit / 2 + Limit % 2;
485 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
486 }
487
Douglas Gregorcca9e962009-07-01 22:01:06 +0000488 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000489 unsigned InstantiationIdx = 0;
Craig Topper09d19ef2013-07-04 03:08:24 +0000490 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000491 Active = ActiveTemplateInstantiations.rbegin(),
492 ActiveEnd = ActiveTemplateInstantiations.rend();
493 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000494 ++Active, ++InstantiationIdx) {
495 // Skip this instantiation?
496 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
497 if (InstantiationIdx == SkipStart) {
498 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000499 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000500 diag::note_instantiation_contexts_suppressed)
501 << unsigned(ActiveTemplateInstantiations.size() - Limit);
502 }
503 continue;
504 }
505
Douglas Gregordf667e72009-03-10 20:44:00 +0000506 switch (Active->Kind) {
507 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000508 Decl *D = Active->Entity;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000509 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
510 unsigned DiagID = diag::note_template_member_class_here;
511 if (isa<ClassTemplateSpecializationDecl>(Record))
512 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000513 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000514 << Context.getTypeDeclType(Record)
515 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000516 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000517 unsigned DiagID;
518 if (Function->getPrimaryTemplate())
519 DiagID = diag::note_function_template_spec_here;
520 else
521 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000522 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000523 << Function
524 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000525 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000526 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor7caa6822009-07-24 20:34:43 +0000527 diag::note_template_static_data_member_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000528 << VD
529 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000530 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
531 Diags.Report(Active->PointOfInstantiation,
532 diag::note_template_enum_def_here)
533 << ED
534 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000535 } else {
536 Diags.Report(Active->PointOfInstantiation,
537 diag::note_template_type_alias_instantiation_here)
538 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000539 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000540 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000541 break;
542 }
543
544 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000545 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000546 SmallVector<char, 128> TemplateArgsStr;
547 llvm::raw_svector_ostream OS(TemplateArgsStr);
548 Template->printName(OS);
549 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000550 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000551 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000552 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000553 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000554 diag::note_default_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000555 << OS.str()
Douglas Gregordf667e72009-03-10 20:44:00 +0000556 << Active->InstantiationRange;
557 break;
558 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000559
Douglas Gregorcca9e962009-07-01 22:01:06 +0000560 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000561 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000562 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000563 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000564 << FnTmpl
565 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
566 Active->TemplateArgs,
567 Active->NumTemplateArgs)
568 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000569 break;
570 }
Mike Stump1eb44332009-09-09 15:08:12 +0000571
Douglas Gregorcca9e962009-07-01 22:01:06 +0000572 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000573 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
574 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000575 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000576 diag::note_partial_spec_deduct_instantiation_here)
577 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000578 << getTemplateArgumentBindingsText(
579 PartialSpec->getTemplateParameters(),
580 Active->TemplateArgs,
581 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000582 << Active->InstantiationRange;
583 } else {
584 FunctionTemplateDecl *FnTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000585 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000586 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000587 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000588 << FnTmpl
589 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
590 Active->TemplateArgs,
591 Active->NumTemplateArgs)
592 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000593 }
594 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000595
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000596 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000597 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000598 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Benjamin Kramer5eada842013-02-22 15:46:01 +0000600 SmallVector<char, 128> TemplateArgsStr;
601 llvm::raw_svector_ostream OS(TemplateArgsStr);
602 FD->printName(OS);
603 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000604 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000605 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000606 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000607 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000608 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000609 << OS.str()
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000610 << Active->InstantiationRange;
611 break;
612 }
Mike Stump1eb44332009-09-09 15:08:12 +0000613
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000614 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000615 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000616 std::string Name;
617 if (!Parm->getName().empty())
618 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000619
620 TemplateParameterList *TemplateParams = 0;
621 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
622 TemplateParams = Template->getTemplateParameters();
623 else
624 TemplateParams =
625 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
626 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000627 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000628 diag::note_prior_template_arg_substitution)
629 << isa<TemplateTemplateParmDecl>(Parm)
630 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000631 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000632 Active->TemplateArgs,
633 Active->NumTemplateArgs)
634 << Active->InstantiationRange;
635 break;
636 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000637
638 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000639 TemplateParameterList *TemplateParams = 0;
640 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
641 TemplateParams = Template->getTemplateParameters();
642 else
643 TemplateParams =
644 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
645 ->getTemplateParameters();
646
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000647 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000648 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000649 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000650 Active->TemplateArgs,
651 Active->NumTemplateArgs)
652 << Active->InstantiationRange;
653 break;
654 }
Richard Smithe6975e92012-04-17 00:58:00 +0000655
656 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
657 Diags.Report(Active->PointOfInstantiation,
658 diag::note_template_exception_spec_instantiation_here)
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000659 << cast<FunctionDecl>(Active->Entity)
Richard Smithe6975e92012-04-17 00:58:00 +0000660 << Active->InstantiationRange;
661 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000662 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000663 }
664}
665
David Blaikiedc84cd52013-02-20 22:23:23 +0000666Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000667 if (InNonInstantiationSFINAEContext)
David Blaikiedc84cd52013-02-20 22:23:23 +0000668 return Optional<TemplateDeductionInfo *>(0);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000669
Craig Topper09d19ef2013-07-04 03:08:24 +0000670 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000671 Active = ActiveTemplateInstantiations.rbegin(),
672 ActiveEnd = ActiveTemplateInstantiations.rend();
673 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000674 ++Active)
675 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000676 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000677 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000678 // An instantiation of an alias template may or may not be a SFINAE
679 // context, depending on what else is on the stack.
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000680 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smitha43ea642012-04-26 07:24:08 +0000681 break;
682 // Fall through.
683 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000684 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000685 // This is a template instantiation, so there is no SFINAE.
David Blaikie66874fb2013-02-21 01:47:18 +0000686 return None;
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000688 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000689 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000690 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000691 // A default template argument instantiation and substitution into
692 // template parameters with arguments for prior parameters may or may
693 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000694 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Douglas Gregorcca9e962009-07-01 22:01:06 +0000696 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
697 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
698 // We're either substitution explicitly-specified template arguments
699 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000700 assert(Active->DeductionInfo && "Missing deduction info pointer");
701 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000702 }
703 }
704
David Blaikie66874fb2013-02-21 01:47:18 +0000705 return None;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000706}
707
Douglas Gregord3731192011-01-10 07:32:04 +0000708/// \brief Retrieve the depth and index of a parameter pack.
709static std::pair<unsigned, unsigned>
710getDepthAndIndex(NamedDecl *ND) {
711 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
712 return std::make_pair(TTP->getDepth(), TTP->getIndex());
713
714 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
715 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
716
717 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
718 return std::make_pair(TTP->getDepth(), TTP->getIndex());
719}
720
Douglas Gregor99ebf652009-02-27 19:31:52 +0000721//===----------------------------------------------------------------------===/
722// Template Instantiation for Types
723//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000724namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000725 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000726 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000727 SourceLocation Loc;
728 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000729
Douglas Gregorcd281c32009-02-28 00:25:32 +0000730 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000731 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000732
733 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000734 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000735 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000736 DeclarationName Entity)
737 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000738 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000739
Mike Stump1eb44332009-09-09 15:08:12 +0000740 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000741 /// transformed.
742 ///
743 /// For the purposes of template instantiation, a type has already been
744 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000745 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Douglas Gregor577f75a2009-08-04 16:50:30 +0000747 /// \brief Returns the location of the entity being instantiated, if known.
748 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Douglas Gregor577f75a2009-08-04 16:50:30 +0000750 /// \brief Returns the name of the entity being instantiated, if any.
751 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000753 /// \brief Sets the "base" location and entity when that
754 /// information is known based on another transformation.
755 void setBase(SourceLocation Loc, DeclarationName Entity) {
756 this->Loc = Loc;
757 this->Entity = Entity;
758 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000759
760 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
761 SourceRange PatternRange,
David Blaikiea71f9d02011-09-22 02:34:54 +0000762 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000763 bool &ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000764 bool &RetainExpansion,
David Blaikiedc84cd52013-02-20 22:23:23 +0000765 Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000766 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
767 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000768 TemplateArgs,
769 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000770 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000771 NumExpansions);
772 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000773
Douglas Gregor12c9c002011-01-07 16:43:16 +0000774 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
775 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
776 }
777
Douglas Gregord3731192011-01-10 07:32:04 +0000778 TemplateArgument ForgetPartiallySubstitutedPack() {
779 TemplateArgument Result;
780 if (NamedDecl *PartialPack
781 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
782 MultiLevelTemplateArgumentList &TemplateArgs
783 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
784 unsigned Depth, Index;
785 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
786 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
787 Result = TemplateArgs(Depth, Index);
788 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
789 }
790 }
791
792 return Result;
793 }
794
795 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
796 if (Arg.isNull())
797 return;
798
799 if (NamedDecl *PartialPack
800 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
801 MultiLevelTemplateArgumentList &TemplateArgs
802 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
803 unsigned Depth, Index;
804 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
805 TemplateArgs.setArgument(Depth, Index, Arg);
806 }
807 }
808
Douglas Gregor577f75a2009-08-04 16:50:30 +0000809 /// \brief Transform the given declaration by instantiating a reference to
810 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000811 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000812
Douglas Gregordfca6f52012-02-13 22:00:16 +0000813 void transformAttrs(Decl *Old, Decl *New) {
814 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
815 }
816
817 void transformedLocalDecl(Decl *Old, Decl *New) {
818 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
819 }
820
Mike Stump1eb44332009-09-09 15:08:12 +0000821 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000822 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000823 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000825 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000826 /// declaration.
827 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
828
Douglas Gregor43959a92009-08-20 07:17:43 +0000829 /// \brief Rebuild the exception declaration and register the declaration
830 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000831 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000832 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000833 SourceLocation StartLoc,
834 SourceLocation NameLoc,
835 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000836
Douglas Gregorbe270a02010-04-26 17:57:08 +0000837 /// \brief Rebuild the Objective-C exception declaration and register the
838 /// declaration as an instantiated local.
839 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
840 TypeSourceInfo *TSInfo, QualType T);
841
John McCallc4e70192009-09-11 04:59:25 +0000842 /// \brief Check for tag mismatches when instantiating an
843 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000844 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
845 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000846 NestedNameSpecifierLoc QualifierLoc,
847 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000848
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000849 TemplateName TransformTemplateName(CXXScopeSpec &SS,
850 TemplateName Name,
851 SourceLocation NameLoc,
852 QualType ObjectType = QualType(),
853 NamedDecl *FirstQualifierInScope = 0);
854
John McCall60d7b3a2010-08-24 06:29:42 +0000855 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
856 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
857 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000858
John McCall60d7b3a2010-08-24 06:29:42 +0000859 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000860 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000861 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
862 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000863
864 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
865 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
866
867 /// \brief Transform a reference to a function parameter pack.
868 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
869 ParmVarDecl *PD);
870
871 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
872 /// expand a function parameter pack reference which refers to an expanded
873 /// pack.
874 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
875
Douglas Gregor895162d2010-04-30 18:55:50 +0000876 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000877 FunctionProtoTypeLoc TL);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000878 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
879 FunctionProtoTypeLoc TL,
880 CXXRecordDecl *ThisContext,
881 unsigned ThisTypeQuals);
882
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000883 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000884 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +0000885 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000886 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000887
Mike Stump1eb44332009-09-09 15:08:12 +0000888 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000889 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000890 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000891 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000892
Douglas Gregorc3069d62011-01-14 02:55:32 +0000893 /// \brief Transforms an already-substituted template type parameter pack
894 /// into either itself (if we aren't substituting into its pack expansion)
895 /// or the appropriate substituted argument.
896 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
897 SubstTemplateTypeParmPackTypeLoc TL);
898
John McCall60d7b3a2010-08-24 06:29:42 +0000899 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000900 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000901 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000902 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
903 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000904 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000905 }
John McCall91a57552011-07-15 05:09:51 +0000906
Richard Smith612409e2012-07-25 03:56:55 +0000907 ExprResult TransformLambdaExpr(LambdaExpr *E) {
908 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
909 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
910 }
911
912 ExprResult TransformLambdaScope(LambdaExpr *E,
913 CXXMethodDecl *CallOperator) {
914 CallOperator->setInstantiationOfMemberFunction(E->getCallOperator(),
915 TSK_ImplicitInstantiation);
916 return TreeTransform<TemplateInstantiator>::
917 TransformLambdaScope(E, CallOperator);
918 }
919
John McCall91a57552011-07-15 05:09:51 +0000920 private:
921 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
922 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000923 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000924 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000925}
926
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000927bool TemplateInstantiator::AlreadyTransformed(QualType T) {
928 if (T.isNull())
929 return true;
930
Douglas Gregor561f8122011-07-01 01:22:09 +0000931 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000932 return false;
933
934 getSema().MarkDeclarationsReferencedInType(Loc, T);
935 return true;
936}
937
Eli Friedman10ec0e42013-07-19 19:40:38 +0000938static TemplateArgument
939getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
940 assert(S.ArgumentPackSubstitutionIndex >= 0);
941 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
942 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
943 if (Arg.isPackExpansion())
944 Arg = Arg.getPackExpansionPattern();
945 return Arg;
946}
947
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000948Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000949 if (!D)
950 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000951
Douglas Gregorc68afe22009-09-03 21:38:09 +0000952 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000953 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000954 // If the corresponding template argument is NULL or non-existent, it's
955 // because we are performing instantiation from explicitly-specified
956 // template arguments in a function template, but there were some
957 // arguments left unspecified.
958 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
959 TTP->getPosition()))
960 return D;
961
Douglas Gregor61c4d282011-01-05 15:48:55 +0000962 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
963
964 if (TTP->isParameterPack()) {
965 assert(Arg.getKind() == TemplateArgument::Pack &&
966 "Missing argument pack");
Eli Friedman10ec0e42013-07-19 19:40:38 +0000967 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000968 }
969
970 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000971 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000972 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000973 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000974 }
Mike Stump1eb44332009-09-09 15:08:12 +0000975
Douglas Gregor788cd062009-11-11 01:00:40 +0000976 // Fall through to find the instantiated declaration for this template
977 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000978 }
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000980 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000981}
982
Douglas Gregoraac571c2010-03-01 17:25:41 +0000983Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000984 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000985 if (!Inst)
986 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000987
Douglas Gregor43959a92009-08-20 07:17:43 +0000988 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
989 return Inst;
990}
991
Douglas Gregor6cd21982009-10-20 05:58:46 +0000992NamedDecl *
993TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
994 SourceLocation Loc) {
995 // If the first part of the nested-name-specifier was a template type
996 // parameter, instantiate that type parameter down to a tag type.
997 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
998 const TemplateTypeParmType *TTP
999 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +00001000
Douglas Gregor6cd21982009-10-20 05:58:46 +00001001 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +00001002 // FIXME: This needs testing w/ member access expressions.
1003 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1004
1005 if (TTP->isParameterPack()) {
1006 assert(Arg.getKind() == TemplateArgument::Pack &&
1007 "Missing argument pack");
1008
Douglas Gregor2be29f42011-01-14 23:41:42 +00001009 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +00001010 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +00001011
Eli Friedman10ec0e42013-07-19 19:40:38 +00001012 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor984a58b2010-12-20 22:48:17 +00001013 }
1014
1015 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +00001016 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001017 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +00001018
1019 if (const TagType *Tag = T->getAs<TagType>())
1020 return Tag->getDecl();
1021
1022 // The resulting type is not a tag; complain.
1023 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1024 return 0;
1025 }
1026 }
1027
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001028 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +00001029}
1030
Douglas Gregor43959a92009-08-20 07:17:43 +00001031VarDecl *
1032TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +00001033 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001034 SourceLocation StartLoc,
1035 SourceLocation NameLoc,
1036 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001037 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001038 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +00001039 if (Var)
1040 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1041 return Var;
1042}
1043
1044VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1045 TypeSourceInfo *TSInfo,
1046 QualType T) {
1047 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1048 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +00001049 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1050 return Var;
1051}
1052
John McCallc4e70192009-09-11 04:59:25 +00001053QualType
John McCall21e413f2010-11-04 19:04:38 +00001054TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1055 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001056 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001057 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +00001058 if (const TagType *TT = T->getAs<TagType>()) {
1059 TagDecl* TD = TT->getDecl();
1060
John McCall21e413f2010-11-04 19:04:38 +00001061 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001062
John McCallc4e70192009-09-11 04:59:25 +00001063 IdentifierInfo *Id = TD->getIdentifier();
1064
1065 // TODO: should we even warn on struct/class mismatches for this? Seems
1066 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001067 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001068 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001069 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1070 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001071 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1072 << Id
1073 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1074 TD->getKindName());
1075 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1076 }
John McCallc4e70192009-09-11 04:59:25 +00001077 }
1078 }
1079
John McCall21e413f2010-11-04 19:04:38 +00001080 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1081 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001082 QualifierLoc,
1083 T);
John McCallc4e70192009-09-11 04:59:25 +00001084}
1085
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001086TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1087 TemplateName Name,
1088 SourceLocation NameLoc,
1089 QualType ObjectType,
1090 NamedDecl *FirstQualifierInScope) {
1091 if (TemplateTemplateParmDecl *TTP
1092 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1093 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1094 // If the corresponding template argument is NULL or non-existent, it's
1095 // because we are performing instantiation from explicitly-specified
1096 // template arguments in a function template, but there were some
1097 // arguments left unspecified.
1098 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1099 TTP->getPosition()))
1100 return Name;
1101
1102 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1103
1104 if (TTP->isParameterPack()) {
1105 assert(Arg.getKind() == TemplateArgument::Pack &&
1106 "Missing argument pack");
1107
1108 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1109 // We have the template argument pack to substitute, but we're not
1110 // actually expanding the enclosing pack expansion yet. So, just
1111 // keep the entire argument pack.
1112 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1113 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001114
1115 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001116 }
1117
1118 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001119 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001120
Douglas Gregor58750382011-03-05 20:06:51 +00001121 // We don't ever want to substitute for a qualified template name, since
1122 // the qualifier is handled separately. So, look through the qualified
1123 // template name to its underlying declaration.
1124 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1125 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001126
1127 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001128 return Template;
1129 }
1130 }
1131
1132 if (SubstTemplateTemplateParmPackStorage *SubstPack
1133 = Name.getAsSubstTemplateTemplateParmPack()) {
1134 if (getSema().ArgumentPackSubstitutionIndex == -1)
1135 return Name;
1136
Eli Friedman10ec0e42013-07-19 19:40:38 +00001137 TemplateArgument Arg = SubstPack->getArgumentPack();
1138 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1139 return Arg.getAsTemplate();
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001140 }
1141
1142 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1143 FirstQualifierInScope);
1144}
1145
John McCall60d7b3a2010-08-24 06:29:42 +00001146ExprResult
John McCall454feb92009-12-08 09:21:05 +00001147TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001148 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001149 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001150
1151 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1152 assert(currentDecl && "Must have current function declaration when "
1153 "instantiating.");
1154
1155 PredefinedExpr::IdentType IT = E->getIdentType();
1156
Anders Carlsson848fa642010-02-11 18:20:28 +00001157 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson773f3972009-09-11 01:22:35 +00001158
1159 llvm::APInt LengthI(32, Length + 1);
Nico Weberb4e80082012-06-25 22:34:48 +00001160 QualType ResTy;
1161 if (IT == PredefinedExpr::LFunction)
Hans Wennborg15f92ba2013-05-10 10:08:40 +00001162 ResTy = getSema().Context.WideCharTy.withConst();
Nico Weberb4e80082012-06-25 22:34:48 +00001163 else
1164 ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001165 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1166 ArrayType::Normal, 0);
1167 PredefinedExpr *PE =
1168 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1169 return getSema().Owned(PE);
1170}
1171
John McCall60d7b3a2010-08-24 06:29:42 +00001172ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001173TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001174 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001175 // If the corresponding template argument is NULL or non-existent, it's
1176 // because we are performing instantiation from explicitly-specified
1177 // template arguments in a function template, but there were some
1178 // arguments left unspecified.
1179 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1180 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001181 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Douglas Gregor56bc9832010-12-24 00:15:10 +00001183 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1184 if (NTTP->isParameterPack()) {
1185 assert(Arg.getKind() == TemplateArgument::Pack &&
1186 "Missing argument pack");
1187
1188 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001189 // We have an argument pack, but we can't select a particular argument
1190 // out of it yet. Therefore, we'll build an expression to hold on to that
1191 // argument pack.
1192 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1193 E->getLocation(),
1194 NTTP->getDeclName());
1195 if (TargetType.isNull())
1196 return ExprError();
1197
1198 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1199 NTTP,
1200 E->getLocation(),
1201 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001202 }
1203
Eli Friedman10ec0e42013-07-19 19:40:38 +00001204 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001205 }
Mike Stump1eb44332009-09-09 15:08:12 +00001206
John McCall91a57552011-07-15 05:09:51 +00001207 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1208}
1209
1210ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1211 NonTypeTemplateParmDecl *parm,
1212 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001213 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001214 ExprResult result;
1215 QualType type;
1216
John McCallb8fc0532010-02-06 08:42:39 +00001217 // The template argument itself might be an expression, in which
1218 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001219 if (arg.getKind() == TemplateArgument::Expression) {
1220 Expr *argExpr = arg.getAsExpr();
1221 result = SemaRef.Owned(argExpr);
1222 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001223
Eli Friedmand7a6b162012-09-26 02:36:12 +00001224 } else if (arg.getKind() == TemplateArgument::Declaration ||
1225 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001226 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001227 if (arg.getKind() == TemplateArgument::Declaration) {
1228 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001229
Douglas Gregord2008e22012-04-06 22:40:38 +00001230 // Find the instantiation of the template argument. This is
1231 // required for nested templates.
1232 VD = cast_or_null<ValueDecl>(
1233 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1234 if (!VD)
1235 return ExprError();
1236 } else {
1237 // Propagate NULL template argument.
1238 VD = 0;
1239 }
1240
John McCall645cf442010-02-06 10:23:53 +00001241 // Derive the type we want the substituted decl to have. This had
1242 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001243 if (parm->isExpandedParameterPack()) {
1244 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1245 } else if (parm->isParameterPack() &&
1246 isa<PackExpansionType>(parm->getType())) {
1247 type = SemaRef.SubstType(
1248 cast<PackExpansionType>(parm->getType())->getPattern(),
1249 TemplateArgs, loc, parm->getDeclName());
1250 } else {
1251 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1252 loc, parm->getDeclName());
1253 }
1254 assert(!type.isNull() && "type substitution failed for param type");
1255 assert(!type->isDependentType() && "param type still dependent");
1256 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001257
John McCall91a57552011-07-15 05:09:51 +00001258 if (!result.isInvalid()) type = result.get()->getType();
1259 } else {
1260 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1261
1262 // Note that this type can be different from the type of 'result',
1263 // e.g. if it's an enum type.
1264 type = arg.getIntegralType();
1265 }
1266 if (result.isInvalid()) return ExprError();
1267
1268 Expr *resultExpr = result.take();
1269 return SemaRef.Owned(new (SemaRef.Context)
1270 SubstNonTypeTemplateParmExpr(type,
1271 resultExpr->getValueKind(),
1272 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001273}
1274
Douglas Gregorc7793c72011-01-15 01:15:58 +00001275ExprResult
1276TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1277 SubstNonTypeTemplateParmPackExpr *E) {
1278 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1279 // We aren't expanding the parameter pack, so just return ourselves.
1280 return getSema().Owned(E);
1281 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001282
1283 TemplateArgument Arg = E->getArgumentPack();
1284 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall91a57552011-07-15 05:09:51 +00001285 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1286 E->getParameterPackLocation(),
1287 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001288}
John McCallb8fc0532010-02-06 08:42:39 +00001289
John McCall60d7b3a2010-08-24 06:29:42 +00001290ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001291TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1292 SourceLocation Loc) {
1293 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1294 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1295}
1296
1297ExprResult
1298TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1299 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1300 // We can expand this parameter pack now.
1301 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1302 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1303 if (!VD)
1304 return ExprError();
1305 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1306 }
1307
1308 QualType T = TransformType(E->getType());
1309 if (T.isNull())
1310 return ExprError();
1311
1312 // Transform each of the parameter expansions into the corresponding
1313 // parameters in the instantiation of the function decl.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001314 SmallVector<Decl *, 8> Parms;
Richard Smith9a4db032012-09-12 00:56:43 +00001315 Parms.reserve(E->getNumExpansions());
1316 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1317 I != End; ++I) {
1318 ParmVarDecl *D =
1319 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1320 if (!D)
1321 return ExprError();
1322 Parms.push_back(D);
1323 }
1324
1325 return FunctionParmPackExpr::Create(getSema().Context, T,
1326 E->getParameterPack(),
1327 E->getParameterPackLocation(), Parms);
1328}
1329
1330ExprResult
1331TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1332 ParmVarDecl *PD) {
1333 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1334 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1335 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1336 assert(Found && "no instantiation for parameter pack");
1337
1338 Decl *TransformedDecl;
1339 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1340 // If this is a reference to a function parameter pack which we can substitute
1341 // but can't yet expand, build a FunctionParmPackExpr for it.
1342 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1343 QualType T = TransformType(E->getType());
1344 if (T.isNull())
1345 return ExprError();
1346 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1347 E->getExprLoc(), *Pack);
1348 }
1349
1350 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1351 } else {
1352 TransformedDecl = Found->get<Decl*>();
1353 }
1354
1355 // We have either an unexpanded pack or a specific expansion.
1356 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1357 E->getExprLoc());
1358}
1359
1360ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001361TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1362 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001363
1364 // Handle references to non-type template parameters and non-type template
1365 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001366 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1367 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1368 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001369
1370 // We have a non-type template parameter that isn't fully substituted;
1371 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001372 }
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Richard Smith9a4db032012-09-12 00:56:43 +00001374 // Handle references to function parameter packs.
1375 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1376 if (PD->isParameterPack())
1377 return TransformFunctionParmPackRefExpr(E, PD);
1378
John McCall454feb92009-12-08 09:21:05 +00001379 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001380}
1381
John McCall60d7b3a2010-08-24 06:29:42 +00001382ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001383 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001384 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1385 getDescribedFunctionTemplate() &&
1386 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001387 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1388 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1389 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001390}
1391
Douglas Gregor895162d2010-04-30 18:55:50 +00001392QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001393 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001394 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001395 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001396 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001397}
1398
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001399QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1400 FunctionProtoTypeLoc TL,
1401 CXXRecordDecl *ThisContext,
1402 unsigned ThisTypeQuals) {
1403 // We need a local instantiation scope for this function prototype.
1404 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1405 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1406 ThisTypeQuals);
1407}
1408
John McCall21ef0fa2010-03-11 09:03:00 +00001409ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001410TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001411 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001412 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001413 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001414 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001415 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001416}
1417
Mike Stump1eb44332009-09-09 15:08:12 +00001418QualType
John McCalla2becad2009-10-21 00:40:46 +00001419TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001420 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001421 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001422 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001423 // Replace the template type parameter with its corresponding
1424 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001425
1426 // If the corresponding template argument is NULL or doesn't exist, it's
1427 // because we are performing instantiation from explicitly-specified
1428 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001429 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001430 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1431 TemplateTypeParmTypeLoc NewTL
1432 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1433 NewTL.setNameLoc(TL.getNameLoc());
1434 return TL.getType();
1435 }
Mike Stump1eb44332009-09-09 15:08:12 +00001436
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001437 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1438
1439 if (T->isParameterPack()) {
1440 assert(Arg.getKind() == TemplateArgument::Pack &&
1441 "Missing argument pack");
1442
1443 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001444 // We have the template argument pack, but we're not expanding the
1445 // enclosing pack expansion yet. Just save the template argument
1446 // pack for later substitution.
1447 QualType Result
1448 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1449 SubstTemplateTypeParmPackTypeLoc NewTL
1450 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1451 NewTL.setNameLoc(TL.getNameLoc());
1452 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001453 }
1454
Eli Friedman10ec0e42013-07-19 19:40:38 +00001455 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001456 }
1457
1458 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001459 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001460
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001461 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001462
1463 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001464 QualType Result
1465 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1466 SubstTemplateTypeParmTypeLoc NewTL
1467 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1468 NewTL.setNameLoc(TL.getNameLoc());
1469 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001470 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001471
1472 // The template type parameter comes from an inner template (e.g.,
1473 // the template parameter list of a member template inside the
1474 // template we are instantiating). Create a new template type
1475 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001476 TemplateTypeParmDecl *NewTTPDecl = 0;
1477 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1478 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1479 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1480
John McCalla2becad2009-10-21 00:40:46 +00001481 QualType Result
1482 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1483 - TemplateArgs.getNumLevels(),
1484 T->getIndex(),
1485 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001486 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001487 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1488 NewTL.setNameLoc(TL.getNameLoc());
1489 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001490}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001491
Douglas Gregorc3069d62011-01-14 02:55:32 +00001492QualType
1493TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1494 TypeLocBuilder &TLB,
1495 SubstTemplateTypeParmPackTypeLoc TL) {
1496 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1497 // We aren't expanding the parameter pack, so just return ourselves.
1498 SubstTemplateTypeParmPackTypeLoc NewTL
1499 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1500 NewTL.setNameLoc(TL.getNameLoc());
1501 return TL.getType();
1502 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001503
1504 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1505 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1506 QualType Result = Arg.getAsType();
1507
Douglas Gregorc3069d62011-01-14 02:55:32 +00001508 Result = getSema().Context.getSubstTemplateTypeParmType(
1509 TL.getTypePtr()->getReplacedParameter(),
1510 Result);
1511 SubstTemplateTypeParmTypeLoc NewTL
1512 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1513 NewTL.setNameLoc(TL.getNameLoc());
1514 return Result;
1515}
1516
John McCallce3ff2b2009-08-25 22:02:44 +00001517/// \brief Perform substitution on the type T with a given set of template
1518/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001519///
1520/// This routine substitutes the given template arguments into the
1521/// type T and produces the instantiated type.
1522///
1523/// \param T the type into which the template arguments will be
1524/// substituted. If this type is not dependent, it will be returned
1525/// immediately.
1526///
James Dennett1dfbd922012-06-14 21:40:34 +00001527/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001528/// substituted for the top-level template parameters within T.
1529///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001530/// \param Loc the location in the source code where this substitution
1531/// is being performed. It will typically be the location of the
1532/// declarator (if we're instantiating the type of some declaration)
1533/// or the location of the type in the source code (if, e.g., we're
1534/// instantiating the type of a cast expression).
1535///
1536/// \param Entity the name of the entity associated with a declaration
1537/// being instantiated (if any). May be empty to indicate that there
1538/// is no such entity (if, e.g., this is a type that occurs as part of
1539/// a cast expression) or that the entity has no name (e.g., an
1540/// unnamed function parameter).
1541///
1542/// \returns If the instantiation succeeds, the instantiated
1543/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001544TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001545 const MultiLevelTemplateArgumentList &Args,
1546 SourceLocation Loc,
1547 DeclarationName Entity) {
1548 assert(!ActiveTemplateInstantiations.empty() &&
1549 "Cannot perform an instantiation without some context on the "
1550 "instantiation stack");
1551
Douglas Gregor561f8122011-07-01 01:22:09 +00001552 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001553 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001554 return T;
1555
1556 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1557 return Instantiator.TransformType(T);
1558}
1559
Douglas Gregor603cfb42011-01-05 23:12:31 +00001560TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1561 const MultiLevelTemplateArgumentList &Args,
1562 SourceLocation Loc,
1563 DeclarationName Entity) {
1564 assert(!ActiveTemplateInstantiations.empty() &&
1565 "Cannot perform an instantiation without some context on the "
1566 "instantiation stack");
1567
1568 if (TL.getType().isNull())
1569 return 0;
1570
Douglas Gregor561f8122011-07-01 01:22:09 +00001571 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001572 !TL.getType()->isVariablyModifiedType()) {
1573 // FIXME: Make a copy of the TypeLoc data here, so that we can
1574 // return a new TypeSourceInfo. Inefficient!
1575 TypeLocBuilder TLB;
1576 TLB.pushFullCopy(TL);
1577 return TLB.getTypeSourceInfo(Context, TL.getType());
1578 }
1579
1580 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1581 TypeLocBuilder TLB;
1582 TLB.reserve(TL.getFullDataSize());
1583 QualType Result = Instantiator.TransformType(TLB, TL);
1584 if (Result.isNull())
1585 return 0;
1586
1587 return TLB.getTypeSourceInfo(Context, Result);
1588}
1589
John McCallcd7ba1c2009-10-21 00:58:09 +00001590/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001591QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001592 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001593 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001594 assert(!ActiveTemplateInstantiations.empty() &&
1595 "Cannot perform an instantiation without some context on the "
1596 "instantiation stack");
1597
Douglas Gregor836adf62010-05-24 17:22:01 +00001598 // If T is not a dependent type or a variably-modified type, there
1599 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001600 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001601 return T;
1602
Douglas Gregor577f75a2009-08-04 16:50:30 +00001603 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1604 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001605}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001606
John McCall6cd3b9f2010-04-09 17:38:44 +00001607static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001608 if (T->getType()->isInstantiationDependentType() ||
1609 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001610 return true;
1611
Abramo Bagnara723df242010-12-14 22:11:44 +00001612 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00001613 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCall6cd3b9f2010-04-09 17:38:44 +00001614 return false;
1615
David Blaikie39e6ab42013-02-18 22:06:02 +00001616 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
John McCall6cd3b9f2010-04-09 17:38:44 +00001617 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1618 ParmVarDecl *P = FP.getArg(I);
1619
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001620 // This must be synthesized from a typedef.
1621 if (!P) continue;
1622
Douglas Gregorc056c172011-05-09 20:45:16 +00001623 // The parameter's type as written might be dependent even if the
1624 // decayed type was not dependent.
1625 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001626 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001627 return true;
1628
John McCall6cd3b9f2010-04-09 17:38:44 +00001629 // TODO: currently we always rebuild expressions. When we
1630 // properly get lazier about this, we should use the same
1631 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001632 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001633 return true;
1634 }
1635
1636 return false;
1637}
1638
1639/// A form of SubstType intended specifically for instantiating the
1640/// type of a FunctionDecl. Its purpose is solely to force the
1641/// instantiation of default-argument expressions.
1642TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1643 const MultiLevelTemplateArgumentList &Args,
1644 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001645 DeclarationName Entity,
1646 CXXRecordDecl *ThisContext,
1647 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001648 assert(!ActiveTemplateInstantiations.empty() &&
1649 "Cannot perform an instantiation without some context on the "
1650 "instantiation stack");
1651
1652 if (!NeedsInstantiationAsFunctionType(T))
1653 return T;
1654
1655 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1656
1657 TypeLocBuilder TLB;
1658
1659 TypeLoc TL = T->getTypeLoc();
1660 TLB.reserve(TL.getFullDataSize());
1661
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001662 QualType Result;
David Blaikie39e6ab42013-02-18 22:06:02 +00001663
1664 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1665 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001666 ThisTypeQuals);
1667 } else {
1668 Result = Instantiator.TransformType(TLB, TL);
1669 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001670 if (Result.isNull())
1671 return 0;
1672
1673 return TLB.getTypeSourceInfo(Context, Result);
1674}
1675
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001676ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001677 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001678 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001679 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001680 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001681 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001682 TypeSourceInfo *NewDI = 0;
1683
Douglas Gregor603cfb42011-01-05 23:12:31 +00001684 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00001685 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1686
Douglas Gregor603cfb42011-01-05 23:12:31 +00001687 // We have a function parameter pack. Substitute into the pattern of the
1688 // expansion.
1689 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1690 OldParm->getLocation(), OldParm->getDeclName());
1691 if (!NewDI)
1692 return 0;
1693
1694 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1695 // We still have unexpanded parameter packs, which means that
1696 // our function parameter is still a function parameter pack.
1697 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001698 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001699 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001700 } else if (ExpectParameterPack) {
1701 // We expected to get a parameter pack but didn't (because the type
1702 // itself is not a pack expansion type), so complain. This can occur when
1703 // the substitution goes through an alias template that "loses" the
1704 // pack expansion.
1705 Diag(OldParm->getLocation(),
1706 diag::err_function_parameter_pack_without_parameter_packs)
1707 << NewDI->getType();
1708 return 0;
1709 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001710 } else {
1711 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1712 OldParm->getDeclName());
1713 }
1714
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001715 if (!NewDI)
1716 return 0;
1717
1718 if (NewDI->getType()->isVoidType()) {
1719 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1720 return 0;
1721 }
1722
1723 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001724 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001725 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001726 OldParm->getIdentifier(),
1727 NewDI->getType(), NewDI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001728 OldParm->getStorageClass());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001729 if (!NewParm)
1730 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001731
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001732 // Mark the (new) default argument as uninstantiated (if any).
1733 if (OldParm->hasUninstantiatedDefaultArg()) {
1734 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1735 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001736 } else if (OldParm->hasUnparsedDefaultArg()) {
1737 NewParm->setUnparsedDefaultArg();
1738 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001739 } else if (Expr *Arg = OldParm->getDefaultArg())
1740 // FIXME: if we non-lazily instantiated non-dependent default args for
1741 // non-dependent parameter types we could remove a bunch of duplicate
1742 // conversion warnings for such arguments.
1743 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001744
1745 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001746
Douglas Gregor12c9c002011-01-07 16:43:16 +00001747 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001748 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001749 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1750 } else {
1751 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001752 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001753 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001754
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001755 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1756 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001757 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001758
1759 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1760 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rose09189892013-03-08 22:25:36 +00001761
1762 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1763
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001764 return NewParm;
1765}
1766
Douglas Gregora009b592011-01-07 00:20:55 +00001767/// \brief Substitute the given template arguments into the given set of
1768/// parameters, producing the set of parameter types that would be generated
1769/// from such a substitution.
1770bool Sema::SubstParmTypes(SourceLocation Loc,
1771 ParmVarDecl **Params, unsigned NumParams,
1772 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001773 SmallVectorImpl<QualType> &ParamTypes,
1774 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001775 assert(!ActiveTemplateInstantiations.empty() &&
1776 "Cannot perform an instantiation without some context on the "
1777 "instantiation stack");
1778
1779 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1780 DeclarationName());
1781 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001782 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001783}
1784
John McCallce3ff2b2009-08-25 22:02:44 +00001785/// \brief Perform substitution on the base class specifiers of the
1786/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001787///
1788/// Produces a diagnostic and returns true on error, returns false and
1789/// attaches the instantiated base classes to the class template
1790/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001791bool
John McCallce3ff2b2009-08-25 22:02:44 +00001792Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1793 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001794 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001795 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001796 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001797 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001798 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001799 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001800 if (!Base->getType()->isDependentType()) {
Matt Beaumont-Gay538fccb2013-06-21 18:58:32 +00001801 if (const CXXRecordDecl *RD = Base->getType()->getAsCXXRecordDecl()) {
1802 if (RD->isInvalidDecl())
1803 Instantiation->setInvalidDecl();
1804 }
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001805 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001806 continue;
1807 }
1808
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001809 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001810 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001811 if (Base->isPackExpansion()) {
1812 // This is a pack expansion. See whether we should expand it now, or
1813 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001814 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001815 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1816 Unexpanded);
1817 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001818 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001819 Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001820 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1821 Base->getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001822 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001823 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001824 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001825 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001826 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001827 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001828 }
1829
1830 // If we should expand this pack expansion now, do so.
1831 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001832 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001833 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1834
1835 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1836 TemplateArgs,
1837 Base->getSourceRange().getBegin(),
1838 DeclarationName());
1839 if (!BaseTypeLoc) {
1840 Invalid = true;
1841 continue;
1842 }
1843
1844 if (CXXBaseSpecifier *InstantiatedBase
1845 = CheckBaseSpecifier(Instantiation,
1846 Base->getSourceRange(),
1847 Base->isVirtual(),
1848 Base->getAccessSpecifierAsWritten(),
1849 BaseTypeLoc,
1850 SourceLocation()))
1851 InstantiatedBases.push_back(InstantiatedBase);
1852 else
1853 Invalid = true;
1854 }
1855
1856 continue;
1857 }
1858
1859 // The resulting base specifier will (still) be a pack expansion.
1860 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001861 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1862 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1863 TemplateArgs,
1864 Base->getSourceRange().getBegin(),
1865 DeclarationName());
1866 } else {
1867 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1868 TemplateArgs,
1869 Base->getSourceRange().getBegin(),
1870 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001871 }
1872
Nick Lewycky56062202010-07-26 16:56:01 +00001873 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001874 Invalid = true;
1875 continue;
1876 }
1877
1878 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001879 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001880 Base->getSourceRange(),
1881 Base->isVirtual(),
1882 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001883 BaseTypeLoc,
1884 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001885 InstantiatedBases.push_back(InstantiatedBase);
1886 else
1887 Invalid = true;
1888 }
1889
Douglas Gregor27b152f2009-03-10 18:52:44 +00001890 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001891 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001892 InstantiatedBases.size()))
1893 Invalid = true;
1894
1895 return Invalid;
1896}
1897
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001898// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001899namespace clang {
1900 namespace sema {
1901 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1902 const MultiLevelTemplateArgumentList &TemplateArgs);
1903 }
1904}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001905
Richard Smithf1c66b42012-03-14 23:13:10 +00001906/// Determine whether we would be unable to instantiate this template (because
1907/// it either has no definition, or is in the process of being instantiated).
1908static bool DiagnoseUninstantiableTemplate(Sema &S,
1909 SourceLocation PointOfInstantiation,
1910 TagDecl *Instantiation,
1911 bool InstantiatedFromMember,
1912 TagDecl *Pattern,
1913 TagDecl *PatternDef,
1914 TemplateSpecializationKind TSK,
1915 bool Complain = true) {
1916 if (PatternDef && !PatternDef->isBeingDefined())
1917 return false;
1918
1919 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1920 // Say nothing
1921 } else if (PatternDef) {
1922 assert(PatternDef->isBeingDefined());
1923 S.Diag(PointOfInstantiation,
1924 diag::err_template_instantiate_within_definition)
1925 << (TSK != TSK_ImplicitInstantiation)
1926 << S.Context.getTypeDeclType(Instantiation);
1927 // Not much point in noting the template declaration here, since
1928 // we're lexically inside it.
1929 Instantiation->setInvalidDecl();
1930 } else if (InstantiatedFromMember) {
1931 S.Diag(PointOfInstantiation,
1932 diag::err_implicit_instantiate_member_undefined)
1933 << S.Context.getTypeDeclType(Instantiation);
1934 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1935 } else {
1936 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1937 << (TSK != TSK_ImplicitInstantiation)
1938 << S.Context.getTypeDeclType(Instantiation);
1939 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1940 }
1941
1942 // In general, Instantiation isn't marked invalid to get more than one
1943 // error for multiple undefined instantiations. But the code that does
1944 // explicit declaration -> explicit definition conversion can't handle
1945 // invalid declarations, so mark as invalid in that case.
1946 if (TSK == TSK_ExplicitInstantiationDeclaration)
1947 Instantiation->setInvalidDecl();
1948 return true;
1949}
1950
Douglas Gregord475b8d2009-03-25 21:17:03 +00001951/// \brief Instantiate the definition of a class from a given pattern.
1952///
1953/// \param PointOfInstantiation The point of instantiation within the
1954/// source code.
1955///
1956/// \param Instantiation is the declaration whose definition is being
1957/// instantiated. This will be either a class template specialization
1958/// or a member class of a class template specialization.
1959///
1960/// \param Pattern is the pattern from which the instantiation
1961/// occurs. This will be either the declaration of a class template or
1962/// the declaration of a member class of a class template.
1963///
1964/// \param TemplateArgs The template arguments to be substituted into
1965/// the pattern.
1966///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001967/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001968///
1969/// \param Complain whether to complain if the class cannot be instantiated due
1970/// to the lack of a definition.
1971///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001972/// \returns true if an error occurred, false otherwise.
1973bool
1974Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1975 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001976 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001977 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001978 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00001979 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001980 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001981 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1982 Instantiation->getInstantiatedFromMemberClass(),
1983 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001984 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001985 Pattern = PatternDef;
1986
Douglas Gregor454885e2009-10-15 15:54:05 +00001987 // \brief Record the point of instantiation.
1988 if (MemberSpecializationInfo *MSInfo
1989 = Instantiation->getMemberSpecializationInfo()) {
1990 MSInfo->setTemplateSpecializationKind(TSK);
1991 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001992 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001993 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001994 Spec->setTemplateSpecializationKind(TSK);
1995 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001996 }
1997
Douglas Gregord048bb72009-03-25 21:23:52 +00001998 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001999 if (Inst)
2000 return true;
2001
2002 // Enter the scope of this instantiation. We don't use
2003 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00002004 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00002005 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002006 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002007
Douglas Gregor05030bb2010-03-24 01:33:17 +00002008 // If this is an instantiation of a local class, merge this local
2009 // instantiation scope with the enclosing scope. Otherwise, every
2010 // instantiation of a class has its own local instantiation scope.
2011 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00002012 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00002013
John McCall1d8d1cc2010-08-01 02:01:53 +00002014 // Pull attributes from the pattern onto the instantiation.
2015 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2016
Douglas Gregord475b8d2009-03-25 21:17:03 +00002017 // Start the definition of this instantiation.
2018 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00002019
2020 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00002021
John McCallce3ff2b2009-08-25 22:02:44 +00002022 // Do substitution on the base class specifiers.
2023 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002024 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002025
Douglas Gregord65587f2010-11-10 19:44:59 +00002026 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002027 SmallVector<Decl*, 4> Fields;
2028 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00002029 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002030 // Delay instantiation of late parsed attributes.
2031 LateInstantiatedAttrVec LateAttrs;
2032 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2033
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002034 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002035 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002036 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00002037 // Don't instantiate members not belonging in this semantic context.
2038 // e.g. for:
2039 // @code
2040 // template <int i> class A {
2041 // class B *g;
2042 // };
2043 // @endcode
2044 // 'class B' has the template as lexical context but semantically it is
2045 // introduced in namespace scope.
2046 if ((*Member)->getDeclContext() != Pattern)
2047 continue;
2048
Douglas Gregord65587f2010-11-10 19:44:59 +00002049 if ((*Member)->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00002050 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002051 continue;
2052 }
2053
2054 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002055 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00002056 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00002057 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00002058 FieldDecl *OldField = cast<FieldDecl>(*Member);
2059 if (OldField->getInClassInitializer())
2060 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2061 Field));
Richard Smith1af83c42012-03-23 03:33:32 +00002062 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2063 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2064 // specialization causes the implicit instantiation of the definitions
2065 // of unscoped member enumerations.
2066 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00002067 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2068 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00002069 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2070 assert(MSInfo && "no spec info for member enum specialization");
2071 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2072 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2073 }
Richard Smithe3f470a2012-07-11 22:37:56 +00002074 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2075 if (SA->isFailed()) {
2076 // A static_assert failed. Bail out; instantiating this
2077 // class is probably not meaningful.
2078 Instantiation->setInvalidDecl();
2079 break;
2080 }
Richard Smith1af83c42012-03-23 03:33:32 +00002081 }
2082
2083 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002084 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002085 } else {
2086 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002087 // instantiations was a semantic disaster, and we'll want to mark the
2088 // declaration invalid.
2089 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002090 }
2091 }
2092
2093 // Finish checking fields.
David Blaikie77b6de02011-09-22 02:58:26 +00002094 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2095 SourceLocation(), SourceLocation(), 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002096 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002097
2098 // Attach any in-class member initializers now the class is complete.
Richard Smithd5be2b52012-12-08 02:13:02 +00002099 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer268efba2012-05-17 12:01:52 +00002100 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002101 // C++11 [expr.prim.general]p4:
2102 // Otherwise, if a member-declarator declares a non-static data member
2103 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2104 // to X" within the optional brace-or-equal-initializer. It shall not
2105 // appear elsewhere in the member-declarator.
2106 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2107
2108 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2109 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2110 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2111 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002112
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002113 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2114 /*CXXDirectInit=*/false);
2115 if (NewInit.isInvalid())
2116 NewField->setInvalidDecl();
2117 else {
2118 Expr *Init = NewInit.take();
2119 assert(Init && "no-argument initializer in class");
2120 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
Richard Smithca523302012-06-10 03:12:00 +00002121 ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002122 }
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002123 }
Richard Smith7a614d82011-06-11 17:19:42 +00002124 }
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002125 // Instantiate late parsed attributes, and attach them to their decls.
2126 // See Sema::InstantiateAttrs
2127 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2128 E = LateAttrs.end(); I != E; ++I) {
2129 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2130 CurrentInstantiationScope = I->Scope;
Richard Smithcafeb942013-06-07 02:33:37 +00002131
2132 // Allow 'this' within late-parsed attributes.
2133 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2134 CXXRecordDecl *ThisContext =
2135 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2136 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2137 ND && ND->isCXXInstanceMember());
2138
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002139 Attr *NewAttr =
2140 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2141 I->NewDecl->addAttr(NewAttr);
2142 LocalInstantiationScope::deleteScopes(I->Scope,
2143 Instantiator.getStartingScope());
2144 }
2145 Instantiator.disableLateAttributeInstantiation();
2146 LateAttrs.clear();
2147
Richard Smithb9d0b762012-07-27 04:22:15 +00002148 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002149
Abramo Bagnarae9946242011-11-18 08:08:52 +00002150 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002151 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002152 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002153 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002154 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002155
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002156 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002157 // Perform any dependent diagnostics from the pattern.
2158 PerformDependentDiagnostics(Pattern, TemplateArgs);
2159
Douglas Gregord65587f2010-11-10 19:44:59 +00002160 // Instantiate any out-of-line class template partial
2161 // specializations now.
2162 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2163 P = Instantiator.delayed_partial_spec_begin(),
2164 PEnd = Instantiator.delayed_partial_spec_end();
2165 P != PEnd; ++P) {
2166 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2167 P->first,
2168 P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002169 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002170 break;
2171 }
2172 }
2173 }
2174
Douglas Gregord475b8d2009-03-25 21:17:03 +00002175 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002176 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002177
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002178 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002179 Consumer.HandleTagDeclDefinition(Instantiation);
2180
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002181 // Always emit the vtable for an explicit instantiation definition
2182 // of a polymorphic class template specialization.
2183 if (TSK == TSK_ExplicitInstantiationDefinition)
2184 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2185 }
2186
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002187 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002188}
2189
Richard Smithf1c66b42012-03-14 23:13:10 +00002190/// \brief Instantiate the definition of an enum from a given pattern.
2191///
2192/// \param PointOfInstantiation The point of instantiation within the
2193/// source code.
2194/// \param Instantiation is the declaration whose definition is being
2195/// instantiated. This will be a member enumeration of a class
2196/// temploid specialization, or a local enumeration within a
2197/// function temploid specialization.
2198/// \param Pattern The templated declaration from which the instantiation
2199/// occurs.
2200/// \param TemplateArgs The template arguments to be substituted into
2201/// the pattern.
2202/// \param TSK The kind of implicit or explicit instantiation to perform.
2203///
2204/// \return \c true if an error occurred, \c false otherwise.
2205bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2206 EnumDecl *Instantiation, EnumDecl *Pattern,
2207 const MultiLevelTemplateArgumentList &TemplateArgs,
2208 TemplateSpecializationKind TSK) {
2209 EnumDecl *PatternDef = Pattern->getDefinition();
2210 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2211 Instantiation->getInstantiatedFromMemberEnum(),
2212 Pattern, PatternDef, TSK,/*Complain*/true))
2213 return true;
2214 Pattern = PatternDef;
2215
2216 // Record the point of instantiation.
2217 if (MemberSpecializationInfo *MSInfo
2218 = Instantiation->getMemberSpecializationInfo()) {
2219 MSInfo->setTemplateSpecializationKind(TSK);
2220 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2221 }
2222
2223 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2224 if (Inst)
2225 return true;
2226
2227 // Enter the scope of this instantiation. We don't use
2228 // PushDeclContext because we don't have a scope.
2229 ContextRAII SavedContext(*this, Instantiation);
2230 EnterExpressionEvaluationContext EvalContext(*this,
2231 Sema::PotentiallyEvaluated);
2232
2233 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2234
2235 // Pull attributes from the pattern onto the instantiation.
2236 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2237
2238 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2239 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2240
2241 // Exit the scope of this instantiation.
2242 SavedContext.pop();
2243
2244 return Instantiation->isInvalidDecl();
2245}
2246
Douglas Gregor9b623632010-10-12 23:32:35 +00002247namespace {
2248 /// \brief A partial specialization whose template arguments have matched
2249 /// a given template-id.
2250 struct PartialSpecMatchResult {
2251 ClassTemplatePartialSpecializationDecl *Partial;
2252 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002253 };
2254}
2255
Mike Stump1eb44332009-09-09 15:08:12 +00002256bool
Douglas Gregor2943aed2009-03-03 04:44:36 +00002257Sema::InstantiateClassTemplateSpecialization(
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002258 SourceLocation PointOfInstantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00002259 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002260 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002261 bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002262 // Perform the actual instantiation on the canonical declaration.
2263 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002264 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002265
Douglas Gregor52604ab2009-09-11 21:19:12 +00002266 // Check whether we have already instantiated or specialized this class
2267 // template specialization.
2268 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2269 if (ClassTemplateSpec->getSpecializationKind() ==
2270 TSK_ExplicitInstantiationDeclaration &&
2271 TSK == TSK_ExplicitInstantiationDefinition) {
2272 // An explicit instantiation definition follows an explicit instantiation
2273 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2274 // explicit instantiation.
2275 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002276
2277 // If this is an explicit instantiation definition, mark the
2278 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002279 if (TSK == TSK_ExplicitInstantiationDefinition &&
2280 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002281 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2282
Douglas Gregor52604ab2009-09-11 21:19:12 +00002283 return false;
2284 }
2285
2286 // We can only instantiate something that hasn't already been
2287 // instantiated or specialized. Fail without any diagnostics: our
2288 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002289 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002290 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002291
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002292 if (ClassTemplateSpec->isInvalidDecl())
2293 return true;
2294
Douglas Gregor2943aed2009-03-03 04:44:36 +00002295 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00002296 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002297
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002298 // C++ [temp.class.spec.match]p1:
2299 // When a class template is used in a context that requires an
2300 // instantiation of the class, it is necessary to determine
2301 // whether the instantiation is to be generated using the primary
2302 // template or one of the partial specializations. This is done by
2303 // matching the template arguments of the class template
2304 // specialization with the template argument lists of the partial
2305 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002306 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002307 SmallVector<MatchResult, 4> Matched;
2308 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002309 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo43847122013-07-19 23:00:19 +00002310 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002311 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2312 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo43847122013-07-19 23:00:19 +00002313 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorf67875d2009-06-12 18:26:56 +00002314 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002315 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002316 ClassTemplateSpec->getTemplateArgs(),
2317 Info)) {
Larisse Voufo43847122013-07-19 23:00:19 +00002318 // Store the failed-deduction information for use in diagnostics, later.
2319 // TODO: Actually use the failed-deduction info?
2320 FailedCandidates.addCandidate()
2321 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorf67875d2009-06-12 18:26:56 +00002322 (void)Result;
2323 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002324 Matched.push_back(PartialSpecMatchResult());
2325 Matched.back().Partial = Partial;
2326 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002327 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002328 }
2329
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002330 // If we're dealing with a member template where the template parameters
2331 // have been instantiated, this provides the original template parameters
2332 // from which the member template's parameters were instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002333 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002334
Douglas Gregored9c0f92009-10-29 00:04:11 +00002335 if (Matched.size() >= 1) {
Craig Topper09d19ef2013-07-04 03:08:24 +00002336 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002337 if (Matched.size() == 1) {
2338 // -- If exactly one matching specialization is found, the
2339 // instantiation is generated from that specialization.
2340 // We don't need to do anything for this.
2341 } else {
2342 // -- If more than one matching specialization is found, the
2343 // partial order rules (14.5.4.2) are used to determine
2344 // whether one of the specializations is more specialized
2345 // than the others. If none of the specializations is more
2346 // specialized than all of the other matching
2347 // specializations, then the use of the class template is
2348 // ambiguous and the program is ill-formed.
Craig Topper09d19ef2013-07-04 03:08:24 +00002349 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2350 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002351 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002352 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002353 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002354 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002355 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002356 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002357
Douglas Gregored9c0f92009-10-29 00:04:11 +00002358 // Determine if the best partial specialization is more specialized than
2359 // the others.
2360 bool Ambiguous = false;
Craig Topper09d19ef2013-07-04 03:08:24 +00002361 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2362 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002363 P != PEnd; ++P) {
2364 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002365 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002366 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002367 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002368 Ambiguous = true;
2369 break;
2370 }
2371 }
2372
2373 if (Ambiguous) {
2374 // Partial ordering did not produce a clear winner. Complain.
2375 ClassTemplateSpec->setInvalidDecl();
2376 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2377 << ClassTemplateSpec;
2378
2379 // Print the matching partial specializations.
Craig Topper09d19ef2013-07-04 03:08:24 +00002380 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2381 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002382 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002383 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2384 << getTemplateArgumentBindingsText(
2385 P->Partial->getTemplateParameters(),
2386 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002387
Douglas Gregored9c0f92009-10-29 00:04:11 +00002388 return true;
2389 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002390 }
2391
2392 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002393 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002394 while (OrigPartialSpec->getInstantiatedFromMember()) {
2395 // If we've found an explicit specialization of this class template,
2396 // stop here and use that as the pattern.
2397 if (OrigPartialSpec->isMemberSpecialization())
2398 break;
2399
2400 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2401 }
2402
2403 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002404 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002405 } else {
2406 // -- If no matches are found, the instantiation is generated
2407 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002408 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002409 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2410 // If we've found an explicit specialization of this class template,
2411 // stop here and use that as the pattern.
2412 if (OrigTemplate->isMemberSpecialization())
2413 break;
2414
Douglas Gregord6350ae2009-08-28 20:31:08 +00002415 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002416 }
2417
Douglas Gregord6350ae2009-08-28 20:31:08 +00002418 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002419 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002420
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002421 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2422 Pattern,
2423 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002424 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002425 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002426
Douglas Gregor199d9912009-06-05 00:53:49 +00002427 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002428}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002429
John McCallce3ff2b2009-08-25 22:02:44 +00002430/// \brief Instantiates the definitions of all of the member
2431/// of the given class, which is an instantiation of a class template
2432/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002433void
2434Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002435 CXXRecordDecl *Instantiation,
2436 const MultiLevelTemplateArgumentList &TemplateArgs,
2437 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002438 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2439 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002440 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002441 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002442 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002443 if (FunctionDecl *Pattern
2444 = Function->getInstantiatedFromMemberFunction()) {
2445 MemberSpecializationInfo *MSInfo
2446 = Function->getMemberSpecializationInfo();
2447 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002448 if (MSInfo->getTemplateSpecializationKind()
2449 == TSK_ExplicitSpecialization)
2450 continue;
2451
Douglas Gregor0d035142009-10-27 18:42:08 +00002452 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2453 Function,
2454 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002455 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002456 SuppressNew) ||
2457 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002458 continue;
2459
Sean Hunt10620eb2011-05-06 20:44:56 +00002460 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002461 continue;
2462
2463 if (TSK == TSK_ExplicitInstantiationDefinition) {
2464 // C++0x [temp.explicit]p8:
2465 // An explicit instantiation definition that names a class template
2466 // specialization explicitly instantiates the class template
2467 // specialization and is only an explicit instantiation definition
2468 // of members whose definition is visible at the point of
2469 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002470 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002471 continue;
2472
2473 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2474
2475 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2476 } else {
2477 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2478 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002479 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002480 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002481 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002482 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2483 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002484 if (MSInfo->getTemplateSpecializationKind()
2485 == TSK_ExplicitSpecialization)
2486 continue;
2487
Douglas Gregor0d035142009-10-27 18:42:08 +00002488 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2489 Var,
2490 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002491 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002492 SuppressNew) ||
2493 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002494 continue;
2495
Douglas Gregor0d035142009-10-27 18:42:08 +00002496 if (TSK == TSK_ExplicitInstantiationDefinition) {
2497 // C++0x [temp.explicit]p8:
2498 // An explicit instantiation definition that names a class template
2499 // specialization explicitly instantiates the class template
2500 // specialization and is only an explicit instantiation definition
2501 // of members whose definition is visible at the point of
2502 // instantiation.
2503 if (!Var->getInstantiatedFromStaticDataMember()
2504 ->getOutOfLineDefinition())
2505 continue;
2506
2507 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002508 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002509 } else {
2510 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2511 }
2512 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002513 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002514 // Always skip the injected-class-name, along with any
2515 // redeclarations of nested classes, since both would cause us
2516 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002517 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002518 continue;
2519
Douglas Gregor0d035142009-10-27 18:42:08 +00002520 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2521 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002522
2523 if (MSInfo->getTemplateSpecializationKind()
2524 == TSK_ExplicitSpecialization)
2525 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002526
Douglas Gregor0d035142009-10-27 18:42:08 +00002527 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2528 Record,
2529 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002530 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002531 SuppressNew) ||
2532 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002533 continue;
2534
Douglas Gregor0d035142009-10-27 18:42:08 +00002535 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2536 assert(Pattern && "Missing instantiated-from-template information");
2537
Douglas Gregor952b0172010-02-11 01:04:33 +00002538 if (!Record->getDefinition()) {
2539 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002540 // C++0x [temp.explicit]p8:
2541 // An explicit instantiation definition that names a class template
2542 // specialization explicitly instantiates the class template
2543 // specialization and is only an explicit instantiation definition
2544 // of members whose definition is visible at the point of
2545 // instantiation.
2546 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2547 MSInfo->setTemplateSpecializationKind(TSK);
2548 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2549 }
2550
2551 continue;
2552 }
2553
2554 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002555 TemplateArgs,
2556 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002557 } else {
2558 if (TSK == TSK_ExplicitInstantiationDefinition &&
2559 Record->getTemplateSpecializationKind() ==
2560 TSK_ExplicitInstantiationDeclaration) {
2561 Record->setTemplateSpecializationKind(TSK);
2562 MarkVTableUsed(PointOfInstantiation, Record, true);
2563 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002564 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002565
Douglas Gregor952b0172010-02-11 01:04:33 +00002566 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002567 if (Pattern)
2568 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2569 TSK);
Richard Smithf1c66b42012-03-14 23:13:10 +00002570 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2571 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2572 assert(MSInfo && "No member specialization information?");
2573
2574 if (MSInfo->getTemplateSpecializationKind()
2575 == TSK_ExplicitSpecialization)
2576 continue;
2577
2578 if (CheckSpecializationInstantiationRedecl(
2579 PointOfInstantiation, TSK, Enum,
2580 MSInfo->getTemplateSpecializationKind(),
2581 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2582 SuppressNew)
2583 continue;
2584
2585 if (Enum->getDefinition())
2586 continue;
2587
2588 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2589 assert(Pattern && "Missing instantiated-from-template information");
2590
2591 if (TSK == TSK_ExplicitInstantiationDefinition) {
2592 if (!Pattern->getDefinition())
2593 continue;
2594
2595 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2596 } else {
2597 MSInfo->setTemplateSpecializationKind(TSK);
2598 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2599 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002600 }
2601 }
2602}
2603
2604/// \brief Instantiate the definitions of all of the members of the
2605/// given class template specialization, which was named as part of an
2606/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002607void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002608Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002609 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002610 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2611 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002612 // C++0x [temp.explicit]p7:
2613 // An explicit instantiation that names a class template
2614 // specialization is an explicit instantion of the same kind
2615 // (declaration or definition) of each of its members (not
2616 // including members inherited from base classes) that has not
2617 // been previously explicitly specialized in the translation unit
2618 // containing the explicit instantiation, except as described
2619 // below.
2620 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002621 getTemplateInstantiationArgs(ClassTemplateSpec),
2622 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002623}
2624
John McCall60d7b3a2010-08-24 06:29:42 +00002625StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002626Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002627 if (!S)
2628 return Owned(S);
2629
2630 TemplateInstantiator Instantiator(*this, TemplateArgs,
2631 SourceLocation(),
2632 DeclarationName());
2633 return Instantiator.TransformStmt(S);
2634}
2635
John McCall60d7b3a2010-08-24 06:29:42 +00002636ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002637Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002638 if (!E)
2639 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002640
Douglas Gregorb98b1992009-08-11 05:31:07 +00002641 TemplateInstantiator Instantiator(*this, TemplateArgs,
2642 SourceLocation(),
2643 DeclarationName());
2644 return Instantiator.TransformExpr(E);
2645}
2646
Richard Smithc83c2302012-12-19 01:39:02 +00002647ExprResult Sema::SubstInitializer(Expr *Init,
2648 const MultiLevelTemplateArgumentList &TemplateArgs,
2649 bool CXXDirectInit) {
2650 TemplateInstantiator Instantiator(*this, TemplateArgs,
2651 SourceLocation(),
2652 DeclarationName());
2653 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2654}
2655
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002656bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2657 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002658 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002659 if (NumExprs == 0)
2660 return false;
Richard Smithc83c2302012-12-19 01:39:02 +00002661
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002662 TemplateInstantiator Instantiator(*this, TemplateArgs,
2663 SourceLocation(),
2664 DeclarationName());
2665 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2666}
2667
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002668NestedNameSpecifierLoc
2669Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2670 const MultiLevelTemplateArgumentList &TemplateArgs) {
2671 if (!NNS)
2672 return NestedNameSpecifierLoc();
2673
2674 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2675 DeclarationName());
2676 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2677}
2678
Abramo Bagnara25777432010-08-11 22:01:17 +00002679/// \brief Do template substitution on declaration name info.
2680DeclarationNameInfo
2681Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2682 const MultiLevelTemplateArgumentList &TemplateArgs) {
2683 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2684 NameInfo.getName());
2685 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2686}
2687
Douglas Gregorde650ae2009-03-31 18:38:02 +00002688TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002689Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2690 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002691 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002692 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2693 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002694 CXXScopeSpec SS;
2695 SS.Adopt(QualifierLoc);
2696 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002697}
Douglas Gregor91333002009-06-11 00:06:24 +00002698
Douglas Gregore02e2622010-12-22 21:19:48 +00002699bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2700 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002701 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002702 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2703 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002704
2705 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002706}
Douglas Gregor895162d2010-04-30 18:55:50 +00002707
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002708
2709static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2710 // When storing ParmVarDecls in the local instantiation scope, we always
2711 // want to use the ParmVarDecl from the canonical function declaration,
2712 // since the map is then valid for any redeclaration or definition of that
2713 // function.
2714 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2715 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2716 unsigned i = PV->getFunctionScopeIndex();
2717 return FD->getCanonicalDecl()->getParamDecl(i);
2718 }
2719 }
2720 return D;
2721}
2722
2723
Douglas Gregor12c9c002011-01-07 16:43:16 +00002724llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2725LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002726 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002727 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002728 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002729
Douglas Gregor895162d2010-04-30 18:55:50 +00002730 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002731 const Decl *CheckD = D;
2732 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002733 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002734 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002735 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002736
2737 // If this is a tag declaration, it's possible that we need to look for
2738 // a previous declaration.
2739 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002740 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002741 else
2742 CheckD = 0;
2743 } while (CheckD);
2744
Douglas Gregor895162d2010-04-30 18:55:50 +00002745 // If we aren't combined with our outer scope, we're done.
2746 if (!Current->CombineWithOuterScope)
2747 break;
2748 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002749
Serge Pavlovdc49d522013-07-15 06:14:07 +00002750 // If we're performing a partial substitution during template argument
2751 // deduction, we may not have values for template parameters yet.
2752 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2753 isa<TemplateTemplateParmDecl>(D))
2754 return 0;
2755
Chris Lattner57ad3782011-02-17 20:34:02 +00002756 // If we didn't find the decl, then we either have a sema bug, or we have a
2757 // forward reference to a label declaration. Return null to indicate that
2758 // we have an uninstantiated label.
2759 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002760 return 0;
2761}
2762
John McCall2a7fb272010-08-25 05:32:35 +00002763void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002764 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002765 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002766 if (Stored.isNull())
2767 Stored = Inst;
Benjamin Kramer3bbffd52013-04-12 15:22:25 +00002768 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2769 Pack->push_back(Inst);
2770 else
Douglas Gregord3731192011-01-10 07:32:04 +00002771 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor895162d2010-04-30 18:55:50 +00002772}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002773
2774void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2775 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002776 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002777 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2778 Pack->push_back(Inst);
2779}
2780
2781void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002782 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002783 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2784 assert(Stored.isNull() && "Already instantiated this local");
2785 DeclArgumentPack *Pack = new DeclArgumentPack;
2786 Stored = Pack;
2787 ArgumentPacks.push_back(Pack);
2788}
2789
Douglas Gregord3731192011-01-10 07:32:04 +00002790void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2791 const TemplateArgument *ExplicitArgs,
2792 unsigned NumExplicitArgs) {
2793 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2794 "Already have a partially-substituted pack");
2795 assert((!PartiallySubstitutedPack
2796 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2797 "Wrong number of arguments in partially-substituted pack");
2798 PartiallySubstitutedPack = Pack;
2799 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2800 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2801}
2802
2803NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2804 const TemplateArgument **ExplicitArgs,
2805 unsigned *NumExplicitArgs) const {
2806 if (ExplicitArgs)
2807 *ExplicitArgs = 0;
2808 if (NumExplicitArgs)
2809 *NumExplicitArgs = 0;
2810
2811 for (const LocalInstantiationScope *Current = this; Current;
2812 Current = Current->Outer) {
2813 if (Current->PartiallySubstitutedPack) {
2814 if (ExplicitArgs)
2815 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2816 if (NumExplicitArgs)
2817 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2818
2819 return Current->PartiallySubstitutedPack;
2820 }
2821
2822 if (!Current->CombineWithOuterScope)
2823 break;
2824 }
2825
2826 return 0;
2827}