blob: c2ebbf4b5575142c0d95128e623c49d2f6cb9057 [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"
John McCall19510852010-08-20 18:27:03 +000015#include "clang/Sema/DeclSpec.h"
Richard Smith7a614d82011-06-11 17:19:42 +000016#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Lookup.h"
John McCall7cd088e2010-08-24 07:21:54 +000018#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000019#include "clang/Sema/TemplateDeduction.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000021#include "clang/AST/ASTContext.h"
22#include "clang/AST/Expr.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000023#include "clang/AST/DeclTemplate.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000024#include "clang/Basic/LangOptions.h"
25
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();
Douglas Gregor93104c12011-05-22 00:21:10 +000064
Douglas Gregor383041d2011-06-15 14:20:42 +000065 // If we have a template template parameter with translation unit context,
66 // then we're performing substitution into a default template argument of
67 // this template template parameter before we've constructed the template
68 // that will own this template template parameter. In this case, we
69 // use empty template parameter lists for all of the outer templates
70 // to avoid performing any substitutions.
71 if (Ctx->isTranslationUnit()) {
72 if (TemplateTemplateParmDecl *TTP
73 = dyn_cast<TemplateTemplateParmDecl>(D)) {
74 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
75 Result.addOuterTemplateArguments(0, 0);
76 return Result;
77 }
78 }
Douglas Gregor93104c12011-05-22 00:21:10 +000079 }
80
John McCallf181d8a2009-08-29 03:16:09 +000081 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +000082 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +000083 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +000084 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
85 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +000086 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
87 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +000088 break;
Mike Stump1eb44332009-09-09 15:08:12 +000089
Douglas Gregord1102432009-08-28 17:37:35 +000090 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +000091
92 // If this class template specialization was instantiated from a
93 // specialized member that is a class template, we're done.
94 assert(Spec->getSpecializedTemplate() && "No class template?");
95 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
96 break;
Mike Stump1eb44332009-09-09 15:08:12 +000097 }
Douglas Gregord1102432009-08-28 17:37:35 +000098 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +000099 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000100 if (!RelativeToPrimary &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000101 (Function->getTemplateSpecializationKind() ==
102 TSK_ExplicitSpecialization &&
103 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000104 break;
105
Douglas Gregord1102432009-08-28 17:37:35 +0000106 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000107 = Function->getTemplateSpecializationArgs()) {
108 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000109 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000110
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000111 // If this function was instantiated from a specialized member that is
112 // a function template, we're done.
113 assert(Function->getPrimaryTemplate() && "No function template?");
114 if (Function->getPrimaryTemplate()->isMemberSpecialization())
115 break;
Douglas Gregorc494f772011-03-05 17:54:25 +0000116 } else if (FunctionTemplateDecl *FunTmpl
117 = Function->getDescribedFunctionTemplate()) {
118 // Add the "injected" template arguments.
119 std::pair<const TemplateArgument *, unsigned>
120 Injected = FunTmpl->getInjectedTemplateArgs();
121 Result.addOuterTemplateArguments(Injected.first, Injected.second);
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000122 }
123
John McCallf181d8a2009-08-29 03:16:09 +0000124 // If this is a friend declaration and it declares an entity at
125 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000126 // instead of its semantic parent, unless of course the pattern we're
127 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000128 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000129 Function->getDeclContext()->isFileContext() &&
130 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000131 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000132 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000133 continue;
134 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000135 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
136 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
137 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
138 const TemplateSpecializationType *TST
139 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
140 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
141 if (ClassTemplate->isMemberSpecialization())
142 break;
143 }
Douglas Gregord1102432009-08-28 17:37:35 +0000144 }
John McCallf181d8a2009-08-29 03:16:09 +0000145
146 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000147 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000148 }
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregord1102432009-08-28 17:37:35 +0000150 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000151}
152
Douglas Gregorf35f8282009-11-11 21:54:23 +0000153bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
154 switch (Kind) {
155 case TemplateInstantiation:
156 case DefaultTemplateArgumentInstantiation:
157 case DefaultFunctionArgumentInstantiation:
158 return true;
159
160 case ExplicitTemplateArgumentSubstitution:
161 case DeducedTemplateArgumentSubstitution:
162 case PriorTemplateArgumentSubstitution:
163 case DefaultTemplateArgumentChecking:
164 return false;
165 }
David Blaikie7530c032012-01-17 06:56:22 +0000166
167 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000168}
169
Douglas Gregor26dce442009-03-10 00:06:19 +0000170Sema::InstantiatingTemplate::
171InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000172 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000173 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000174 : SemaRef(SemaRef),
175 SavedInNonInstantiationSFINAEContext(
176 SemaRef.InNonInstantiationSFINAEContext)
177{
Douglas Gregordf667e72009-03-10 20:44:00 +0000178 Invalid = CheckInstantiationDepth(PointOfInstantiation,
179 InstantiationRange);
180 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000181 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +0000182 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +0000183 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregordf667e72009-03-10 20:44:00 +0000184 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregor313a81d2009-03-12 18:36:18 +0000185 Inst.TemplateArgs = 0;
186 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +0000187 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000188 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregordf667e72009-03-10 20:44:00 +0000189 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregordf667e72009-03-10 20:44:00 +0000190 }
191}
192
Mike Stump1eb44332009-09-09 15:08:12 +0000193Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregordf667e72009-03-10 20:44:00 +0000194 SourceLocation PointOfInstantiation,
195 TemplateDecl *Template,
196 const TemplateArgument *TemplateArgs,
197 unsigned NumTemplateArgs,
198 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000199 : SemaRef(SemaRef),
200 SavedInNonInstantiationSFINAEContext(
201 SemaRef.InNonInstantiationSFINAEContext)
202{
Douglas Gregordf667e72009-03-10 20:44:00 +0000203 Invalid = CheckInstantiationDepth(PointOfInstantiation,
204 InstantiationRange);
205 if (!Invalid) {
206 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000207 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000208 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
209 Inst.PointOfInstantiation = PointOfInstantiation;
210 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
211 Inst.TemplateArgs = TemplateArgs;
212 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor26dce442009-03-10 00:06:19 +0000213 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000214 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000215 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000216 }
217}
218
Mike Stump1eb44332009-09-09 15:08:12 +0000219Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor637a4092009-06-10 23:47:09 +0000220 SourceLocation PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000221 FunctionTemplateDecl *FunctionTemplate,
222 const TemplateArgument *TemplateArgs,
223 unsigned NumTemplateArgs,
224 ActiveTemplateInstantiation::InstantiationKind Kind,
Douglas Gregor9b623632010-10-12 23:32:35 +0000225 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000226 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000227 : SemaRef(SemaRef),
228 SavedInNonInstantiationSFINAEContext(
229 SemaRef.InNonInstantiationSFINAEContext)
230{
Douglas Gregorcca9e962009-07-01 22:01:06 +0000231 Invalid = CheckInstantiationDepth(PointOfInstantiation,
232 InstantiationRange);
233 if (!Invalid) {
234 ActiveTemplateInstantiation Inst;
235 Inst.Kind = Kind;
236 Inst.PointOfInstantiation = PointOfInstantiation;
237 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
238 Inst.TemplateArgs = TemplateArgs;
239 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor9b623632010-10-12 23:32:35 +0000240 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000241 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000242 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000243 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000244
245 if (!Inst.isInstantiationRecord())
246 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000247 }
248}
249
Mike Stump1eb44332009-09-09 15:08:12 +0000250Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000251 SourceLocation PointOfInstantiation,
Douglas Gregor637a4092009-06-10 23:47:09 +0000252 ClassTemplatePartialSpecializationDecl *PartialSpec,
253 const TemplateArgument *TemplateArgs,
254 unsigned NumTemplateArgs,
Douglas Gregor9b623632010-10-12 23:32:35 +0000255 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregor637a4092009-06-10 23:47:09 +0000256 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000257 : SemaRef(SemaRef),
258 SavedInNonInstantiationSFINAEContext(
259 SemaRef.InNonInstantiationSFINAEContext)
260{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000261 Invalid = false;
262
263 ActiveTemplateInstantiation Inst;
264 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
265 Inst.PointOfInstantiation = PointOfInstantiation;
266 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
267 Inst.TemplateArgs = TemplateArgs;
268 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor9b623632010-10-12 23:32:35 +0000269 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000270 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000271 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000272 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
273
274 assert(!Inst.isInstantiationRecord());
275 ++SemaRef.NonInstantiationEntries;
Douglas Gregor637a4092009-06-10 23:47:09 +0000276}
277
Mike Stump1eb44332009-09-09 15:08:12 +0000278Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000279 SourceLocation PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000280 ParmVarDecl *Param,
281 const TemplateArgument *TemplateArgs,
282 unsigned NumTemplateArgs,
283 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000284 : SemaRef(SemaRef),
285 SavedInNonInstantiationSFINAEContext(
286 SemaRef.InNonInstantiationSFINAEContext)
287{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000288 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000289
290 if (!Invalid) {
291 ActiveTemplateInstantiation Inst;
292 Inst.Kind
293 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000294 Inst.PointOfInstantiation = PointOfInstantiation;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000295 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
296 Inst.TemplateArgs = TemplateArgs;
297 Inst.NumTemplateArgs = NumTemplateArgs;
298 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000299 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000300 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000301 }
302}
303
304Sema::InstantiatingTemplate::
305InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000306 NamedDecl *Template,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000307 NonTypeTemplateParmDecl *Param,
308 const TemplateArgument *TemplateArgs,
309 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000310 SourceRange InstantiationRange)
311 : SemaRef(SemaRef),
312 SavedInNonInstantiationSFINAEContext(
313 SemaRef.InNonInstantiationSFINAEContext)
314{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000315 Invalid = false;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000316
Douglas Gregorf35f8282009-11-11 21:54:23 +0000317 ActiveTemplateInstantiation Inst;
318 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
319 Inst.PointOfInstantiation = PointOfInstantiation;
320 Inst.Template = Template;
321 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
322 Inst.TemplateArgs = TemplateArgs;
323 Inst.NumTemplateArgs = NumTemplateArgs;
324 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000325 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000326 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
327
328 assert(!Inst.isInstantiationRecord());
329 ++SemaRef.NonInstantiationEntries;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000330}
331
332Sema::InstantiatingTemplate::
333InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000334 NamedDecl *Template,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000335 TemplateTemplateParmDecl *Param,
336 const TemplateArgument *TemplateArgs,
337 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000338 SourceRange InstantiationRange)
339 : SemaRef(SemaRef),
340 SavedInNonInstantiationSFINAEContext(
341 SemaRef.InNonInstantiationSFINAEContext)
342{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000343 Invalid = false;
344 ActiveTemplateInstantiation Inst;
345 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
346 Inst.PointOfInstantiation = PointOfInstantiation;
347 Inst.Template = Template;
348 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
349 Inst.TemplateArgs = TemplateArgs;
350 Inst.NumTemplateArgs = NumTemplateArgs;
351 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000352 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000353 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000354
Douglas Gregorf35f8282009-11-11 21:54:23 +0000355 assert(!Inst.isInstantiationRecord());
356 ++SemaRef.NonInstantiationEntries;
357}
358
359Sema::InstantiatingTemplate::
360InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
361 TemplateDecl *Template,
362 NamedDecl *Param,
363 const TemplateArgument *TemplateArgs,
364 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000365 SourceRange InstantiationRange)
366 : SemaRef(SemaRef),
367 SavedInNonInstantiationSFINAEContext(
368 SemaRef.InNonInstantiationSFINAEContext)
369{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000370 Invalid = false;
371
372 ActiveTemplateInstantiation Inst;
373 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
374 Inst.PointOfInstantiation = PointOfInstantiation;
375 Inst.Template = Template;
376 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
377 Inst.TemplateArgs = TemplateArgs;
378 Inst.NumTemplateArgs = NumTemplateArgs;
379 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000380 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000381 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
382
383 assert(!Inst.isInstantiationRecord());
384 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000385}
386
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000387void Sema::InstantiatingTemplate::Clear() {
388 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000389 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
390 assert(SemaRef.NonInstantiationEntries > 0);
391 --SemaRef.NonInstantiationEntries;
392 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000393 SemaRef.InNonInstantiationSFINAEContext
394 = SavedInNonInstantiationSFINAEContext;
Douglas Gregor26dce442009-03-10 00:06:19 +0000395 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000396 Invalid = true;
397 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000398}
399
Douglas Gregordf667e72009-03-10 20:44:00 +0000400bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
401 SourceLocation PointOfInstantiation,
402 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000403 assert(SemaRef.NonInstantiationEntries <=
404 SemaRef.ActiveTemplateInstantiations.size());
405 if ((SemaRef.ActiveTemplateInstantiations.size() -
406 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000407 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000408 return false;
409
Mike Stump1eb44332009-09-09 15:08:12 +0000410 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000411 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000412 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000413 << InstantiationRange;
414 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000415 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000416 return true;
417}
418
Douglas Gregoree1828a2009-03-10 18:03:33 +0000419/// \brief Prints the current instantiation stack through a series of
420/// notes.
421void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000422 // Determine which template instantiations to skip, if any.
423 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
424 unsigned Limit = Diags.getTemplateBacktraceLimit();
425 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
426 SkipStart = Limit / 2 + Limit % 2;
427 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
428 }
429
Douglas Gregorcca9e962009-07-01 22:01:06 +0000430 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000431 unsigned InstantiationIdx = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000432 for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000433 Active = ActiveTemplateInstantiations.rbegin(),
434 ActiveEnd = ActiveTemplateInstantiations.rend();
435 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000436 ++Active, ++InstantiationIdx) {
437 // Skip this instantiation?
438 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
439 if (InstantiationIdx == SkipStart) {
440 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000441 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000442 diag::note_instantiation_contexts_suppressed)
443 << unsigned(ActiveTemplateInstantiations.size() - Limit);
444 }
445 continue;
446 }
447
Douglas Gregordf667e72009-03-10 20:44:00 +0000448 switch (Active->Kind) {
449 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000450 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
451 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
452 unsigned DiagID = diag::note_template_member_class_here;
453 if (isa<ClassTemplateSpecializationDecl>(Record))
454 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000455 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000456 << Context.getTypeDeclType(Record)
457 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000458 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000459 unsigned DiagID;
460 if (Function->getPrimaryTemplate())
461 DiagID = diag::note_function_template_spec_here;
462 else
463 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000464 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000465 << Function
466 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000467 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000468 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor7caa6822009-07-24 20:34:43 +0000469 diag::note_template_static_data_member_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000470 << VD
471 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000472 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
473 Diags.Report(Active->PointOfInstantiation,
474 diag::note_template_enum_def_here)
475 << ED
476 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000477 } else {
478 Diags.Report(Active->PointOfInstantiation,
479 diag::note_template_type_alias_instantiation_here)
480 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000481 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000482 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000483 break;
484 }
485
486 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
487 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
488 std::string TemplateArgsStr
Douglas Gregor7532dc62009-03-30 22:58:21 +0000489 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump1eb44332009-09-09 15:08:12 +0000490 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000491 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000492 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000493 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000494 diag::note_default_arg_instantiation_here)
495 << (Template->getNameAsString() + TemplateArgsStr)
496 << Active->InstantiationRange;
497 break;
498 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000499
Douglas Gregorcca9e962009-07-01 22:01:06 +0000500 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Mike Stump1eb44332009-09-09 15:08:12 +0000501 FunctionTemplateDecl *FnTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +0000502 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000503 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000504 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000505 << FnTmpl
506 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
507 Active->TemplateArgs,
508 Active->NumTemplateArgs)
509 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000510 break;
511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Douglas Gregorcca9e962009-07-01 22:01:06 +0000513 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
514 if (ClassTemplatePartialSpecializationDecl *PartialSpec
515 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
516 (Decl *)Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000517 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000518 diag::note_partial_spec_deduct_instantiation_here)
519 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000520 << getTemplateArgumentBindingsText(
521 PartialSpec->getTemplateParameters(),
522 Active->TemplateArgs,
523 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000524 << Active->InstantiationRange;
525 } else {
526 FunctionTemplateDecl *FnTmpl
527 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000528 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000529 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000530 << FnTmpl
531 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
532 Active->TemplateArgs,
533 Active->NumTemplateArgs)
534 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000535 }
536 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000537
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000538 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
539 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
540 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000542 std::string TemplateArgsStr
543 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump1eb44332009-09-09 15:08:12 +0000544 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000545 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000546 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000547 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000548 diag::note_default_function_arg_instantiation_here)
Anders Carlsson6bc107b2009-09-05 05:38:54 +0000549 << (FD->getNameAsString() + TemplateArgsStr)
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000550 << Active->InstantiationRange;
551 break;
552 }
Mike Stump1eb44332009-09-09 15:08:12 +0000553
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000554 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
555 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
556 std::string Name;
557 if (!Parm->getName().empty())
558 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000559
560 TemplateParameterList *TemplateParams = 0;
561 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
562 TemplateParams = Template->getTemplateParameters();
563 else
564 TemplateParams =
565 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
566 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000567 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000568 diag::note_prior_template_arg_substitution)
569 << isa<TemplateTemplateParmDecl>(Parm)
570 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000571 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000572 Active->TemplateArgs,
573 Active->NumTemplateArgs)
574 << Active->InstantiationRange;
575 break;
576 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000577
578 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000579 TemplateParameterList *TemplateParams = 0;
580 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
581 TemplateParams = Template->getTemplateParameters();
582 else
583 TemplateParams =
584 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
585 ->getTemplateParameters();
586
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000587 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000588 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000589 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000590 Active->TemplateArgs,
591 Active->NumTemplateArgs)
592 << Active->InstantiationRange;
593 break;
594 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000595 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000596 }
597}
598
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000599llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000600 if (InNonInstantiationSFINAEContext)
601 return llvm::Optional<TemplateDeductionInfo *>(0);
602
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000603 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
604 Active = ActiveTemplateInstantiations.rbegin(),
605 ActiveEnd = ActiveTemplateInstantiations.rend();
606 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000607 ++Active)
608 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000609 switch(Active->Kind) {
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000610 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000611 case ActiveTemplateInstantiation::TemplateInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000612 // This is a template instantiation, so there is no SFINAE.
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000613 return llvm::Optional<TemplateDeductionInfo *>();
Mike Stump1eb44332009-09-09 15:08:12 +0000614
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000615 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000616 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000617 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000618 // A default template argument instantiation and substitution into
619 // template parameters with arguments for prior parameters may or may
620 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000621 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000622
Douglas Gregorcca9e962009-07-01 22:01:06 +0000623 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
624 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
625 // We're either substitution explicitly-specified template arguments
626 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000627 assert(Active->DeductionInfo && "Missing deduction info pointer");
628 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000629 }
630 }
631
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000632 return llvm::Optional<TemplateDeductionInfo *>();
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000633}
634
Douglas Gregord3731192011-01-10 07:32:04 +0000635/// \brief Retrieve the depth and index of a parameter pack.
636static std::pair<unsigned, unsigned>
637getDepthAndIndex(NamedDecl *ND) {
638 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
639 return std::make_pair(TTP->getDepth(), TTP->getIndex());
640
641 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
642 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
643
644 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
645 return std::make_pair(TTP->getDepth(), TTP->getIndex());
646}
647
Douglas Gregor99ebf652009-02-27 19:31:52 +0000648//===----------------------------------------------------------------------===/
649// Template Instantiation for Types
650//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000651namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000652 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000653 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000654 SourceLocation Loc;
655 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000656
Douglas Gregorcd281c32009-02-28 00:25:32 +0000657 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000658 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000659
660 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000661 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000662 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000663 DeclarationName Entity)
664 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000665 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000666
Mike Stump1eb44332009-09-09 15:08:12 +0000667 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000668 /// transformed.
669 ///
670 /// For the purposes of template instantiation, a type has already been
671 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000672 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000673
Douglas Gregor577f75a2009-08-04 16:50:30 +0000674 /// \brief Returns the location of the entity being instantiated, if known.
675 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000676
Douglas Gregor577f75a2009-08-04 16:50:30 +0000677 /// \brief Returns the name of the entity being instantiated, if any.
678 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000679
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000680 /// \brief Sets the "base" location and entity when that
681 /// information is known based on another transformation.
682 void setBase(SourceLocation Loc, DeclarationName Entity) {
683 this->Loc = Loc;
684 this->Entity = Entity;
685 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000686
687 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
688 SourceRange PatternRange,
David Blaikiea71f9d02011-09-22 02:34:54 +0000689 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000690 bool &ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000691 bool &RetainExpansion,
Douglas Gregorcded4f62011-01-14 17:04:44 +0000692 llvm::Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000693 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
694 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000695 TemplateArgs,
696 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000697 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000698 NumExpansions);
699 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000700
Douglas Gregor12c9c002011-01-07 16:43:16 +0000701 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
702 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
703 }
704
Douglas Gregord3731192011-01-10 07:32:04 +0000705 TemplateArgument ForgetPartiallySubstitutedPack() {
706 TemplateArgument Result;
707 if (NamedDecl *PartialPack
708 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
709 MultiLevelTemplateArgumentList &TemplateArgs
710 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
711 unsigned Depth, Index;
712 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
713 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
714 Result = TemplateArgs(Depth, Index);
715 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
716 }
717 }
718
719 return Result;
720 }
721
722 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
723 if (Arg.isNull())
724 return;
725
726 if (NamedDecl *PartialPack
727 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
728 MultiLevelTemplateArgumentList &TemplateArgs
729 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
730 unsigned Depth, Index;
731 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
732 TemplateArgs.setArgument(Depth, Index, Arg);
733 }
734 }
735
Douglas Gregor577f75a2009-08-04 16:50:30 +0000736 /// \brief Transform the given declaration by instantiating a reference to
737 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000738 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000739
Douglas Gregordfca6f52012-02-13 22:00:16 +0000740 void transformAttrs(Decl *Old, Decl *New) {
741 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
742 }
743
744 void transformedLocalDecl(Decl *Old, Decl *New) {
745 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
746 }
747
Mike Stump1eb44332009-09-09 15:08:12 +0000748 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000749 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000750 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Douglas Gregor6cd21982009-10-20 05:58:46 +0000752 /// \bried Transform the first qualifier within a scope by instantiating the
753 /// declaration.
754 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
755
Douglas Gregor43959a92009-08-20 07:17:43 +0000756 /// \brief Rebuild the exception declaration and register the declaration
757 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000758 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000759 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000760 SourceLocation StartLoc,
761 SourceLocation NameLoc,
762 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Douglas Gregorbe270a02010-04-26 17:57:08 +0000764 /// \brief Rebuild the Objective-C exception declaration and register the
765 /// declaration as an instantiated local.
766 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
767 TypeSourceInfo *TSInfo, QualType T);
768
John McCallc4e70192009-09-11 04:59:25 +0000769 /// \brief Check for tag mismatches when instantiating an
770 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000771 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
772 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000773 NestedNameSpecifierLoc QualifierLoc,
774 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000775
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000776 TemplateName TransformTemplateName(CXXScopeSpec &SS,
777 TemplateName Name,
778 SourceLocation NameLoc,
779 QualType ObjectType = QualType(),
780 NamedDecl *FirstQualifierInScope = 0);
781
John McCall60d7b3a2010-08-24 06:29:42 +0000782 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
783 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
784 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
785 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000786 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000787 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
788 SubstNonTypeTemplateParmPackExpr *E);
789
Douglas Gregor895162d2010-04-30 18:55:50 +0000790 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000791 FunctionProtoTypeLoc TL);
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000792 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000793 int indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000794 llvm::Optional<unsigned> NumExpansions,
795 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000796
Mike Stump1eb44332009-09-09 15:08:12 +0000797 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000798 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000799 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000800 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000801
Douglas Gregorc3069d62011-01-14 02:55:32 +0000802 /// \brief Transforms an already-substituted template type parameter pack
803 /// into either itself (if we aren't substituting into its pack expansion)
804 /// or the appropriate substituted argument.
805 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
806 SubstTemplateTypeParmPackTypeLoc TL);
807
John McCall60d7b3a2010-08-24 06:29:42 +0000808 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000809 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000810 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000811 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
812 getSema().CallsUndergoingInstantiation.pop_back();
813 return move(Result);
814 }
John McCall91a57552011-07-15 05:09:51 +0000815
816 private:
817 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
818 SourceLocation loc,
819 const TemplateArgument &arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000820 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000821}
822
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000823bool TemplateInstantiator::AlreadyTransformed(QualType T) {
824 if (T.isNull())
825 return true;
826
Douglas Gregor561f8122011-07-01 01:22:09 +0000827 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000828 return false;
829
830 getSema().MarkDeclarationsReferencedInType(Loc, T);
831 return true;
832}
833
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000834Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000835 if (!D)
836 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Douglas Gregorc68afe22009-09-03 21:38:09 +0000838 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000839 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000840 // If the corresponding template argument is NULL or non-existent, it's
841 // because we are performing instantiation from explicitly-specified
842 // template arguments in a function template, but there were some
843 // arguments left unspecified.
844 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
845 TTP->getPosition()))
846 return D;
847
Douglas Gregor61c4d282011-01-05 15:48:55 +0000848 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
849
850 if (TTP->isParameterPack()) {
851 assert(Arg.getKind() == TemplateArgument::Pack &&
852 "Missing argument pack");
853
Douglas Gregor1aee05d2011-01-15 06:45:20 +0000854 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
Douglas Gregord3731192011-01-10 07:32:04 +0000855 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000856 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
857 }
858
859 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000860 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000861 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000862 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000863 }
Mike Stump1eb44332009-09-09 15:08:12 +0000864
Douglas Gregor788cd062009-11-11 01:00:40 +0000865 // Fall through to find the instantiated declaration for this template
866 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000867 }
Mike Stump1eb44332009-09-09 15:08:12 +0000868
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000869 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000870}
871
Douglas Gregoraac571c2010-03-01 17:25:41 +0000872Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000873 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000874 if (!Inst)
875 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000876
Douglas Gregor43959a92009-08-20 07:17:43 +0000877 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
878 return Inst;
879}
880
Douglas Gregor6cd21982009-10-20 05:58:46 +0000881NamedDecl *
882TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
883 SourceLocation Loc) {
884 // If the first part of the nested-name-specifier was a template type
885 // parameter, instantiate that type parameter down to a tag type.
886 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
887 const TemplateTypeParmType *TTP
888 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000889
Douglas Gregor6cd21982009-10-20 05:58:46 +0000890 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000891 // FIXME: This needs testing w/ member access expressions.
892 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
893
894 if (TTP->isParameterPack()) {
895 assert(Arg.getKind() == TemplateArgument::Pack &&
896 "Missing argument pack");
897
Douglas Gregor2be29f42011-01-14 23:41:42 +0000898 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +0000899 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +0000900
Douglas Gregord3731192011-01-10 07:32:04 +0000901 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor984a58b2010-12-20 22:48:17 +0000902 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
903 }
904
905 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000906 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000907 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000908
909 if (const TagType *Tag = T->getAs<TagType>())
910 return Tag->getDecl();
911
912 // The resulting type is not a tag; complain.
913 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
914 return 0;
915 }
916 }
917
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000918 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000919}
920
Douglas Gregor43959a92009-08-20 07:17:43 +0000921VarDecl *
922TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000923 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000924 SourceLocation StartLoc,
925 SourceLocation NameLoc,
926 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000927 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000928 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000929 if (Var)
930 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
931 return Var;
932}
933
934VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
935 TypeSourceInfo *TSInfo,
936 QualType T) {
937 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
938 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +0000939 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
940 return Var;
941}
942
John McCallc4e70192009-09-11 04:59:25 +0000943QualType
John McCall21e413f2010-11-04 19:04:38 +0000944TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
945 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000946 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000947 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +0000948 if (const TagType *TT = T->getAs<TagType>()) {
949 TagDecl* TD = TT->getDecl();
950
John McCall21e413f2010-11-04 19:04:38 +0000951 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +0000952
953 // FIXME: type might be anonymous.
954 IdentifierInfo *Id = TD->getIdentifier();
955
956 // TODO: should we even warn on struct/class mismatches for this? Seems
957 // like it's likely to produce a lot of spurious errors.
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000958 if (Keyword != ETK_None && Keyword != ETK_Typename) {
959 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +0000960 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
961 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000962 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
963 << Id
964 << FixItHint::CreateReplacement(SourceRange(TagLocation),
965 TD->getKindName());
966 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
967 }
John McCallc4e70192009-09-11 04:59:25 +0000968 }
969 }
970
John McCall21e413f2010-11-04 19:04:38 +0000971 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
972 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000973 QualifierLoc,
974 T);
John McCallc4e70192009-09-11 04:59:25 +0000975}
976
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000977TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
978 TemplateName Name,
979 SourceLocation NameLoc,
980 QualType ObjectType,
981 NamedDecl *FirstQualifierInScope) {
982 if (TemplateTemplateParmDecl *TTP
983 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
984 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
985 // If the corresponding template argument is NULL or non-existent, it's
986 // because we are performing instantiation from explicitly-specified
987 // template arguments in a function template, but there were some
988 // arguments left unspecified.
989 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
990 TTP->getPosition()))
991 return Name;
992
993 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
994
995 if (TTP->isParameterPack()) {
996 assert(Arg.getKind() == TemplateArgument::Pack &&
997 "Missing argument pack");
998
999 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1000 // We have the template argument pack to substitute, but we're not
1001 // actually expanding the enclosing pack expansion yet. So, just
1002 // keep the entire argument pack.
1003 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1004 }
1005
1006 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1007 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1008 }
1009
1010 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001011 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001012
Douglas Gregor58750382011-03-05 20:06:51 +00001013 // We don't ever want to substitute for a qualified template name, since
1014 // the qualifier is handled separately. So, look through the qualified
1015 // template name to its underlying declaration.
1016 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1017 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001018
1019 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001020 return Template;
1021 }
1022 }
1023
1024 if (SubstTemplateTemplateParmPackStorage *SubstPack
1025 = Name.getAsSubstTemplateTemplateParmPack()) {
1026 if (getSema().ArgumentPackSubstitutionIndex == -1)
1027 return Name;
1028
1029 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1030 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1031 "Pack substitution index out-of-range");
1032 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1033 .getAsTemplate();
1034 }
1035
1036 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1037 FirstQualifierInScope);
1038}
1039
John McCall60d7b3a2010-08-24 06:29:42 +00001040ExprResult
John McCall454feb92009-12-08 09:21:05 +00001041TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001042 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001043 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001044
1045 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1046 assert(currentDecl && "Must have current function declaration when "
1047 "instantiating.");
1048
1049 PredefinedExpr::IdentType IT = E->getIdentType();
1050
Anders Carlsson848fa642010-02-11 18:20:28 +00001051 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson773f3972009-09-11 01:22:35 +00001052
1053 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001054 QualType ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001055 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1056 ArrayType::Normal, 0);
1057 PredefinedExpr *PE =
1058 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1059 return getSema().Owned(PE);
1060}
1061
John McCall60d7b3a2010-08-24 06:29:42 +00001062ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001063TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001064 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001065 // If the corresponding template argument is NULL or non-existent, it's
1066 // because we are performing instantiation from explicitly-specified
1067 // template arguments in a function template, but there were some
1068 // arguments left unspecified.
1069 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1070 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001071 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001072
Douglas Gregor56bc9832010-12-24 00:15:10 +00001073 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1074 if (NTTP->isParameterPack()) {
1075 assert(Arg.getKind() == TemplateArgument::Pack &&
1076 "Missing argument pack");
1077
1078 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001079 // We have an argument pack, but we can't select a particular argument
1080 // out of it yet. Therefore, we'll build an expression to hold on to that
1081 // argument pack.
1082 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1083 E->getLocation(),
1084 NTTP->getDeclName());
1085 if (TargetType.isNull())
1086 return ExprError();
1087
1088 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1089 NTTP,
1090 E->getLocation(),
1091 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001092 }
1093
Douglas Gregord3731192011-01-10 07:32:04 +00001094 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor56bc9832010-12-24 00:15:10 +00001095 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1096 }
Mike Stump1eb44332009-09-09 15:08:12 +00001097
John McCall91a57552011-07-15 05:09:51 +00001098 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1099}
1100
1101ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1102 NonTypeTemplateParmDecl *parm,
1103 SourceLocation loc,
1104 const TemplateArgument &arg) {
1105 ExprResult result;
1106 QualType type;
1107
John McCallb8fc0532010-02-06 08:42:39 +00001108 // The template argument itself might be an expression, in which
1109 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001110 if (arg.getKind() == TemplateArgument::Expression) {
1111 Expr *argExpr = arg.getAsExpr();
1112 result = SemaRef.Owned(argExpr);
1113 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001114
John McCall91a57552011-07-15 05:09:51 +00001115 } else if (arg.getKind() == TemplateArgument::Declaration) {
1116 ValueDecl *VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001117
John McCall645cf442010-02-06 10:23:53 +00001118 // Find the instantiation of the template argument. This is
1119 // required for nested templates.
John McCallb8fc0532010-02-06 08:42:39 +00001120 VD = cast_or_null<ValueDecl>(
John McCall91a57552011-07-15 05:09:51 +00001121 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
John McCallb8fc0532010-02-06 08:42:39 +00001122 if (!VD)
John McCallf312b1e2010-08-26 23:41:50 +00001123 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001124
John McCall645cf442010-02-06 10:23:53 +00001125 // Derive the type we want the substituted decl to have. This had
1126 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001127 if (parm->isExpandedParameterPack()) {
1128 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1129 } else if (parm->isParameterPack() &&
1130 isa<PackExpansionType>(parm->getType())) {
1131 type = SemaRef.SubstType(
1132 cast<PackExpansionType>(parm->getType())->getPattern(),
1133 TemplateArgs, loc, parm->getDeclName());
1134 } else {
1135 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1136 loc, parm->getDeclName());
1137 }
1138 assert(!type.isNull() && "type substitution failed for param type");
1139 assert(!type->isDependentType() && "param type still dependent");
1140 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001141
John McCall91a57552011-07-15 05:09:51 +00001142 if (!result.isInvalid()) type = result.get()->getType();
1143 } else {
1144 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1145
1146 // Note that this type can be different from the type of 'result',
1147 // e.g. if it's an enum type.
1148 type = arg.getIntegralType();
1149 }
1150 if (result.isInvalid()) return ExprError();
1151
1152 Expr *resultExpr = result.take();
1153 return SemaRef.Owned(new (SemaRef.Context)
1154 SubstNonTypeTemplateParmExpr(type,
1155 resultExpr->getValueKind(),
1156 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001157}
1158
Douglas Gregorc7793c72011-01-15 01:15:58 +00001159ExprResult
1160TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1161 SubstNonTypeTemplateParmPackExpr *E) {
1162 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1163 // We aren't expanding the parameter pack, so just return ourselves.
1164 return getSema().Owned(E);
1165 }
1166
Douglas Gregorc7793c72011-01-15 01:15:58 +00001167 const TemplateArgument &ArgPack = E->getArgumentPack();
1168 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1169 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1170
1171 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
John McCall91a57552011-07-15 05:09:51 +00001172 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1173 E->getParameterPackLocation(),
1174 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001175}
John McCallb8fc0532010-02-06 08:42:39 +00001176
John McCall60d7b3a2010-08-24 06:29:42 +00001177ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001178TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1179 NamedDecl *D = E->getDecl();
1180 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1181 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1182 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001183
1184 // We have a non-type template parameter that isn't fully substituted;
1185 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001186 }
Mike Stump1eb44332009-09-09 15:08:12 +00001187
John McCall454feb92009-12-08 09:21:05 +00001188 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001189}
1190
John McCall60d7b3a2010-08-24 06:29:42 +00001191ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001192 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001193 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1194 getDescribedFunctionTemplate() &&
1195 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001196 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1197 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1198 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001199}
1200
Douglas Gregor895162d2010-04-30 18:55:50 +00001201QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001202 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001203 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001204 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001205 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001206}
1207
1208ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001209TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001210 int indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001211 llvm::Optional<unsigned> NumExpansions,
1212 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001213 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001214 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001215}
1216
Mike Stump1eb44332009-09-09 15:08:12 +00001217QualType
John McCalla2becad2009-10-21 00:40:46 +00001218TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001219 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001220 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001221 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001222 // Replace the template type parameter with its corresponding
1223 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001224
1225 // If the corresponding template argument is NULL or doesn't exist, it's
1226 // because we are performing instantiation from explicitly-specified
1227 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001228 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001229 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1230 TemplateTypeParmTypeLoc NewTL
1231 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1232 NewTL.setNameLoc(TL.getNameLoc());
1233 return TL.getType();
1234 }
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001236 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1237
1238 if (T->isParameterPack()) {
1239 assert(Arg.getKind() == TemplateArgument::Pack &&
1240 "Missing argument pack");
1241
1242 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001243 // We have the template argument pack, but we're not expanding the
1244 // enclosing pack expansion yet. Just save the template argument
1245 // pack for later substitution.
1246 QualType Result
1247 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1248 SubstTemplateTypeParmPackTypeLoc NewTL
1249 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1250 NewTL.setNameLoc(TL.getNameLoc());
1251 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001252 }
1253
Douglas Gregord3731192011-01-10 07:32:04 +00001254 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001255 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1256 }
1257
1258 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001259 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001260
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001261 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001262
1263 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001264 QualType Result
1265 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1266 SubstTemplateTypeParmTypeLoc NewTL
1267 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1268 NewTL.setNameLoc(TL.getNameLoc());
1269 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001270 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001271
1272 // The template type parameter comes from an inner template (e.g.,
1273 // the template parameter list of a member template inside the
1274 // template we are instantiating). Create a new template type
1275 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001276 TemplateTypeParmDecl *NewTTPDecl = 0;
1277 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1278 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1279 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1280
John McCalla2becad2009-10-21 00:40:46 +00001281 QualType Result
1282 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1283 - TemplateArgs.getNumLevels(),
1284 T->getIndex(),
1285 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001286 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001287 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1288 NewTL.setNameLoc(TL.getNameLoc());
1289 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001290}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001291
Douglas Gregorc3069d62011-01-14 02:55:32 +00001292QualType
1293TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1294 TypeLocBuilder &TLB,
1295 SubstTemplateTypeParmPackTypeLoc TL) {
1296 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1297 // We aren't expanding the parameter pack, so just return ourselves.
1298 SubstTemplateTypeParmPackTypeLoc NewTL
1299 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1300 NewTL.setNameLoc(TL.getNameLoc());
1301 return TL.getType();
1302 }
1303
1304 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1305 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1306 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1307
1308 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1309 Result = getSema().Context.getSubstTemplateTypeParmType(
1310 TL.getTypePtr()->getReplacedParameter(),
1311 Result);
1312 SubstTemplateTypeParmTypeLoc NewTL
1313 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1314 NewTL.setNameLoc(TL.getNameLoc());
1315 return Result;
1316}
1317
John McCallce3ff2b2009-08-25 22:02:44 +00001318/// \brief Perform substitution on the type T with a given set of template
1319/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001320///
1321/// This routine substitutes the given template arguments into the
1322/// type T and produces the instantiated type.
1323///
1324/// \param T the type into which the template arguments will be
1325/// substituted. If this type is not dependent, it will be returned
1326/// immediately.
1327///
1328/// \param TemplateArgs the template arguments that will be
1329/// substituted for the top-level template parameters within T.
1330///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001331/// \param Loc the location in the source code where this substitution
1332/// is being performed. It will typically be the location of the
1333/// declarator (if we're instantiating the type of some declaration)
1334/// or the location of the type in the source code (if, e.g., we're
1335/// instantiating the type of a cast expression).
1336///
1337/// \param Entity the name of the entity associated with a declaration
1338/// being instantiated (if any). May be empty to indicate that there
1339/// is no such entity (if, e.g., this is a type that occurs as part of
1340/// a cast expression) or that the entity has no name (e.g., an
1341/// unnamed function parameter).
1342///
1343/// \returns If the instantiation succeeds, the instantiated
1344/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001345TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001346 const MultiLevelTemplateArgumentList &Args,
1347 SourceLocation Loc,
1348 DeclarationName Entity) {
1349 assert(!ActiveTemplateInstantiations.empty() &&
1350 "Cannot perform an instantiation without some context on the "
1351 "instantiation stack");
1352
Douglas Gregor561f8122011-07-01 01:22:09 +00001353 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001354 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001355 return T;
1356
1357 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1358 return Instantiator.TransformType(T);
1359}
1360
Douglas Gregor603cfb42011-01-05 23:12:31 +00001361TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1362 const MultiLevelTemplateArgumentList &Args,
1363 SourceLocation Loc,
1364 DeclarationName Entity) {
1365 assert(!ActiveTemplateInstantiations.empty() &&
1366 "Cannot perform an instantiation without some context on the "
1367 "instantiation stack");
1368
1369 if (TL.getType().isNull())
1370 return 0;
1371
Douglas Gregor561f8122011-07-01 01:22:09 +00001372 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001373 !TL.getType()->isVariablyModifiedType()) {
1374 // FIXME: Make a copy of the TypeLoc data here, so that we can
1375 // return a new TypeSourceInfo. Inefficient!
1376 TypeLocBuilder TLB;
1377 TLB.pushFullCopy(TL);
1378 return TLB.getTypeSourceInfo(Context, TL.getType());
1379 }
1380
1381 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1382 TypeLocBuilder TLB;
1383 TLB.reserve(TL.getFullDataSize());
1384 QualType Result = Instantiator.TransformType(TLB, TL);
1385 if (Result.isNull())
1386 return 0;
1387
1388 return TLB.getTypeSourceInfo(Context, Result);
1389}
1390
John McCallcd7ba1c2009-10-21 00:58:09 +00001391/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001392QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001393 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001394 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001395 assert(!ActiveTemplateInstantiations.empty() &&
1396 "Cannot perform an instantiation without some context on the "
1397 "instantiation stack");
1398
Douglas Gregor836adf62010-05-24 17:22:01 +00001399 // If T is not a dependent type or a variably-modified type, there
1400 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001401 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001402 return T;
1403
Douglas Gregor577f75a2009-08-04 16:50:30 +00001404 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1405 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001406}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001407
John McCall6cd3b9f2010-04-09 17:38:44 +00001408static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001409 if (T->getType()->isInstantiationDependentType() ||
1410 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001411 return true;
1412
Abramo Bagnara723df242010-12-14 22:11:44 +00001413 TypeLoc TL = T->getTypeLoc().IgnoreParens();
John McCall6cd3b9f2010-04-09 17:38:44 +00001414 if (!isa<FunctionProtoTypeLoc>(TL))
1415 return false;
1416
1417 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1418 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1419 ParmVarDecl *P = FP.getArg(I);
1420
Douglas Gregorc056c172011-05-09 20:45:16 +00001421 // The parameter's type as written might be dependent even if the
1422 // decayed type was not dependent.
1423 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001424 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001425 return true;
1426
John McCall6cd3b9f2010-04-09 17:38:44 +00001427 // TODO: currently we always rebuild expressions. When we
1428 // properly get lazier about this, we should use the same
1429 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001430 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001431 return true;
1432 }
1433
1434 return false;
1435}
1436
1437/// A form of SubstType intended specifically for instantiating the
1438/// type of a FunctionDecl. Its purpose is solely to force the
1439/// instantiation of default-argument expressions.
1440TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1441 const MultiLevelTemplateArgumentList &Args,
1442 SourceLocation Loc,
1443 DeclarationName Entity) {
1444 assert(!ActiveTemplateInstantiations.empty() &&
1445 "Cannot perform an instantiation without some context on the "
1446 "instantiation stack");
1447
1448 if (!NeedsInstantiationAsFunctionType(T))
1449 return T;
1450
1451 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1452
1453 TypeLocBuilder TLB;
1454
1455 TypeLoc TL = T->getTypeLoc();
1456 TLB.reserve(TL.getFullDataSize());
1457
John McCall43fed0d2010-11-12 08:19:04 +00001458 QualType Result = Instantiator.TransformType(TLB, TL);
John McCall6cd3b9f2010-04-09 17:38:44 +00001459 if (Result.isNull())
1460 return 0;
1461
1462 return TLB.getTypeSourceInfo(Context, Result);
1463}
1464
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001465ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001466 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001467 int indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001468 llvm::Optional<unsigned> NumExpansions,
1469 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001470 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001471 TypeSourceInfo *NewDI = 0;
1472
Douglas Gregor603cfb42011-01-05 23:12:31 +00001473 TypeLoc OldTL = OldDI->getTypeLoc();
1474 if (isa<PackExpansionTypeLoc>(OldTL)) {
1475 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
Douglas Gregor603cfb42011-01-05 23:12:31 +00001476
1477 // We have a function parameter pack. Substitute into the pattern of the
1478 // expansion.
1479 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1480 OldParm->getLocation(), OldParm->getDeclName());
1481 if (!NewDI)
1482 return 0;
1483
1484 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1485 // We still have unexpanded parameter packs, which means that
1486 // our function parameter is still a function parameter pack.
1487 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001488 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001489 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001490 } else if (ExpectParameterPack) {
1491 // We expected to get a parameter pack but didn't (because the type
1492 // itself is not a pack expansion type), so complain. This can occur when
1493 // the substitution goes through an alias template that "loses" the
1494 // pack expansion.
1495 Diag(OldParm->getLocation(),
1496 diag::err_function_parameter_pack_without_parameter_packs)
1497 << NewDI->getType();
1498 return 0;
1499 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001500 } else {
1501 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1502 OldParm->getDeclName());
1503 }
1504
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001505 if (!NewDI)
1506 return 0;
1507
1508 if (NewDI->getType()->isVoidType()) {
1509 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1510 return 0;
1511 }
1512
1513 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001514 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001515 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001516 OldParm->getIdentifier(),
1517 NewDI->getType(), NewDI,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001518 OldParm->getStorageClass(),
1519 OldParm->getStorageClassAsWritten());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001520 if (!NewParm)
1521 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001522
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001523 // Mark the (new) default argument as uninstantiated (if any).
1524 if (OldParm->hasUninstantiatedDefaultArg()) {
1525 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1526 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001527 } else if (OldParm->hasUnparsedDefaultArg()) {
1528 NewParm->setUnparsedDefaultArg();
1529 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001530 } else if (Expr *Arg = OldParm->getDefaultArg())
1531 NewParm->setUninstantiatedDefaultArg(Arg);
1532
1533 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001534
Douglas Gregor12c9c002011-01-07 16:43:16 +00001535 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001536 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001537 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1538 } else {
1539 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001540 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001541 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001542
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001543 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1544 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001545 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001546
1547 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1548 OldParm->getFunctionScopeIndex() + indexAdjustment);
Fariborz Jahaniane7ffbe22010-07-13 20:05:58 +00001549
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001550 return NewParm;
1551}
1552
Douglas Gregora009b592011-01-07 00:20:55 +00001553/// \brief Substitute the given template arguments into the given set of
1554/// parameters, producing the set of parameter types that would be generated
1555/// from such a substitution.
1556bool Sema::SubstParmTypes(SourceLocation Loc,
1557 ParmVarDecl **Params, unsigned NumParams,
1558 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001559 SmallVectorImpl<QualType> &ParamTypes,
1560 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001561 assert(!ActiveTemplateInstantiations.empty() &&
1562 "Cannot perform an instantiation without some context on the "
1563 "instantiation stack");
1564
1565 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1566 DeclarationName());
1567 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001568 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001569}
1570
John McCallce3ff2b2009-08-25 22:02:44 +00001571/// \brief Perform substitution on the base class specifiers of the
1572/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001573///
1574/// Produces a diagnostic and returns true on error, returns false and
1575/// attaches the instantiated base classes to the class template
1576/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001577bool
John McCallce3ff2b2009-08-25 22:02:44 +00001578Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1579 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001580 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001581 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001582 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001583 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001584 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001585 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001586 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001587 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001588 continue;
1589 }
1590
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001591 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001592 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001593 if (Base->isPackExpansion()) {
1594 // This is a pack expansion. See whether we should expand it now, or
1595 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001596 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001597 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1598 Unexpanded);
1599 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001600 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00001601 llvm::Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001602 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1603 Base->getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001604 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001605 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001606 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001607 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001608 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001609 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001610 }
1611
1612 // If we should expand this pack expansion now, do so.
1613 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001614 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001615 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1616
1617 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1618 TemplateArgs,
1619 Base->getSourceRange().getBegin(),
1620 DeclarationName());
1621 if (!BaseTypeLoc) {
1622 Invalid = true;
1623 continue;
1624 }
1625
1626 if (CXXBaseSpecifier *InstantiatedBase
1627 = CheckBaseSpecifier(Instantiation,
1628 Base->getSourceRange(),
1629 Base->isVirtual(),
1630 Base->getAccessSpecifierAsWritten(),
1631 BaseTypeLoc,
1632 SourceLocation()))
1633 InstantiatedBases.push_back(InstantiatedBase);
1634 else
1635 Invalid = true;
1636 }
1637
1638 continue;
1639 }
1640
1641 // The resulting base specifier will (still) be a pack expansion.
1642 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001643 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1644 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1645 TemplateArgs,
1646 Base->getSourceRange().getBegin(),
1647 DeclarationName());
1648 } else {
1649 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1650 TemplateArgs,
1651 Base->getSourceRange().getBegin(),
1652 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001653 }
1654
Nick Lewycky56062202010-07-26 16:56:01 +00001655 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001656 Invalid = true;
1657 continue;
1658 }
1659
1660 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001661 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001662 Base->getSourceRange(),
1663 Base->isVirtual(),
1664 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001665 BaseTypeLoc,
1666 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001667 InstantiatedBases.push_back(InstantiatedBase);
1668 else
1669 Invalid = true;
1670 }
1671
Douglas Gregor27b152f2009-03-10 18:52:44 +00001672 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001673 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001674 InstantiatedBases.size()))
1675 Invalid = true;
1676
1677 return Invalid;
1678}
1679
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001680// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001681namespace clang {
1682 namespace sema {
1683 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1684 const MultiLevelTemplateArgumentList &TemplateArgs);
1685 }
1686}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001687
Richard Smithf1c66b42012-03-14 23:13:10 +00001688/// Determine whether we would be unable to instantiate this template (because
1689/// it either has no definition, or is in the process of being instantiated).
1690static bool DiagnoseUninstantiableTemplate(Sema &S,
1691 SourceLocation PointOfInstantiation,
1692 TagDecl *Instantiation,
1693 bool InstantiatedFromMember,
1694 TagDecl *Pattern,
1695 TagDecl *PatternDef,
1696 TemplateSpecializationKind TSK,
1697 bool Complain = true) {
1698 if (PatternDef && !PatternDef->isBeingDefined())
1699 return false;
1700
1701 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1702 // Say nothing
1703 } else if (PatternDef) {
1704 assert(PatternDef->isBeingDefined());
1705 S.Diag(PointOfInstantiation,
1706 diag::err_template_instantiate_within_definition)
1707 << (TSK != TSK_ImplicitInstantiation)
1708 << S.Context.getTypeDeclType(Instantiation);
1709 // Not much point in noting the template declaration here, since
1710 // we're lexically inside it.
1711 Instantiation->setInvalidDecl();
1712 } else if (InstantiatedFromMember) {
1713 S.Diag(PointOfInstantiation,
1714 diag::err_implicit_instantiate_member_undefined)
1715 << S.Context.getTypeDeclType(Instantiation);
1716 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1717 } else {
1718 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1719 << (TSK != TSK_ImplicitInstantiation)
1720 << S.Context.getTypeDeclType(Instantiation);
1721 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1722 }
1723
1724 // In general, Instantiation isn't marked invalid to get more than one
1725 // error for multiple undefined instantiations. But the code that does
1726 // explicit declaration -> explicit definition conversion can't handle
1727 // invalid declarations, so mark as invalid in that case.
1728 if (TSK == TSK_ExplicitInstantiationDeclaration)
1729 Instantiation->setInvalidDecl();
1730 return true;
1731}
1732
Douglas Gregord475b8d2009-03-25 21:17:03 +00001733/// \brief Instantiate the definition of a class from a given pattern.
1734///
1735/// \param PointOfInstantiation The point of instantiation within the
1736/// source code.
1737///
1738/// \param Instantiation is the declaration whose definition is being
1739/// instantiated. This will be either a class template specialization
1740/// or a member class of a class template specialization.
1741///
1742/// \param Pattern is the pattern from which the instantiation
1743/// occurs. This will be either the declaration of a class template or
1744/// the declaration of a member class of a class template.
1745///
1746/// \param TemplateArgs The template arguments to be substituted into
1747/// the pattern.
1748///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001749/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001750///
1751/// \param Complain whether to complain if the class cannot be instantiated due
1752/// to the lack of a definition.
1753///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001754/// \returns true if an error occurred, false otherwise.
1755bool
1756Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1757 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001758 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001759 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001760 bool Complain) {
Douglas Gregord475b8d2009-03-25 21:17:03 +00001761 bool Invalid = false;
John McCalle29ba202009-08-20 01:44:21 +00001762
Mike Stump1eb44332009-09-09 15:08:12 +00001763 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001764 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001765 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1766 Instantiation->getInstantiatedFromMemberClass(),
1767 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001768 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001769 Pattern = PatternDef;
1770
Douglas Gregor454885e2009-10-15 15:54:05 +00001771 // \brief Record the point of instantiation.
1772 if (MemberSpecializationInfo *MSInfo
1773 = Instantiation->getMemberSpecializationInfo()) {
1774 MSInfo->setTemplateSpecializationKind(TSK);
1775 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001776 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001777 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001778 Spec->setTemplateSpecializationKind(TSK);
1779 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001780 }
1781
Douglas Gregord048bb72009-03-25 21:23:52 +00001782 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001783 if (Inst)
1784 return true;
1785
1786 // Enter the scope of this instantiation. We don't use
1787 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001788 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001789 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001790 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001791
Douglas Gregor05030bb2010-03-24 01:33:17 +00001792 // If this is an instantiation of a local class, merge this local
1793 // instantiation scope with the enclosing scope. Otherwise, every
1794 // instantiation of a class has its own local instantiation scope.
1795 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001796 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001797
John McCall1d8d1cc2010-08-01 02:01:53 +00001798 // Pull attributes from the pattern onto the instantiation.
1799 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1800
Douglas Gregord475b8d2009-03-25 21:17:03 +00001801 // Start the definition of this instantiation.
1802 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00001803
1804 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001805
John McCallce3ff2b2009-08-25 22:02:44 +00001806 // Do substitution on the base class specifiers.
1807 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001808 Invalid = true;
1809
Douglas Gregord65587f2010-11-10 19:44:59 +00001810 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001811 SmallVector<Decl*, 4> Fields;
1812 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00001813 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001814 // Delay instantiation of late parsed attributes.
1815 LateInstantiatedAttrVec LateAttrs;
1816 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1817
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001818 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001819 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001820 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001821 // Don't instantiate members not belonging in this semantic context.
1822 // e.g. for:
1823 // @code
1824 // template <int i> class A {
1825 // class B *g;
1826 // };
1827 // @endcode
1828 // 'class B' has the template as lexical context but semantically it is
1829 // introduced in namespace scope.
1830 if ((*Member)->getDeclContext() != Pattern)
1831 continue;
1832
Douglas Gregord65587f2010-11-10 19:44:59 +00001833 if ((*Member)->isInvalidDecl()) {
1834 Invalid = true;
1835 continue;
1836 }
1837
1838 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001839 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00001840 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00001841 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00001842 FieldDecl *OldField = cast<FieldDecl>(*Member);
1843 if (OldField->getInClassInitializer())
1844 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
1845 Field));
1846 } else if (NewMember->isInvalidDecl())
Eli Friedman721e77d2009-12-07 00:22:08 +00001847 Invalid = true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001848 } else {
1849 // FIXME: Eventually, a NULL return will mean that one of the
Mike Stump390b4cc2009-05-16 07:39:55 +00001850 // instantiations was a semantic disaster, and we'll want to set Invalid =
1851 // true. For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00001852 }
1853 }
1854
1855 // Finish checking fields.
David Blaikie77b6de02011-09-22 02:58:26 +00001856 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
1857 SourceLocation(), SourceLocation(), 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00001858 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00001859
1860 // Attach any in-class member initializers now the class is complete.
1861 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
1862 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
1863 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
1864 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00001865
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001866 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
1867 /*CXXDirectInit=*/false);
1868 if (NewInit.isInvalid())
Richard Smith7a614d82011-06-11 17:19:42 +00001869 NewField->setInvalidDecl();
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001870 else {
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00001871 Expr *Init = NewInit.take();
1872 assert(Init && "no-argument initializer in class");
1873 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
1874 ActOnCXXInClassMemberInitializer(NewField,
1875 Init->getSourceRange().getBegin(), Init);
Richard Smith0ff6f8f2011-07-20 00:12:52 +00001876 }
Richard Smith7a614d82011-06-11 17:19:42 +00001877 }
1878
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001879 // Instantiate late parsed attributes, and attach them to their decls.
1880 // See Sema::InstantiateAttrs
1881 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
1882 E = LateAttrs.end(); I != E; ++I) {
1883 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
1884 CurrentInstantiationScope = I->Scope;
1885 Attr *NewAttr =
1886 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
1887 I->NewDecl->addAttr(NewAttr);
1888 LocalInstantiationScope::deleteScopes(I->Scope,
1889 Instantiator.getStartingScope());
1890 }
1891 Instantiator.disableLateAttributeInstantiation();
1892 LateAttrs.clear();
1893
Richard Smith7a614d82011-06-11 17:19:42 +00001894 if (!FieldsWithMemberInitializers.empty())
1895 ActOnFinishDelayedMemberInitializers(Instantiation);
1896
Abramo Bagnarae9946242011-11-18 08:08:52 +00001897 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00001898 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00001899 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00001900 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00001901 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00001902
Douglas Gregor663b5a02009-10-14 20:14:33 +00001903 if (Instantiation->isInvalidDecl())
1904 Invalid = true;
Douglas Gregord65587f2010-11-10 19:44:59 +00001905 else {
1906 // Instantiate any out-of-line class template partial
1907 // specializations now.
1908 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
1909 P = Instantiator.delayed_partial_spec_begin(),
1910 PEnd = Instantiator.delayed_partial_spec_end();
1911 P != PEnd; ++P) {
1912 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
1913 P->first,
1914 P->second)) {
1915 Invalid = true;
1916 break;
1917 }
1918 }
1919 }
1920
Douglas Gregord475b8d2009-03-25 21:17:03 +00001921 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00001922 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001923
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001924 if (!Invalid) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001925 Consumer.HandleTagDeclDefinition(Instantiation);
1926
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001927 // Always emit the vtable for an explicit instantiation definition
1928 // of a polymorphic class template specialization.
1929 if (TSK == TSK_ExplicitInstantiationDefinition)
1930 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
1931 }
1932
Douglas Gregord475b8d2009-03-25 21:17:03 +00001933 return Invalid;
1934}
1935
Richard Smithf1c66b42012-03-14 23:13:10 +00001936/// \brief Instantiate the definition of an enum from a given pattern.
1937///
1938/// \param PointOfInstantiation The point of instantiation within the
1939/// source code.
1940/// \param Instantiation is the declaration whose definition is being
1941/// instantiated. This will be a member enumeration of a class
1942/// temploid specialization, or a local enumeration within a
1943/// function temploid specialization.
1944/// \param Pattern The templated declaration from which the instantiation
1945/// occurs.
1946/// \param TemplateArgs The template arguments to be substituted into
1947/// the pattern.
1948/// \param TSK The kind of implicit or explicit instantiation to perform.
1949///
1950/// \return \c true if an error occurred, \c false otherwise.
1951bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
1952 EnumDecl *Instantiation, EnumDecl *Pattern,
1953 const MultiLevelTemplateArgumentList &TemplateArgs,
1954 TemplateSpecializationKind TSK) {
1955 EnumDecl *PatternDef = Pattern->getDefinition();
1956 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1957 Instantiation->getInstantiatedFromMemberEnum(),
1958 Pattern, PatternDef, TSK,/*Complain*/true))
1959 return true;
1960 Pattern = PatternDef;
1961
1962 // Record the point of instantiation.
1963 if (MemberSpecializationInfo *MSInfo
1964 = Instantiation->getMemberSpecializationInfo()) {
1965 MSInfo->setTemplateSpecializationKind(TSK);
1966 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1967 }
1968
1969 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1970 if (Inst)
1971 return true;
1972
1973 // Enter the scope of this instantiation. We don't use
1974 // PushDeclContext because we don't have a scope.
1975 ContextRAII SavedContext(*this, Instantiation);
1976 EnterExpressionEvaluationContext EvalContext(*this,
1977 Sema::PotentiallyEvaluated);
1978
1979 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
1980
1981 // Pull attributes from the pattern onto the instantiation.
1982 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1983
1984 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
1985 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
1986
1987 // Exit the scope of this instantiation.
1988 SavedContext.pop();
1989
1990 return Instantiation->isInvalidDecl();
1991}
1992
Douglas Gregor9b623632010-10-12 23:32:35 +00001993namespace {
1994 /// \brief A partial specialization whose template arguments have matched
1995 /// a given template-id.
1996 struct PartialSpecMatchResult {
1997 ClassTemplatePartialSpecializationDecl *Partial;
1998 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00001999 };
2000}
2001
Mike Stump1eb44332009-09-09 15:08:12 +00002002bool
Douglas Gregor2943aed2009-03-03 04:44:36 +00002003Sema::InstantiateClassTemplateSpecialization(
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002004 SourceLocation PointOfInstantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00002005 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002006 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002007 bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002008 // Perform the actual instantiation on the canonical declaration.
2009 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002010 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002011
Douglas Gregor52604ab2009-09-11 21:19:12 +00002012 // Check whether we have already instantiated or specialized this class
2013 // template specialization.
2014 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2015 if (ClassTemplateSpec->getSpecializationKind() ==
2016 TSK_ExplicitInstantiationDeclaration &&
2017 TSK == TSK_ExplicitInstantiationDefinition) {
2018 // An explicit instantiation definition follows an explicit instantiation
2019 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2020 // explicit instantiation.
2021 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002022
2023 // If this is an explicit instantiation definition, mark the
2024 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002025 if (TSK == TSK_ExplicitInstantiationDefinition &&
2026 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002027 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2028
Douglas Gregor52604ab2009-09-11 21:19:12 +00002029 return false;
2030 }
2031
2032 // We can only instantiate something that hasn't already been
2033 // instantiated or specialized. Fail without any diagnostics: our
2034 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002035 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002036 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002037
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002038 if (ClassTemplateSpec->isInvalidDecl())
2039 return true;
2040
Douglas Gregor2943aed2009-03-03 04:44:36 +00002041 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00002042 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002043
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002044 // C++ [temp.class.spec.match]p1:
2045 // When a class template is used in a context that requires an
2046 // instantiation of the class, it is necessary to determine
2047 // whether the instantiation is to be generated using the primary
2048 // template or one of the partial specializations. This is done by
2049 // matching the template arguments of the class template
2050 // specialization with the template argument lists of the partial
2051 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002052 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002053 SmallVector<MatchResult, 4> Matched;
2054 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002055 Template->getPartialSpecializations(PartialSpecs);
2056 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2057 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
John McCall5769d612010-02-08 23:07:23 +00002058 TemplateDeductionInfo Info(Context, PointOfInstantiation);
Douglas Gregorf67875d2009-06-12 18:26:56 +00002059 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002060 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002061 ClassTemplateSpec->getTemplateArgs(),
2062 Info)) {
2063 // FIXME: Store the failed-deduction information for use in
2064 // diagnostics, later.
2065 (void)Result;
2066 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002067 Matched.push_back(PartialSpecMatchResult());
2068 Matched.back().Partial = Partial;
2069 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002070 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002071 }
2072
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002073 // If we're dealing with a member template where the template parameters
2074 // have been instantiated, this provides the original template parameters
2075 // from which the member template's parameters were instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002076 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002077
Douglas Gregored9c0f92009-10-29 00:04:11 +00002078 if (Matched.size() >= 1) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002079 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002080 if (Matched.size() == 1) {
2081 // -- If exactly one matching specialization is found, the
2082 // instantiation is generated from that specialization.
2083 // We don't need to do anything for this.
2084 } else {
2085 // -- If more than one matching specialization is found, the
2086 // partial order rules (14.5.4.2) are used to determine
2087 // whether one of the specializations is more specialized
2088 // than the others. If none of the specializations is more
2089 // specialized than all of the other matching
2090 // specializations, then the use of the class template is
2091 // ambiguous and the program is ill-formed.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002092 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002093 PEnd = Matched.end();
2094 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002095 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002096 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002097 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002098 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002099 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002100
Douglas Gregored9c0f92009-10-29 00:04:11 +00002101 // Determine if the best partial specialization is more specialized than
2102 // the others.
2103 bool Ambiguous = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002104 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002105 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002106 P != PEnd; ++P) {
2107 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002108 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002109 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002110 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002111 Ambiguous = true;
2112 break;
2113 }
2114 }
2115
2116 if (Ambiguous) {
2117 // Partial ordering did not produce a clear winner. Complain.
2118 ClassTemplateSpec->setInvalidDecl();
2119 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2120 << ClassTemplateSpec;
2121
2122 // Print the matching partial specializations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002123 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002124 PEnd = Matched.end();
2125 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002126 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2127 << getTemplateArgumentBindingsText(
2128 P->Partial->getTemplateParameters(),
2129 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002130
Douglas Gregored9c0f92009-10-29 00:04:11 +00002131 return true;
2132 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002133 }
2134
2135 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002136 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002137 while (OrigPartialSpec->getInstantiatedFromMember()) {
2138 // If we've found an explicit specialization of this class template,
2139 // stop here and use that as the pattern.
2140 if (OrigPartialSpec->isMemberSpecialization())
2141 break;
2142
2143 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2144 }
2145
2146 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002147 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002148 } else {
2149 // -- If no matches are found, the instantiation is generated
2150 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002151 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002152 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2153 // If we've found an explicit specialization of this class template,
2154 // stop here and use that as the pattern.
2155 if (OrigTemplate->isMemberSpecialization())
2156 break;
2157
Douglas Gregord6350ae2009-08-28 20:31:08 +00002158 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002159 }
2160
Douglas Gregord6350ae2009-08-28 20:31:08 +00002161 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002162 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002163
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002164 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2165 Pattern,
2166 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002167 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002168 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002169
Douglas Gregor199d9912009-06-05 00:53:49 +00002170 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002171}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002172
John McCallce3ff2b2009-08-25 22:02:44 +00002173/// \brief Instantiates the definitions of all of the member
2174/// of the given class, which is an instantiation of a class template
2175/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002176void
2177Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002178 CXXRecordDecl *Instantiation,
2179 const MultiLevelTemplateArgumentList &TemplateArgs,
2180 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002181 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2182 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002183 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002184 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002185 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002186 if (FunctionDecl *Pattern
2187 = Function->getInstantiatedFromMemberFunction()) {
2188 MemberSpecializationInfo *MSInfo
2189 = Function->getMemberSpecializationInfo();
2190 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002191 if (MSInfo->getTemplateSpecializationKind()
2192 == TSK_ExplicitSpecialization)
2193 continue;
2194
Douglas Gregor0d035142009-10-27 18:42:08 +00002195 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2196 Function,
2197 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002198 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002199 SuppressNew) ||
2200 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002201 continue;
2202
Sean Hunt10620eb2011-05-06 20:44:56 +00002203 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002204 continue;
2205
2206 if (TSK == TSK_ExplicitInstantiationDefinition) {
2207 // C++0x [temp.explicit]p8:
2208 // An explicit instantiation definition that names a class template
2209 // specialization explicitly instantiates the class template
2210 // specialization and is only an explicit instantiation definition
2211 // of members whose definition is visible at the point of
2212 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002213 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002214 continue;
2215
2216 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2217
2218 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2219 } else {
2220 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2221 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002222 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002223 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002224 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002225 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2226 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002227 if (MSInfo->getTemplateSpecializationKind()
2228 == TSK_ExplicitSpecialization)
2229 continue;
2230
Douglas Gregor0d035142009-10-27 18:42:08 +00002231 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2232 Var,
2233 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002234 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002235 SuppressNew) ||
2236 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002237 continue;
2238
Douglas Gregor0d035142009-10-27 18:42:08 +00002239 if (TSK == TSK_ExplicitInstantiationDefinition) {
2240 // C++0x [temp.explicit]p8:
2241 // An explicit instantiation definition that names a class template
2242 // specialization explicitly instantiates the class template
2243 // specialization and is only an explicit instantiation definition
2244 // of members whose definition is visible at the point of
2245 // instantiation.
2246 if (!Var->getInstantiatedFromStaticDataMember()
2247 ->getOutOfLineDefinition())
2248 continue;
2249
2250 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002251 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002252 } else {
2253 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2254 }
2255 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002256 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002257 // Always skip the injected-class-name, along with any
2258 // redeclarations of nested classes, since both would cause us
2259 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002260 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002261 continue;
2262
Douglas Gregor0d035142009-10-27 18:42:08 +00002263 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2264 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002265
2266 if (MSInfo->getTemplateSpecializationKind()
2267 == TSK_ExplicitSpecialization)
2268 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002269
Douglas Gregor0d035142009-10-27 18:42:08 +00002270 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2271 Record,
2272 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002273 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002274 SuppressNew) ||
2275 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002276 continue;
2277
Douglas Gregor0d035142009-10-27 18:42:08 +00002278 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2279 assert(Pattern && "Missing instantiated-from-template information");
2280
Douglas Gregor952b0172010-02-11 01:04:33 +00002281 if (!Record->getDefinition()) {
2282 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002283 // C++0x [temp.explicit]p8:
2284 // An explicit instantiation definition that names a class template
2285 // specialization explicitly instantiates the class template
2286 // specialization and is only an explicit instantiation definition
2287 // of members whose definition is visible at the point of
2288 // instantiation.
2289 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2290 MSInfo->setTemplateSpecializationKind(TSK);
2291 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2292 }
2293
2294 continue;
2295 }
2296
2297 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002298 TemplateArgs,
2299 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002300 } else {
2301 if (TSK == TSK_ExplicitInstantiationDefinition &&
2302 Record->getTemplateSpecializationKind() ==
2303 TSK_ExplicitInstantiationDeclaration) {
2304 Record->setTemplateSpecializationKind(TSK);
2305 MarkVTableUsed(PointOfInstantiation, Record, true);
2306 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002307 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002308
Douglas Gregor952b0172010-02-11 01:04:33 +00002309 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002310 if (Pattern)
2311 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2312 TSK);
Richard Smithf1c66b42012-03-14 23:13:10 +00002313 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2314 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2315 assert(MSInfo && "No member specialization information?");
2316
2317 if (MSInfo->getTemplateSpecializationKind()
2318 == TSK_ExplicitSpecialization)
2319 continue;
2320
2321 if (CheckSpecializationInstantiationRedecl(
2322 PointOfInstantiation, TSK, Enum,
2323 MSInfo->getTemplateSpecializationKind(),
2324 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2325 SuppressNew)
2326 continue;
2327
2328 if (Enum->getDefinition())
2329 continue;
2330
2331 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2332 assert(Pattern && "Missing instantiated-from-template information");
2333
2334 if (TSK == TSK_ExplicitInstantiationDefinition) {
2335 if (!Pattern->getDefinition())
2336 continue;
2337
2338 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2339 } else {
2340 MSInfo->setTemplateSpecializationKind(TSK);
2341 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2342 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002343 }
2344 }
2345}
2346
2347/// \brief Instantiate the definitions of all of the members of the
2348/// given class template specialization, which was named as part of an
2349/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002350void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002351Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002352 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002353 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2354 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002355 // C++0x [temp.explicit]p7:
2356 // An explicit instantiation that names a class template
2357 // specialization is an explicit instantion of the same kind
2358 // (declaration or definition) of each of its members (not
2359 // including members inherited from base classes) that has not
2360 // been previously explicitly specialized in the translation unit
2361 // containing the explicit instantiation, except as described
2362 // below.
2363 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002364 getTemplateInstantiationArgs(ClassTemplateSpec),
2365 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002366}
2367
John McCall60d7b3a2010-08-24 06:29:42 +00002368StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002369Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002370 if (!S)
2371 return Owned(S);
2372
2373 TemplateInstantiator Instantiator(*this, TemplateArgs,
2374 SourceLocation(),
2375 DeclarationName());
2376 return Instantiator.TransformStmt(S);
2377}
2378
John McCall60d7b3a2010-08-24 06:29:42 +00002379ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002380Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002381 if (!E)
2382 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002383
Douglas Gregorb98b1992009-08-11 05:31:07 +00002384 TemplateInstantiator Instantiator(*this, TemplateArgs,
2385 SourceLocation(),
2386 DeclarationName());
2387 return Instantiator.TransformExpr(E);
2388}
2389
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002390bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2391 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002392 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002393 if (NumExprs == 0)
2394 return false;
2395
2396 TemplateInstantiator Instantiator(*this, TemplateArgs,
2397 SourceLocation(),
2398 DeclarationName());
2399 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2400}
2401
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002402NestedNameSpecifierLoc
2403Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2404 const MultiLevelTemplateArgumentList &TemplateArgs) {
2405 if (!NNS)
2406 return NestedNameSpecifierLoc();
2407
2408 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2409 DeclarationName());
2410 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2411}
2412
Abramo Bagnara25777432010-08-11 22:01:17 +00002413/// \brief Do template substitution on declaration name info.
2414DeclarationNameInfo
2415Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2416 const MultiLevelTemplateArgumentList &TemplateArgs) {
2417 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2418 NameInfo.getName());
2419 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2420}
2421
Douglas Gregorde650ae2009-03-31 18:38:02 +00002422TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002423Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2424 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002425 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002426 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2427 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002428 CXXScopeSpec SS;
2429 SS.Adopt(QualifierLoc);
2430 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002431}
Douglas Gregor91333002009-06-11 00:06:24 +00002432
Douglas Gregore02e2622010-12-22 21:19:48 +00002433bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2434 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002435 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002436 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2437 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002438
2439 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002440}
Douglas Gregor895162d2010-04-30 18:55:50 +00002441
Douglas Gregor12c9c002011-01-07 16:43:16 +00002442llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2443LocalInstantiationScope::findInstantiationOf(const Decl *D) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002444 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002445 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002446
Douglas Gregor895162d2010-04-30 18:55:50 +00002447 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002448 const Decl *CheckD = D;
2449 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002450 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002451 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002452 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002453
2454 // If this is a tag declaration, it's possible that we need to look for
2455 // a previous declaration.
2456 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002457 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002458 else
2459 CheckD = 0;
2460 } while (CheckD);
2461
Douglas Gregor895162d2010-04-30 18:55:50 +00002462 // If we aren't combined with our outer scope, we're done.
2463 if (!Current->CombineWithOuterScope)
2464 break;
2465 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002466
2467 // If we didn't find the decl, then we either have a sema bug, or we have a
2468 // forward reference to a label declaration. Return null to indicate that
2469 // we have an uninstantiated label.
2470 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002471 return 0;
2472}
2473
John McCall2a7fb272010-08-25 05:32:35 +00002474void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002475 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002476 if (Stored.isNull())
2477 Stored = Inst;
2478 else if (Stored.is<Decl *>()) {
2479 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2480 Stored = Inst;
2481 } else
2482 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
Douglas Gregor895162d2010-04-30 18:55:50 +00002483}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002484
2485void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2486 Decl *Inst) {
2487 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2488 Pack->push_back(Inst);
2489}
2490
2491void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2492 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2493 assert(Stored.isNull() && "Already instantiated this local");
2494 DeclArgumentPack *Pack = new DeclArgumentPack;
2495 Stored = Pack;
2496 ArgumentPacks.push_back(Pack);
2497}
2498
Douglas Gregord3731192011-01-10 07:32:04 +00002499void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2500 const TemplateArgument *ExplicitArgs,
2501 unsigned NumExplicitArgs) {
2502 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2503 "Already have a partially-substituted pack");
2504 assert((!PartiallySubstitutedPack
2505 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2506 "Wrong number of arguments in partially-substituted pack");
2507 PartiallySubstitutedPack = Pack;
2508 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2509 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2510}
2511
2512NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2513 const TemplateArgument **ExplicitArgs,
2514 unsigned *NumExplicitArgs) const {
2515 if (ExplicitArgs)
2516 *ExplicitArgs = 0;
2517 if (NumExplicitArgs)
2518 *NumExplicitArgs = 0;
2519
2520 for (const LocalInstantiationScope *Current = this; Current;
2521 Current = Current->Outer) {
2522 if (Current->PartiallySubstitutedPack) {
2523 if (ExplicitArgs)
2524 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2525 if (NumExplicitArgs)
2526 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2527
2528 return Current->PartiallySubstitutedPack;
2529 }
2530
2531 if (!Current->CombineWithOuterScope)
2532 break;
2533 }
2534
2535 return 0;
2536}