blob: 6936539f1caaa5a19712933e84d39c932706c067 [file] [log] [blame]
Douglas Gregord7e7a512009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations.
10//
11//===----------------------------------------------------------------------===/
John McCall83024632010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregor28ad4b52009-05-26 20:50:29 +000013#include "clang/AST/ASTConsumer.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000014#include "clang/AST/ASTContext.h"
Richard Smithd28ac5b2014-03-22 23:33:22 +000015#include "clang/AST/ASTMutationListener.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000016#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
John McCallc62bb642010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregor6131b442009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.h"
John McCall58f10c32010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Template.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000025
26using namespace clang;
27
David Majnemer192d1792013-11-27 08:20:38 +000028static bool isDeclWithinFunction(const Decl *D) {
29 const DeclContext *DC = D->getDeclContext();
30 if (DC->isFunctionOrMethod())
31 return true;
32
33 if (DC->isRecord())
34 return cast<CXXRecordDecl>(DC)->isLocalClass();
35
36 return false;
37}
38
Richard Smithcc928662014-10-17 20:37:29 +000039template<typename DeclT>
40static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
41 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor14454802011-02-25 02:25:35 +000042 if (!OldDecl->getQualifierLoc())
43 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000044
Richard Smithcc928662014-10-17 20:37:29 +000045 assert((NewDecl->getFriendObjectKind() ||
46 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&
47 "non-friend with qualified name defined in dependent context");
48 Sema::ContextRAII SavedContext(
49 SemaRef,
50 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
51 ? NewDecl->getLexicalDeclContext()
52 : OldDecl->getLexicalDeclContext()));
53
Douglas Gregor14454802011-02-25 02:25:35 +000054 NestedNameSpecifierLoc NewQualifierLoc
Richard Smithcc928662014-10-17 20:37:29 +000055 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
56 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000057
Douglas Gregor14454802011-02-25 02:25:35 +000058 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000059 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000060
Douglas Gregor14454802011-02-25 02:25:35 +000061 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000062 return false;
63}
64
Richard Smithcc928662014-10-17 20:37:29 +000065bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
66 DeclaratorDecl *NewDecl) {
67 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
68}
69
John McCall3e11ebe2010-03-15 10:12:16 +000070bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
71 TagDecl *NewDecl) {
Richard Smithcc928662014-10-17 20:37:29 +000072 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
John McCall3e11ebe2010-03-15 10:12:16 +000073}
74
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000075// Include attribute instantiation code.
76#include "clang/Sema/AttrTemplateInstantiate.inc"
77
Richard Smith44c247f2013-02-22 08:32:16 +000078static void instantiateDependentAlignedAttr(
79 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
80 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
81 if (Aligned->isAlignmentExpr()) {
82 // The alignment expression is a constant expression.
83 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
84 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
85 if (!Result.isInvalid())
Nikola Smiljanic01a75982014-05-29 10:55:11 +000086 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
Richard Smith44c247f2013-02-22 08:32:16 +000087 Aligned->getSpellingListIndex(), IsPackExpansion);
88 } else {
89 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
90 TemplateArgs, Aligned->getLocation(),
91 DeclarationName());
92 if (Result)
93 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
94 Aligned->getSpellingListIndex(), IsPackExpansion);
95 }
96}
97
98static void instantiateDependentAlignedAttr(
99 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
100 const AlignedAttr *Aligned, Decl *New) {
101 if (!Aligned->isPackExpansion()) {
102 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
103 return;
104 }
105
106 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
107 if (Aligned->isAlignmentExpr())
108 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
109 Unexpanded);
110 else
111 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
112 Unexpanded);
113 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
114
115 // Determine whether we can expand this attribute pack yet.
116 bool Expand = true, RetainExpansion = false;
117 Optional<unsigned> NumExpansions;
118 // FIXME: Use the actual location of the ellipsis.
119 SourceLocation EllipsisLoc = Aligned->getLocation();
120 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
121 Unexpanded, TemplateArgs, Expand,
122 RetainExpansion, NumExpansions))
123 return;
124
125 if (!Expand) {
126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
128 } else {
129 for (unsigned I = 0; I != *NumExpansions; ++I) {
130 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
131 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
132 }
133 }
134}
135
Hal Finkelee90a222014-09-26 05:04:30 +0000136static void instantiateDependentAssumeAlignedAttr(
137 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
138 const AssumeAlignedAttr *Aligned, Decl *New) {
139 // The alignment expression is a constant expression.
140 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
141
142 Expr *E, *OE = nullptr;
143 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
144 if (Result.isInvalid())
145 return;
146 E = Result.getAs<Expr>();
147
148 if (Aligned->getOffset()) {
149 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
150 if (Result.isInvalid())
151 return;
152 OE = Result.getAs<Expr>();
153 }
154
155 S.AddAssumeAlignedAttr(Aligned->getLocation(), New, E, OE,
156 Aligned->getSpellingListIndex());
157}
158
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000159static void instantiateDependentAlignValueAttr(
160 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
161 const AlignValueAttr *Aligned, Decl *New) {
162 // The alignment expression is a constant expression.
163 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
164 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
165 if (!Result.isInvalid())
166 S.AddAlignValueAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
167 Aligned->getSpellingListIndex());
168}
169
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000170static void instantiateDependentEnableIfAttr(
171 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
172 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000173 Expr *Cond = nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000174 {
175 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
176 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
177 if (Result.isInvalid())
178 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000179 Cond = Result.getAs<Expr>();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000180 }
181 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
182 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
183 if (Converted.isInvalid())
184 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000185 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000186 }
187
188 SmallVector<PartialDiagnosticAt, 8> Diags;
189 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
190 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
191 Diags)) {
192 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
193 for (int I = 0, N = Diags.size(); I != N; ++I)
194 S.Diag(Diags[I].first, Diags[I].second);
195 return;
196 }
197
Aaron Ballman36a53502014-01-16 13:03:14 +0000198 EnableIfAttr *EIA = new (S.getASTContext())
199 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
200 A->getMessage(),
201 A->getSpellingListIndex());
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000202 New->addAttr(EIA);
203}
204
John McCall6602bb12010-08-01 02:01:53 +0000205void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000206 const Decl *Tmpl, Decl *New,
207 LateInstantiatedAttrVec *LateAttrs,
208 LocalInstantiationScope *OuterMostScope) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000209 for (const auto *TmplAttr : Tmpl->attrs()) {
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000210 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000211 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
212 if (Aligned && Aligned->isAlignmentDependent()) {
213 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
214 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000215 }
216
Hal Finkelee90a222014-09-26 05:04:30 +0000217 const AssumeAlignedAttr *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr);
218 if (AssumeAligned) {
219 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
220 continue;
221 }
222
Hal Finkel1b0d24e2014-10-02 21:21:25 +0000223 const AlignValueAttr *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr);
224 if (AlignValue) {
225 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
226 continue;
227 }
228
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000229 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
230 if (EnableIf && EnableIf->getCond()->isValueDependent()) {
231 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
232 New);
233 continue;
234 }
235
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +0000236 // Existing DLL attribute on the instantiation takes precedence.
237 if (TmplAttr->getKind() == attr::DLLExport ||
238 TmplAttr->getKind() == attr::DLLImport) {
239 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
240 continue;
241 }
242 }
243
Richard Smith44c247f2013-02-22 08:32:16 +0000244 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000245 if (TmplAttr->isLateParsed() && LateAttrs) {
246 // Late parsed attributes must be instantiated and attached after the
247 // enclosing class has been instantiated. See Sema::InstantiateClass.
Craig Topperc3ec1492014-05-26 06:22:03 +0000248 LocalInstantiationScope *Saved = nullptr;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000249 if (CurrentInstantiationScope)
250 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
251 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
252 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000253 // Allow 'this' within late-parsed attributes.
254 NamedDecl *ND = dyn_cast<NamedDecl>(New);
255 CXXRecordDecl *ThisContext =
256 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
257 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
258 ND && ND->isCXXInstanceMember());
259
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000260 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
261 *this, TemplateArgs);
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000262 if (NewAttr)
263 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000264 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000265 }
266}
267
Richard Smith41c79d92014-10-11 00:37:16 +0000268/// Get the previous declaration of a declaration for the purposes of template
269/// instantiation. If this finds a previous declaration, then the previous
270/// declaration of the instantiation of D should be an instantiation of the
271/// result of this function.
272template<typename DeclT>
273static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
274 DeclT *Result = D->getPreviousDecl();
275
276 // If the declaration is within a class, and the previous declaration was
277 // merged from a different definition of that class, then we don't have a
278 // previous declaration for the purpose of template instantiation.
279 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
280 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
281 return nullptr;
282
283 return Result;
284}
285
Douglas Gregor8a655532009-03-25 15:45:12 +0000286Decl *
287TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000288 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000289}
290
291Decl *
Richard Smithf19e1272015-03-07 00:04:49 +0000292TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
293 llvm_unreachable("extern \"C\" context cannot be instantiated");
294}
295
296Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000297TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
298 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
299 D->getIdentifier());
300 Owner->addDecl(Inst);
301 return Inst;
302}
303
304Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000305TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000306 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000307}
308
John McCalld8d0d432010-02-16 06:53:13 +0000309Decl *
310TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
311 NamespaceAliasDecl *Inst
312 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
313 D->getNamespaceLoc(),
314 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000315 D->getIdentifier(),
316 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000317 D->getTargetNameLoc(),
318 D->getNamespace());
319 Owner->addDecl(Inst);
320 return Inst;
321}
322
Richard Smith3f1b5d02011-05-05 21:57:07 +0000323Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
324 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000325 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000326 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000327 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000328 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000329 DI = SemaRef.SubstType(DI, TemplateArgs,
330 D->getLocation(), D->getDeclName());
331 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000332 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000333 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000334 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000335 } else {
336 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000337 }
Mike Stump11289f42009-09-09 15:08:12 +0000338
Richard Smith2ddcbab2012-10-23 00:32:41 +0000339 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
340 // libstdc++ relies upon this bug in its implementation of common_type.
341 // If we happen to be processing that implementation, fake up the g++ ?:
342 // semantics. See LWG issue 2141 for more information on the bug.
343 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
344 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
345 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
346 DT->isReferenceType() &&
347 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
348 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
349 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
350 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
351 // Fold it to the (non-reference) type which g++ would have produced.
352 DI = SemaRef.Context.getTrivialTypeSourceInfo(
353 DI->getType().getNonReferenceType());
354
Douglas Gregord7e7a512009-03-17 21:15:40 +0000355 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000356 TypedefNameDecl *Typedef;
357 if (IsTypeAlias)
358 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
359 D->getLocation(), D->getIdentifier(), DI);
360 else
361 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
362 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000363 if (Invalid)
364 Typedef->setInvalidDecl();
365
John McCall04fcd0d2011-02-01 08:20:08 +0000366 // If the old typedef was the name for linkage purposes of an anonymous
367 // tag decl, re-establish that relationship for the new typedef.
368 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
369 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000370 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000371 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000372 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000373 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000374 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000375 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000376
Richard Smith41c79d92014-10-11 00:37:16 +0000377 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000378 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
379 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000380 if (!InstPrev)
Craig Topperc3ec1492014-05-26 06:22:03 +0000381 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000382
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000383 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
384
385 // If the typedef types are not identical, reject them.
386 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
387
Rafael Espindola8db352d2013-10-17 15:37:26 +0000388 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000389 }
390
John McCall6602bb12010-08-01 02:01:53 +0000391 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000392
John McCall401982f2010-01-20 21:53:11 +0000393 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000394
Douglas Gregord7e7a512009-03-17 21:15:40 +0000395 return Typedef;
396}
397
Richard Smithdda56e42011-04-15 14:24:37 +0000398Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000399 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
Richard Smith41c79d92014-10-11 00:37:16 +0000400 if (Typedef)
401 Owner->addDecl(Typedef);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000402 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000403}
404
405Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000406 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
Richard Smith41c79d92014-10-11 00:37:16 +0000407 if (Typedef)
408 Owner->addDecl(Typedef);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000409 return Typedef;
410}
411
412Decl *
413TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
414 // Create a local instantiation scope for this type alias template, which
415 // will contain the instantiations of the template parameters.
416 LocalInstantiationScope Scope(SemaRef);
417
418 TemplateParameterList *TempParams = D->getTemplateParameters();
419 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
420 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000421 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000422
423 TypeAliasDecl *Pattern = D->getTemplatedDecl();
424
Craig Topperc3ec1492014-05-26 06:22:03 +0000425 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
Richard Smith41c79d92014-10-11 00:37:16 +0000426 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000427 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000428 if (!Found.empty()) {
429 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000430 }
431 }
432
433 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
434 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
435 if (!AliasInst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000436 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000437
438 TypeAliasTemplateDecl *Inst
439 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
440 D->getDeclName(), InstParams, AliasInst);
Richard Smith43ccec8e2014-08-26 03:52:16 +0000441 AliasInst->setDescribedAliasTemplate(Inst);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000442 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000443 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000444
445 Inst->setAccess(D->getAccess());
446
447 if (!PrevAliasTemplate)
448 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000449
Richard Smith3f1b5d02011-05-05 21:57:07 +0000450 Owner->addDecl(Inst);
451
452 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000453}
454
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000455Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000456 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000457}
458
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000459Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
460 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000461
Douglas Gregor04163182010-05-21 00:31:19 +0000462 // If this is the variable for an anonymous struct or union,
463 // instantiate the anonymous struct/union type first.
464 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
465 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
466 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +0000467 return nullptr;
Douglas Gregor04163182010-05-21 00:31:19 +0000468
John McCall76d824f2009-08-25 22:02:44 +0000469 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000470 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000471 TemplateArgs,
472 D->getTypeSpecStartLoc(),
473 D->getDeclName());
474 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +0000475 return nullptr;
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000476
Douglas Gregor61623342010-09-12 07:37:24 +0000477 if (DI->getType()->isFunctionType()) {
478 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
479 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000480 return nullptr;
Douglas Gregor61623342010-09-12 07:37:24 +0000481 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000482
Richard Smith541b38b2013-09-20 01:15:31 +0000483 DeclContext *DC = Owner;
484 if (D->isLocalExternDecl())
485 SemaRef.adjustContextForLocalExternDecl(DC);
486
Larisse Voufo39a1e502013-08-06 01:03:05 +0000487 // Build the instantiated declaration.
Richard Smith541b38b2013-09-20 01:15:31 +0000488 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000489 D->getLocation(), D->getIdentifier(),
Larisse Voufo39a1e502013-08-06 01:03:05 +0000490 DI->getType(), DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000491
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000492 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000493 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000494 SemaRef.inferObjCARCLifetime(Var))
495 Var->setInvalidDecl();
496
Larisse Voufo39a1e502013-08-06 01:03:05 +0000497 // Substitute the nested name specifier, if any.
498 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +0000499 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000500
Richard Smith541b38b2013-09-20 01:15:31 +0000501 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000502 StartingScope, InstantiatingVarTemplate);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000503
504 if (D->isNRVOVariable()) {
505 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
506 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
507 Var->setNRVOVariable(true);
508 }
509
Alexander Kornienko83a4e182014-05-27 21:29:22 +0000510 Var->setImplicit(D->isImplicit());
511
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000512 return Var;
513}
514
Abramo Bagnarad7340582010-06-05 05:09:32 +0000515Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
516 AccessSpecDecl* AD
517 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
518 D->getAccessSpecifierLoc(), D->getColonLoc());
519 Owner->addHiddenDecl(AD);
520 return AD;
521}
522
Douglas Gregord7e7a512009-03-17 21:15:40 +0000523Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
524 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000525 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000526 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000527 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000528 DI = SemaRef.SubstType(DI, TemplateArgs,
529 D->getLocation(), D->getDeclName());
530 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000531 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000532 Invalid = true;
533 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000534 // C++ [temp.arg.type]p3:
535 // If a declaration acquires a function type through a type
536 // dependent on a template-parameter and this causes a
537 // declaration that does not use the syntactic form of a
538 // function declarator to have function type, the program is
539 // ill-formed.
540 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000541 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000542 Invalid = true;
543 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000544 } else {
545 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000546 }
547
548 Expr *BitWidth = D->getBitWidth();
549 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +0000550 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000551 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000552 // The bit-width expression is a constant expression.
553 EnterExpressionEvaluationContext Unevaluated(SemaRef,
554 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000555
John McCalldadc5752010-08-24 06:29:42 +0000556 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000557 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000558 if (InstantiatedBitWidth.isInvalid()) {
559 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +0000560 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000561 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000562 BitWidth = InstantiatedBitWidth.getAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000563 }
564
John McCall90459c52009-10-22 23:33:21 +0000565 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
566 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000567 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000568 D->getLocation(),
569 D->isMutable(),
570 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000571 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000572 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000573 D->getAccess(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000574 nullptr);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000575 if (!Field) {
576 cast<Decl>(Owner)->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +0000577 return nullptr;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000578 }
Mike Stump11289f42009-09-09 15:08:12 +0000579
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000580 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000581
Richard Smith848e1f12013-02-01 08:12:08 +0000582 if (Field->hasAttrs())
583 SemaRef.CheckAlignasUnderalignment(Field);
584
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000585 if (Invalid)
586 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000587
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000588 if (!Field->getDeclName()) {
589 // Keep track of where this decl came from.
590 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000591 }
Douglas Gregor04163182010-05-21 00:31:19 +0000592 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
593 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000594 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000595 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000596 }
Mike Stump11289f42009-09-09 15:08:12 +0000597
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000598 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000599 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000600 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000601
602 return Field;
603}
604
John McCall5e77d762013-04-16 07:28:30 +0000605Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
606 bool Invalid = false;
607 TypeSourceInfo *DI = D->getTypeSourceInfo();
608
609 if (DI->getType()->isVariablyModifiedType()) {
610 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +0000611 << D;
John McCall5e77d762013-04-16 07:28:30 +0000612 Invalid = true;
613 } else if (DI->getType()->isInstantiationDependentType()) {
614 DI = SemaRef.SubstType(DI, TemplateArgs,
615 D->getLocation(), D->getDeclName());
616 if (!DI) {
617 DI = D->getTypeSourceInfo();
618 Invalid = true;
619 } else if (DI->getType()->isFunctionType()) {
620 // C++ [temp.arg.type]p3:
621 // If a declaration acquires a function type through a type
622 // dependent on a template-parameter and this causes a
623 // declaration that does not use the syntactic form of a
624 // function declarator to have function type, the program is
625 // ill-formed.
626 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
627 << DI->getType();
628 Invalid = true;
629 }
630 } else {
631 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
632 }
633
Richard Smithf7981722013-11-22 09:01:48 +0000634 MSPropertyDecl *Property = MSPropertyDecl::Create(
635 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
636 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000637
638 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
639 StartingScope);
640
641 if (Invalid)
642 Property->setInvalidDecl();
643
644 Property->setAccess(D->getAccess());
645 Owner->addDecl(Property);
646
647 return Property;
648}
649
Francois Pichet783dd6e2010-11-21 06:08:52 +0000650Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
651 NamedDecl **NamedChain =
652 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
653
654 int i = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +0000655 for (auto *PI : D->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +0000656 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000657 TemplateArgs);
658 if (!Next)
Craig Topperc3ec1492014-05-26 06:22:03 +0000659 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000660
Douglas Gregor55e6b312011-03-04 19:46:35 +0000661 NamedChain[i++] = Next;
662 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000663
Francois Pichetdbafc192010-12-09 10:07:54 +0000664 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Aaron Ballman260995b2014-10-15 16:58:18 +0000665 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
666 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
667 NamedChain, D->getChainingSize());
Francois Pichet783dd6e2010-11-21 06:08:52 +0000668
NAKAMURA Takumi729be142014-10-27 12:37:26 +0000669 for (const auto *Attr : D->attrs())
670 IndirectField->addAttr(Attr->clone(SemaRef.Context));
Francois Pichet783dd6e2010-11-21 06:08:52 +0000671
672 IndirectField->setImplicit(D->isImplicit());
673 IndirectField->setAccess(D->getAccess());
674 Owner->addDecl(IndirectField);
675 return IndirectField;
676}
677
John McCallaa74a0c2009-08-28 07:59:38 +0000678Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000679 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000680 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000681 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000682 TypeSourceInfo *InstTy;
683 // If this is an unsupported friend, don't bother substituting template
684 // arguments into it. The actual type referred to won't be used by any
685 // parts of Clang, and may not be valid for instantiating. Just use the
686 // same info for the instantiated friend.
687 if (D->isUnsupportedFriend()) {
688 InstTy = Ty;
689 } else {
690 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
691 D->getLocation(), DeclarationName());
692 }
693 if (!InstTy)
Craig Topperc3ec1492014-05-26 06:22:03 +0000694 return nullptr;
John McCallaa74a0c2009-08-28 07:59:38 +0000695
Richard Smitha31a89a2012-09-20 01:31:00 +0000696 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000697 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000698 if (!FD)
Craig Topperc3ec1492014-05-26 06:22:03 +0000699 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000700
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000701 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000702 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000703 Owner->addDecl(FD);
704 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000705 }
706
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000707 NamedDecl *ND = D->getFriendDecl();
708 assert(ND && "friend decl must be a decl or a type!");
709
John McCallb9c78482010-04-08 09:05:18 +0000710 // All of the Visit implementations for the various potential friend
711 // declarations have to be carefully written to work for friend
712 // objects, with the most important detail being that the target
713 // decl should almost certainly not be placed in Owner.
714 Decl *NewND = Visit(ND);
Craig Topperc3ec1492014-05-26 06:22:03 +0000715 if (!NewND) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000716
John McCallaa74a0c2009-08-28 07:59:38 +0000717 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000718 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000719 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000720 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000721 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000722 Owner->addDecl(FD);
723 return FD;
John McCall58de3582009-08-14 02:03:10 +0000724}
725
Douglas Gregord7e7a512009-03-17 21:15:40 +0000726Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
727 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000728
Richard Smith764d2fe2011-12-20 02:08:33 +0000729 // The expression in a static assertion is a constant expression.
730 EnterExpressionEvaluationContext Unevaluated(SemaRef,
731 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000732
John McCalldadc5752010-08-24 06:29:42 +0000733 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000734 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000735 if (InstantiatedAssertExpr.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +0000736 return nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000737
Richard Smithded9c2e2012-07-11 22:37:56 +0000738 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000739 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000740 D->getMessage(),
741 D->getRParenLoc(),
742 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000743}
744
745Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000746 EnumDecl *PrevDecl = nullptr;
Richard Smith41c79d92014-10-11 00:37:16 +0000747 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
Richard Smith2e6610a2012-03-26 04:58:10 +0000748 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Richard Smith41c79d92014-10-11 00:37:16 +0000749 PatternPrev,
Richard Smith2e6610a2012-03-26 04:58:10 +0000750 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +0000751 if (!Prev) return nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +0000752 PrevDecl = cast<EnumDecl>(Prev);
753 }
754
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000755 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000756 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000757 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000758 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000759 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000760 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000761 // If we have type source information for the underlying type, it means it
762 // has been explicitly set by the user. Perform substitution on it before
763 // moving on.
764 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000765 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
766 DeclarationName());
767 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000768 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000769 else
770 Enum->setIntegerTypeSourceInfo(NewTI);
771 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000772 assert(!D->getIntegerType()->isDependentType()
773 && "Dependent type without type source info");
774 Enum->setIntegerType(D->getIntegerType());
775 }
776 }
777
John McCall811a0f52010-10-22 23:36:17 +0000778 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
779
Richard Smith4b38ded2012-03-14 23:13:10 +0000780 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000781 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +0000782 // Forward the mangling number from the template to the instantiated decl.
783 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
Craig Topperc3ec1492014-05-26 06:22:03 +0000784 if (SubstQualifier(D, Enum)) return nullptr;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000785 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +0000786
Richard Smith258a7442012-03-26 04:08:46 +0000787 EnumDecl *Def = D->getDefinition();
788 if (Def && Def != D) {
789 // If this is an out-of-line definition of an enum member template, check
790 // that the underlying types match in the instantiation of both
791 // declarations.
792 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
793 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
794 QualType DefnUnderlying =
795 SemaRef.SubstType(TI->getType(), TemplateArgs,
796 UnderlyingLoc, DeclarationName());
797 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
798 DefnUnderlying, Enum);
799 }
800 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000801
Richard Smith4b38ded2012-03-14 23:13:10 +0000802 // C++11 [temp.inst]p1: The implicit instantiation of a class template
803 // specialization causes the implicit instantiation of the declarations, but
804 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +0000805 //
806 // DR1484 clarifies that enumeration definitions inside of a template
807 // declaration aren't considered entities that can be separately instantiated
808 // from the rest of the entity they are declared inside of.
809 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
810 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +0000811 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +0000812 }
Richard Smith4b38ded2012-03-14 23:13:10 +0000813
814 return Enum;
815}
816
817void TemplateDeclInstantiator::InstantiateEnumDefinition(
818 EnumDecl *Enum, EnumDecl *Pattern) {
819 Enum->startDefinition();
820
Richard Smith7d137e32012-03-23 03:33:32 +0000821 // Update the location to refer to the definition.
822 Enum->setLocation(Pattern->getLocation());
823
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000824 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000825
Craig Topperc3ec1492014-05-26 06:22:03 +0000826 EnumConstantDecl *LastEnumConst = nullptr;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000827 for (auto *EC : Pattern->enumerators()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000828 // The specified value for the enumerator.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000829 ExprResult Value((Expr *)nullptr);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000830 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000831 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +0000832 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +0000833 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000834
John McCall76d824f2009-08-25 22:02:44 +0000835 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000836 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000837
838 // Drop the initial value and continue.
839 bool isInvalid = false;
840 if (Value.isInvalid()) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000841 Value = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000842 isInvalid = true;
843 }
844
Mike Stump11289f42009-09-09 15:08:12 +0000845 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +0000846 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
847 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +0000848 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000849
850 if (isInvalid) {
851 if (EnumConst)
852 EnumConst->setInvalidDecl();
853 Enum->setInvalidDecl();
854 }
855
856 if (EnumConst) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000857 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +0000858
John McCallf9b528c2010-01-23 22:37:59 +0000859 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000860 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +0000861 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000862 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000863
Richard Smith4b38ded2012-03-14 23:13:10 +0000864 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
865 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000866 // If the enumeration is within a function or method, record the enum
867 // constant as a local.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000868 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000869 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000870 }
871 }
Mike Stump11289f42009-09-09 15:08:12 +0000872
Richard Smith4b38ded2012-03-14 23:13:10 +0000873 // FIXME: Fixup LBraceLoc
874 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
875 Enum->getRBraceLoc(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +0000876 Enumerators,
Craig Topperc3ec1492014-05-26 06:22:03 +0000877 nullptr, nullptr);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000878}
879
Douglas Gregor9106b822009-03-25 15:04:13 +0000880Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000881 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +0000882}
883
John McCall87a44eb2009-08-20 01:44:21 +0000884Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000885 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
886
Douglas Gregor954de172009-10-31 17:21:17 +0000887 // Create a local instantiation scope for this class template, which
888 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +0000889 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +0000890 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000891 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000892 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000893 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +0000894
895 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +0000896
897 // Instantiate the qualifier. We have to do this first in case
898 // we're a friend declaration, because if we are then we need to put
899 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +0000900 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
901 if (QualifierLoc) {
902 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
903 TemplateArgs);
904 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +0000905 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000906 }
907
Craig Topperc3ec1492014-05-26 06:22:03 +0000908 CXXRecordDecl *PrevDecl = nullptr;
909 ClassTemplateDecl *PrevClassTemplate = nullptr;
John McCall598b4402010-03-25 06:39:04 +0000910
Richard Smith41c79d92014-10-11 00:37:16 +0000911 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
Nick Lewycky61478912010-11-08 23:29:42 +0000912 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000913 if (!Found.empty()) {
914 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +0000915 if (PrevClassTemplate)
916 PrevDecl = PrevClassTemplate->getTemplatedDecl();
917 }
918 }
919
John McCall598b4402010-03-25 06:39:04 +0000920 // If this isn't a friend, then it's a member template, in which
921 // case we just want to build the instantiation in the
922 // specialization. If it is a friend, we want to build it in
923 // the appropriate context.
924 DeclContext *DC = Owner;
925 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +0000926 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000927 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +0000928 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +0000929 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +0000930 if (!DC) return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000931 } else {
932 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
933 Pattern->getDeclContext(),
934 TemplateArgs);
935 }
936
937 // Look for a previous declaration of the template in the owning
938 // context.
939 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
940 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
941 SemaRef.LookupQualifiedName(R, DC);
942
943 if (R.isSingleResult()) {
944 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
945 if (PrevClassTemplate)
946 PrevDecl = PrevClassTemplate->getTemplatedDecl();
947 }
948
Douglas Gregor14454802011-02-25 02:25:35 +0000949 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000950 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +0000951 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +0000952 << QualifierLoc.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000953 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000954 }
955
Douglas Gregor01e09d92010-04-08 18:16:15 +0000956 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +0000957 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +0000958 bool Complain = true;
959
960 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
961 // template for struct std::tr1::__detail::_Map_base, where the
962 // template parameters of the friend declaration don't match the
963 // template parameters of the original declaration. In this one
964 // case, we don't complain about the ill-formed friend
965 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000966 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +0000967 Pattern->getIdentifier()->isStr("_Map_base") &&
968 DC->isNamespace() &&
969 cast<NamespaceDecl>(DC)->getIdentifier() &&
970 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
971 DeclContext *DCParent = DC->getParent();
972 if (DCParent->isNamespace() &&
973 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
974 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
Richard Trieuc771d5d2014-05-28 02:16:01 +0000975 if (cast<Decl>(DCParent)->isInStdNamespace())
Douglas Gregor01e09d92010-04-08 18:16:15 +0000976 Complain = false;
977 }
978 }
979
John McCall598b4402010-03-25 06:39:04 +0000980 TemplateParameterList *PrevParams
981 = PrevClassTemplate->getTemplateParameters();
982
983 // Make sure the parameter lists match.
984 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000985 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +0000986 Sema::TPL_TemplateMatch)) {
987 if (Complain)
Craig Topperc3ec1492014-05-26 06:22:03 +0000988 return nullptr;
Douglas Gregor01e09d92010-04-08 18:16:15 +0000989
990 AdoptedPreviousTemplateParams = true;
991 InstParams = PrevParams;
992 }
John McCall598b4402010-03-25 06:39:04 +0000993
994 // Do some additional validation, then merge default arguments
995 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +0000996 if (!AdoptedPreviousTemplateParams &&
997 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +0000998 Sema::TPC_ClassTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +0000999 return nullptr;
John McCall598b4402010-03-25 06:39:04 +00001000 }
1001 }
1002
John McCall87a44eb2009-08-20 01:44:21 +00001003 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +00001004 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001005 Pattern->getLocStart(), Pattern->getLocation(),
1006 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +00001007 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +00001008
Douglas Gregor14454802011-02-25 02:25:35 +00001009 if (QualifierLoc)
1010 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001011
John McCall87a44eb2009-08-20 01:44:21 +00001012 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +00001013 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1014 D->getIdentifier(), InstParams, RecordInst,
1015 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +00001016 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +00001017
John McCall598b4402010-03-25 06:39:04 +00001018 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +00001019 if (PrevClassTemplate)
1020 Inst->setAccess(PrevClassTemplate->getAccess());
1021 else
1022 Inst->setAccess(D->getAccess());
1023
Richard Smith64017682013-07-17 23:53:16 +00001024 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +00001025 // TODO: do we want to track the instantiation progeny of this
1026 // friend target decl?
1027 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +00001028 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +00001029 if (!PrevClassTemplate)
1030 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +00001031 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001032
Douglas Gregoref06ccf2009-10-12 23:11:44 +00001033 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +00001034 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +00001035 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +00001036
Douglas Gregorbb3b46e2009-10-30 22:42:42 +00001037 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +00001038 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +00001039 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +00001040 Inst->setLexicalDeclContext(Owner);
1041 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +00001042 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +00001043 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001044
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +00001045 if (D->isOutOfLine()) {
1046 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1047 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1048 }
1049
John McCall87a44eb2009-08-20 01:44:21 +00001050 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +00001051
1052 if (!PrevClassTemplate) {
1053 // Queue up any out-of-line partial specializations of this member
1054 // class template; the client will force their instantiation once
1055 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001056 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +00001057 D->getPartialSpecializations(PartialSpecs);
1058 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001059 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +00001060 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1061 }
1062
John McCall87a44eb2009-08-20 01:44:21 +00001063 return Inst;
1064}
1065
Douglas Gregore704c9d2009-08-27 16:57:43 +00001066Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +00001067TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1068 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +00001069 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001070
Douglas Gregor21610382009-10-29 00:04:11 +00001071 // Lookup the already-instantiated declaration in the instantiation
1072 // of the class template and return that.
1073 DeclContext::lookup_result Found
1074 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001075 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00001076 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001077
Douglas Gregor21610382009-10-29 00:04:11 +00001078 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +00001079 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +00001080 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00001081 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001082
Douglas Gregor869853e2010-11-10 19:44:59 +00001083 if (ClassTemplatePartialSpecializationDecl *Result
1084 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1085 return Result;
1086
1087 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001088}
1089
Larisse Voufo39a1e502013-08-06 01:03:05 +00001090Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1091 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1092 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001093
1094 // Create a local instantiation scope for this variable template, which
1095 // will contain the instantiations of the template parameters.
1096 LocalInstantiationScope Scope(SemaRef);
1097 TemplateParameterList *TempParams = D->getTemplateParameters();
1098 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1099 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001100 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001101
1102 VarDecl *Pattern = D->getTemplatedDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001103 VarTemplateDecl *PrevVarTemplate = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001104
Richard Smith41c79d92014-10-11 00:37:16 +00001105 if (getPreviousDeclForInstantiation(Pattern)) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00001106 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1107 if (!Found.empty())
1108 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1109 }
1110
Richard Smith1c34fb72013-08-13 18:18:50 +00001111 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001112 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1113 /*InstantiatingVarTemplate=*/true));
Larisse Voufo39a1e502013-08-06 01:03:05 +00001114
1115 DeclContext *DC = Owner;
1116
Larisse Voufo39a1e502013-08-06 01:03:05 +00001117 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1118 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001119 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001120 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001121 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001122
1123 Inst->setAccess(D->getAccess());
1124 if (!PrevVarTemplate)
1125 Inst->setInstantiatedFromMemberTemplate(D);
1126
1127 if (D->isOutOfLine()) {
1128 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1129 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1130 }
1131
1132 Owner->addDecl(Inst);
1133
1134 if (!PrevVarTemplate) {
1135 // Queue up any out-of-line partial specializations of this member
1136 // variable template; the client will force their instantiation once
1137 // the enclosing class has been instantiated.
1138 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1139 D->getPartialSpecializations(PartialSpecs);
1140 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001141 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001142 OutOfLineVarPartialSpecs.push_back(
1143 std::make_pair(Inst, PartialSpecs[I]));
1144 }
1145
1146 return Inst;
1147}
1148
1149Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1150 VarTemplatePartialSpecializationDecl *D) {
1151 assert(D->isStaticDataMember() &&
1152 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001153
1154 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1155
1156 // Lookup the already-instantiated declaration and return that.
1157 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1158 assert(!Found.empty() && "Instantiation found nothing?");
1159
1160 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1161 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1162
1163 if (VarTemplatePartialSpecializationDecl *Result =
1164 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1165 return Result;
1166
1167 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1168}
1169
Douglas Gregore4b05162009-10-07 17:21:34 +00001170Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001171TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001172 // Create a local instantiation scope for this function template, which
1173 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001174 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001175 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001176 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001177
Douglas Gregore704c9d2009-08-27 16:57:43 +00001178 TemplateParameterList *TempParams = D->getTemplateParameters();
1179 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001180 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001181 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001182
Craig Topperc3ec1492014-05-26 06:22:03 +00001183 FunctionDecl *Instantiated = nullptr;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001184 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001185 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001186 InstParams));
1187 else
1188 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001189 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001190 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001191
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001192 if (!Instantiated)
Craig Topperc3ec1492014-05-26 06:22:03 +00001193 return nullptr;
Douglas Gregore704c9d2009-08-27 16:57:43 +00001194
Mike Stump11289f42009-09-09 15:08:12 +00001195 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001196 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001197 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001198 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001199 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001200 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001201 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001202
John McCall30837102010-03-26 23:10:15 +00001203 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1204
John McCall2079d0b2009-12-14 23:19:40 +00001205 // Link the instantiation back to the pattern *unless* this is a
1206 // non-definition friend declaration.
1207 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001208 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001209 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001210
John McCall30837102010-03-26 23:10:15 +00001211 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001212 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001213 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001214 } else if (InstTemplate->getDeclContext()->isRecord() &&
Richard Smith41c79d92014-10-11 00:37:16 +00001215 !getPreviousDeclForInstantiation(D)) {
John McCalla0a96892012-08-10 03:15:35 +00001216 SemaRef.CheckFriendAccess(InstTemplate);
1217 }
John McCall30837102010-03-26 23:10:15 +00001218
Douglas Gregore704c9d2009-08-27 16:57:43 +00001219 return InstTemplate;
1220}
1221
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001222Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001223 CXXRecordDecl *PrevDecl = nullptr;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001224 if (D->isInjectedClassName())
1225 PrevDecl = cast<CXXRecordDecl>(Owner);
Richard Smith41c79d92014-10-11 00:37:16 +00001226 else if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001227 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Richard Smith41c79d92014-10-11 00:37:16 +00001228 PatternPrev,
John McCalle9f92a02009-12-15 22:29:06 +00001229 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001230 if (!Prev) return nullptr;
John McCalle9f92a02009-12-15 22:29:06 +00001231 PrevDecl = cast<CXXRecordDecl>(Prev);
1232 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001233
1234 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001235 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001236 D->getLocStart(), D->getLocation(),
1237 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001238
1239 // Substitute the nested name specifier, if any.
1240 if (SubstQualifier(D, Record))
Craig Topperc3ec1492014-05-26 06:22:03 +00001241 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00001242
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001243 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001244 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1245 // the tag decls introduced by friend class declarations don't have an access
1246 // specifier. Remove once this area of the code gets sorted out.
1247 if (D->getAccess() != AS_none)
1248 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001249 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001250 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001251
John McCallaa74a0c2009-08-28 07:59:38 +00001252 // If the original function was part of a friend declaration,
1253 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001254 if (D->getFriendObjectKind())
1255 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001256
Douglas Gregor04163182010-05-21 00:31:19 +00001257 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001258 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001259 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001260
1261 if (D->isLocalClass())
1262 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001263
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001264 // Forward the mangling number from the template to the instantiated decl.
1265 SemaRef.Context.setManglingNumber(Record,
1266 SemaRef.Context.getManglingNumber(D));
1267
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001268 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001269
1270 // DR1484 clarifies that the members of a local class are instantiated as part
1271 // of the instantiation of their enclosing entity.
1272 if (D->isCompleteDefinition() && D->isLocalClass()) {
David Majnemera64cb5a2014-02-22 00:17:46 +00001273 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1274 TSK_ImplicitInstantiation,
1275 /*Complain=*/true);
1276 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1277 TSK_ImplicitInstantiation);
David Majnemer192d1792013-11-27 08:20:38 +00001278 }
Nico Weber72889432014-09-06 01:25:55 +00001279
1280 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1281
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001282 return Record;
1283}
1284
Douglas Gregor89f593a2012-09-13 21:56:43 +00001285/// \brief Adjust the given function type for an instantiation of the
1286/// given declaration, to cope with modifications to the function's type that
1287/// aren't reflected in the type-source information.
1288///
1289/// \param D The declaration we're instantiating.
1290/// \param TInfo The already-instantiated type.
1291static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1292 FunctionDecl *D,
1293 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001294 const FunctionProtoType *OrigFunc
1295 = D->getType()->castAs<FunctionProtoType>();
1296 const FunctionProtoType *NewFunc
1297 = TInfo->getType()->castAs<FunctionProtoType>();
1298 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1299 return TInfo->getType();
1300
1301 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1302 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001303 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001304 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001305}
1306
John McCallaa74a0c2009-08-28 07:59:38 +00001307/// Normal class members are of more specific types and therefore
1308/// don't make it here. This function serves two purposes:
1309/// 1) instantiating function templates
1310/// 2) substituting friend declarations
Douglas Gregor33636e62009-12-24 20:56:24 +00001311Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001312 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001313 // Check whether there is already a function template specialization for
1314 // this declaration.
1315 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001316 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001317 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001318
Craig Topperc3ec1492014-05-26 06:22:03 +00001319 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001320 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00001321 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001322
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001323 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001324 if (SpecFunc)
1325 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001326 }
Mike Stump11289f42009-09-09 15:08:12 +00001327
John McCall2f88d7d2010-03-27 05:57:59 +00001328 bool isFriend;
1329 if (FunctionTemplate)
1330 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1331 else
1332 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1333
Craig Topperc3ec1492014-05-26 06:22:03 +00001334 bool MergeWithParentScope = (TemplateParams != nullptr) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001335 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001336 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001337 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001338 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001339
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001340 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001341 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001342 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001343 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001344 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001345
Douglas Gregor14454802011-02-25 02:25:35 +00001346 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1347 if (QualifierLoc) {
1348 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1349 TemplateArgs);
1350 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001351 return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001352 }
1353
John McCallce410662010-02-06 01:50:47 +00001354 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001355 // in the enclosing namespace; otherwise we need to find the instantiated
1356 // context.
John McCallce410662010-02-06 01:50:47 +00001357 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001358 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001359 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001360 SemaRef.adjustContextForLocalExternDecl(DC);
1361 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001362 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001363 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001364 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001365 if (!DC) return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001366 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001367 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001368 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001369 }
John McCallce410662010-02-06 01:50:47 +00001370
John McCallaa74a0c2009-08-28 07:59:38 +00001371 FunctionDecl *Function =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001372 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara0d4fce12012-10-04 21:40:42 +00001373 D->getNameInfo(), T, TInfo,
Rafael Espindola9dd86de2013-04-16 02:29:15 +00001374 D->getCanonicalDecl()->getStorageClass(),
Reid Kleckner0f764e52015-04-07 20:46:51 +00001375 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001376 D->isConstexpr());
Enea Zaffanella25723ce2013-07-19 18:02:36 +00001377 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCall3e11ebe2010-03-15 10:12:16 +00001378
Richard Smithf3814ad2013-01-25 00:08:28 +00001379 if (D->isInlined())
1380 Function->setImplicitlyInline();
1381
Douglas Gregor14454802011-02-25 02:25:35 +00001382 if (QualifierLoc)
1383 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001384
Richard Smith541b38b2013-09-20 01:15:31 +00001385 if (D->isLocalExternDecl())
1386 Function->setLocalExternDecl();
1387
John McCall30837102010-03-26 23:10:15 +00001388 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001389 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001390 assert(D->getDeclContext()->isFileContext());
1391 LexicalDC = D->getDeclContext();
1392 }
1393
1394 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001395
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001396 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001397 for (unsigned P = 0; P < Params.size(); ++P)
1398 if (Params[P])
1399 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001400 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001401
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001402 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001403 if (TemplateParams) {
1404 // Our resulting instantiation is actually a function template, since we
1405 // are substituting only the outer template parameters. For example, given
1406 //
1407 // template<typename T>
1408 // struct X {
1409 // template<typename U> friend void f(T, U);
1410 // };
1411 //
1412 // X<int> x;
1413 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001414 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001415 // which means substituting int for T, but leaving "f" as a friend function
1416 // template.
1417 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001418 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001419 Function->getLocation(),
1420 Function->getDeclName(),
1421 TemplateParams, Function);
1422 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001423
1424 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001425
1426 if (isFriend && D->isThisDeclarationADefinition()) {
1427 // TODO: should we remember this connection regardless of whether
1428 // the friend declaration provided a body?
1429 FunctionTemplate->setInstantiatedFromMemberTemplate(
1430 D->getDescribedFunctionTemplate());
1431 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001432 } else if (FunctionTemplate) {
1433 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001434 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001435 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001436 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001437 Innermost.begin(),
1438 Innermost.size()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001439 /*InsertPos=*/nullptr);
Chandler Carruth48b28312011-08-18 09:09:59 +00001440 } else if (isFriend) {
1441 // Note, we need this connection even if the friend doesn't have a body.
1442 // Its body may exist but not have been attached yet due to deferred
1443 // parsing.
1444 // FIXME: It might be cleaner to set this when attaching the body to the
1445 // friend function declaration, however that would require finding all the
1446 // instantiations and modifying them.
John McCalle0b2ddb2010-03-26 04:53:08 +00001447 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001448 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001449
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001450 if (InitFunctionInstantiation(Function, D))
1451 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001452
John McCallb9c78482010-04-08 09:05:18 +00001453 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001454
Richard Smith541b38b2013-09-20 01:15:31 +00001455 LookupResult Previous(
1456 SemaRef, Function->getDeclName(), SourceLocation(),
1457 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1458 : Sema::LookupOrdinaryName,
1459 Sema::ForRedeclaration);
John McCall1f82f242009-11-18 22:49:29 +00001460
John McCallb9c78482010-04-08 09:05:18 +00001461 if (DependentFunctionTemplateSpecializationInfo *Info
1462 = D->getDependentSpecializationInfo()) {
1463 assert(isFriend && "non-friend has dependent specialization info?");
1464
1465 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001466 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001467
1468 // Instantiate the explicit template arguments.
1469 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1470 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001471 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1472 ExplicitArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00001473 return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001474
1475 // Map the candidate templates to their instantiations.
1476 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1477 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1478 Info->getTemplate(I),
1479 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001480 if (!Temp) return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001481
1482 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1483 }
1484
1485 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1486 &ExplicitArgs,
1487 Previous))
1488 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001489
John McCallb9c78482010-04-08 09:05:18 +00001490 isExplicitSpecialization = true;
1491
1492 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001493 // Look only into the namespace where the friend would be declared to
1494 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001495 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001496 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001497
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001498 // In C++, the previous declaration we find might be a tag type
1499 // (class or enum). In this case, the new declaration will hide the
1500 // tag type. Note that this does does not apply if we're declaring a
1501 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001502 if (Previous.isSingleTagDecl())
1503 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001504 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001505
Craig Topperc3ec1492014-05-26 06:22:03 +00001506 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001507 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001508
John McCallb9467b62010-04-24 01:30:58 +00001509 NamedDecl *PrincipalDecl = (TemplateParams
1510 ? cast<NamedDecl>(FunctionTemplate)
1511 : Function);
1512
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001513 // If the original function was part of a friend declaration,
1514 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001515 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001516 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001517 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001518
Richard Smith91dfaac2014-02-03 02:37:59 +00001519 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001520
Richard Smith91dfaac2014-02-03 02:37:59 +00001521 // C++11 [temp.friend]p4 (DR329):
1522 // When a function is defined in a friend function declaration in a class
1523 // template, the function is instantiated when the function is odr-used.
1524 // The same restrictions on multiple declarations and definitions that
1525 // apply to non-template function declarations and definitions also apply
1526 // to these implicit definitions.
1527 if (D->isThisDeclarationADefinition()) {
Douglas Gregorb92ea592010-05-18 05:45:02 +00001528 // Check for a function body.
Craig Topperc3ec1492014-05-26 06:22:03 +00001529 const FunctionDecl *Definition = nullptr;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001530 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001531 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001532 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1533 << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001534 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001535 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001536 // Check for redefinitions due to other instantiations of this or
1537 // a similar friend function.
Aaron Ballman86c93902014-03-06 23:45:36 +00001538 else for (auto R : Function->redecls()) {
1539 if (R == Function)
Gabor Greif122f1eb2010-08-28 15:42:30 +00001540 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00001541
1542 // If some prior declaration of this function has been used, we need
1543 // to instantiate its definition.
1544 if (!QueuedInstantiation && R->isUsed(false)) {
1545 if (MemberSpecializationInfo *MSInfo =
1546 Function->getMemberSpecializationInfo()) {
1547 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1548 SourceLocation Loc = R->getLocation(); // FIXME
1549 MSInfo->setPointOfInstantiation(Loc);
1550 SemaRef.PendingLocalImplicitInstantiations.push_back(
1551 std::make_pair(Function, Loc));
1552 QueuedInstantiation = true;
Gabor Greif718d5152010-08-30 21:10:05 +00001553 }
1554 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001555 }
1556
1557 // If some prior declaration of this function was a friend with an
1558 // uninstantiated definition, reject it.
1559 if (R->getFriendObjectKind()) {
1560 if (const FunctionDecl *RPattern =
1561 R->getTemplateInstantiationPattern()) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001562 if (RPattern->isDefined(RPattern)) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001563 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001564 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001565 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregorb92ea592010-05-18 05:45:02 +00001566 break;
1567 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001568 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001569 }
1570 }
1571 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001572 }
1573
Richard Smith541b38b2013-09-20 01:15:31 +00001574 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1575 DC->makeDeclVisibleInContext(PrincipalDecl);
1576
John McCallb9467b62010-04-24 01:30:58 +00001577 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1578 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1579 PrincipalDecl->setNonMemberOperator();
1580
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001581 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001582 return Function;
1583}
1584
Douglas Gregore704c9d2009-08-27 16:57:43 +00001585Decl *
1586TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001587 TemplateParameterList *TemplateParams,
1588 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001589 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001590 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001591 // We are creating a function template specialization from a function
1592 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001593 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001594 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001595
Craig Topperc3ec1492014-05-26 06:22:03 +00001596 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001597 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00001598 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001599
Douglas Gregor97628d62009-08-21 00:16:32 +00001600 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001601 if (SpecFunc)
1602 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001603 }
1604
John McCall2f88d7d2010-03-27 05:57:59 +00001605 bool isFriend;
1606 if (FunctionTemplate)
1607 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1608 else
1609 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1610
Craig Topperc3ec1492014-05-26 06:22:03 +00001611 bool MergeWithParentScope = (TemplateParams != nullptr) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001612 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001613 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001614 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001615
John McCalld0e23ec2010-10-19 02:26:41 +00001616 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001617 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001618 unsigned NumTempParamLists = 0;
1619 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1620 TempParamLists.set_size(NumTempParamLists);
1621 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1622 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1623 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1624 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001625 return nullptr;
John McCalld0e23ec2010-10-19 02:26:41 +00001626 TempParamLists[I] = InstParams;
1627 }
1628 }
1629
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001630 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001631 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001632 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001633 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001634 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001635
Douglas Gregor14454802011-02-25 02:25:35 +00001636 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1637 if (QualifierLoc) {
1638 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001639 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001640 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001641 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001642 }
1643
1644 DeclContext *DC = Owner;
1645 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001646 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001647 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001648 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001649 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001650
1651 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00001652 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001653 } else {
1654 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1655 D->getDeclContext(),
1656 TemplateArgs);
1657 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001658 if (!DC) return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001659 }
1660
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001661 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001662 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Craig Topperc3ec1492014-05-26 06:22:03 +00001663 CXXMethodDecl *Method = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001664
Abramo Bagnaradff19302011-03-08 08:55:46 +00001665 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001666 DeclarationNameInfo NameInfo
1667 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001668 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001669 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001670 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001671 Constructor->isExplicit(),
Reid Kleckner0f764e52015-04-07 20:46:51 +00001672 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001673 false, Constructor->isConstexpr());
Richard Smith4c163a02013-05-17 02:19:35 +00001674
Richard Smith185be182013-04-10 05:48:59 +00001675 // Claim that the instantiation of a constructor or constructor template
1676 // inherits the same constructor that the template does.
Richard Smith4c163a02013-05-17 02:19:35 +00001677 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1678 Constructor->getInheritedConstructor())) {
1679 // If we're instantiating a specialization of a function template, our
1680 // "inherited constructor" will actually itself be a function template.
1681 // Instantiate a declaration of it, too.
1682 if (FunctionTemplate) {
1683 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1684 !Inh->getParent()->isDependentContext() &&
1685 "inheriting constructor template in dependent context?");
1686 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1687 Inh);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001688 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00001689 return nullptr;
Richard Smith4c163a02013-05-17 02:19:35 +00001690 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1691 LocalInstantiationScope LocalScope(SemaRef);
1692
1693 // Use the same template arguments that we deduced for the inheriting
1694 // constructor. There's no way they could be deduced differently.
1695 MultiLevelTemplateArgumentList InheritedArgs;
1696 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1697 Inh = cast_or_null<CXXConstructorDecl>(
1698 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1699 if (!Inh)
Craig Topperc3ec1492014-05-26 06:22:03 +00001700 return nullptr;
Richard Smith4c163a02013-05-17 02:19:35 +00001701 }
Richard Smith185be182013-04-10 05:48:59 +00001702 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smith4c163a02013-05-17 02:19:35 +00001703 }
Douglas Gregore8394862009-08-21 22:43:28 +00001704 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001705 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001706 StartLoc, NameInfo, T, TInfo,
Reid Kleckner0f764e52015-04-07 20:46:51 +00001707 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001708 false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001709 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001710 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001711 StartLoc, NameInfo, T, TInfo,
Reid Kleckner0f764e52015-04-07 20:46:51 +00001712 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001713 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001714 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001715 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001716 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001717 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001718 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001719 StartLoc, NameInfo, T, TInfo,
Reid Kleckner0f764e52015-04-07 20:46:51 +00001720 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001721 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001722 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001723
Richard Smithf3814ad2013-01-25 00:08:28 +00001724 if (D->isInlined())
1725 Method->setImplicitlyInline();
1726
Douglas Gregor14454802011-02-25 02:25:35 +00001727 if (QualifierLoc)
1728 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001729
Douglas Gregore704c9d2009-08-27 16:57:43 +00001730 if (TemplateParams) {
1731 // Our resulting instantiation is actually a function template, since we
1732 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001733 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001734 // template<typename T>
1735 // struct X {
1736 // template<typename U> void f(T, U);
1737 // };
1738 //
1739 // X<int> x;
1740 //
1741 // We are instantiating the member template "f" within X<int>, which means
1742 // substituting int for T, but leaving "f" as a member function template.
1743 // Build the function template itself.
1744 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1745 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001746 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001747 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001748 if (isFriend) {
1749 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001750 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001751 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001752 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001753 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001754 } else if (FunctionTemplate) {
1755 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001756 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001757 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001758 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001759 Innermost.begin(),
1760 Innermost.size()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001761 /*InsertPos=*/nullptr);
John McCall2f88d7d2010-03-27 05:57:59 +00001762 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001763 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001764 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001765 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001766
Mike Stump11289f42009-09-09 15:08:12 +00001767 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001768 // out-of-line, the instantiation will have the same lexical
1769 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001770 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00001771 if (NumTempParamLists)
1772 Method->setTemplateParameterListsInfo(SemaRef.Context,
1773 NumTempParamLists,
1774 TempParamLists.data());
1775
John McCall2f88d7d2010-03-27 05:57:59 +00001776 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001777 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001778 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001779 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001780
Douglas Gregor21342092009-03-24 00:38:23 +00001781 // Attach the parameters
1782 for (unsigned P = 0; P < Params.size(); ++P)
1783 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00001784 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00001785
1786 if (InitMethodInstantiation(Method, D))
1787 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001788
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001789 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1790 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001791
John McCall2f88d7d2010-03-27 05:57:59 +00001792 if (!FunctionTemplate || TemplateParams || isFriend) {
1793 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001794
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001795 // In C++, the previous declaration we find might be a tag type
1796 // (class or enum). In this case, the new declaration will hide the
1797 // tag type. Note that this does does not apply if we're declaring a
1798 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001799 if (Previous.isSingleTagDecl())
1800 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001801 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001802
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001803 if (!IsClassScopeSpecialization)
Craig Topperc3ec1492014-05-26 06:22:03 +00001804 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001805
Douglas Gregor21920e372009-12-01 17:24:26 +00001806 if (D->isPure())
1807 SemaRef.CheckPureMethod(Method, SourceRange());
1808
John McCalla0a96892012-08-10 03:15:35 +00001809 // Propagate access. For a non-friend declaration, the access is
1810 // whatever we're propagating from. For a friend, it should be the
1811 // previous declaration we just found.
1812 if (isFriend && Method->getPreviousDecl())
1813 Method->setAccess(Method->getPreviousDecl()->getAccess());
1814 else
1815 Method->setAccess(D->getAccess());
1816 if (FunctionTemplate)
1817 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00001818
Anders Carlsson7c812f52011-01-20 06:52:44 +00001819 SemaRef.CheckOverrideControl(Method);
1820
Eli Friedman41340732011-11-15 22:39:08 +00001821 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00001822 if (D->isExplicitlyDefaulted())
1823 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001824 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00001825 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001826
John McCalla0a96892012-08-10 03:15:35 +00001827 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00001828 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00001829 // do nothing
1830
1831 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00001832 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00001833 // do nothing
1834
1835 // Otherwise, check access to friends and make them visible.
1836 } else if (isFriend) {
1837 // We only need to re-check access for methods which we didn't
1838 // manage to match during parsing.
1839 if (!D->getPreviousDecl())
1840 SemaRef.CheckFriendAccess(Method);
1841
1842 Record->makeDeclVisibleInContext(Method);
1843
1844 // Otherwise, add the declaration. We don't need to do this for
1845 // class-scope specializations because we'll have matched them with
1846 // the appropriate template.
1847 } else if (!IsClassScopeSpecialization) {
1848 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001849 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001850
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001851 return Method;
1852}
1853
Douglas Gregor4044d992009-03-24 16:43:20 +00001854Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001855 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001856}
1857
Douglas Gregor654b07e2009-03-24 00:15:49 +00001858Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001859 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001860}
1861
Douglas Gregor1880ba52009-03-25 00:34:44 +00001862Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001863 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001864}
1865
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00001866Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00001867 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1868 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001869}
1870
John McCall87a44eb2009-08-20 01:44:21 +00001871Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1872 TemplateTypeParmDecl *D) {
1873 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00001874 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00001875
John McCall87a44eb2009-08-20 01:44:21 +00001876 TemplateTypeParmDecl *Inst =
Abramo Bagnarab3185b02011-03-06 15:48:19 +00001877 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1878 D->getLocStart(), D->getLocation(),
Chandler Carruth08836322011-05-01 00:51:33 +00001879 D->getDepth() - TemplateArgs.getNumLevels(),
1880 D->getIndex(), D->getIdentifier(),
John McCall87a44eb2009-08-20 01:44:21 +00001881 D->wasDeclaredWithTypename(),
1882 D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001883 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00001884
David Majnemer89189202013-08-28 23:48:32 +00001885 if (D->hasDefaultArgument()) {
1886 TypeSourceInfo *InstantiatedDefaultArg =
1887 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1888 D->getDefaultArgumentLoc(), D->getDeclName());
1889 if (InstantiatedDefaultArg)
1890 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1891 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001892
1893 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001894 // scope.
1895 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001896
John McCall87a44eb2009-08-20 01:44:21 +00001897 return Inst;
1898}
1899
Douglas Gregor6b815c82009-10-23 23:25:44 +00001900Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1901 NonTypeTemplateParmDecl *D) {
1902 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001903 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001904 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1905 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001906 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001907 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001908 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001909 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001910
1911 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001912 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001913 // expansion of types. Substitute into each of the expanded types.
1914 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1915 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1916 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1917 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1918 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001919 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001920 D->getDeclName());
1921 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001922 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001923
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001924 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1925 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1926 D->getLocation());
1927 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001928 return nullptr;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001929 ExpandedParameterPackTypes.push_back(NewT);
1930 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001931
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001932 IsExpandedParameterPack = true;
1933 DI = D->getTypeSourceInfo();
1934 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00001935 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001936 // The non-type template parameter pack's type is a pack expansion of types.
1937 // Determine whether we need to expand this parameter pack into separate
1938 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00001939 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001940 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001941 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001942 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001943
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001944 // Determine whether the set of unexpanded parameter packs can and should
1945 // be expanded.
1946 bool Expand = true;
1947 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001948 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001949 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00001950 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001951 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1952 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001953 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001954 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001955 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001956 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00001957 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001958
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001959 if (Expand) {
1960 for (unsigned I = 0; I != *NumExpansions; ++I) {
1961 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1962 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001963 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001964 D->getDeclName());
1965 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001966 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001967
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001968 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1969 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1970 NewDI->getType(),
1971 D->getLocation());
1972 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001973 return nullptr;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001974 ExpandedParameterPackTypes.push_back(NewT);
1975 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001976
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001977 // Note that we have an expanded parameter pack. The "type" of this
1978 // expanded parameter pack is the original expansion type, but callers
1979 // will end up using the expanded parameter pack types for type-checking.
1980 IsExpandedParameterPack = true;
1981 DI = D->getTypeSourceInfo();
1982 T = DI->getType();
1983 } else {
1984 // We cannot fully expand the pack expansion now, so substitute into the
1985 // pattern and create a new pack expansion type.
1986 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1987 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001988 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001989 D->getDeclName());
1990 if (!NewPattern)
Craig Topperc3ec1492014-05-26 06:22:03 +00001991 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001992
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001993 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1994 NumExpansions);
1995 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001996 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001997
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001998 T = DI->getType();
1999 }
2000 } else {
2001 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002002 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002003 D->getLocation(), D->getDeclName());
2004 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002005 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002006
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002007 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002008 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002009 D->getLocation());
2010 if (T.isNull()) {
2011 T = SemaRef.Context.IntTy;
2012 Invalid = true;
2013 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00002014 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002015
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002016 NonTypeTemplateParmDecl *Param;
2017 if (IsExpandedParameterPack)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002018 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002019 D->getInnerLocStart(),
2020 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002021 D->getDepth() - TemplateArgs.getNumLevels(),
2022 D->getPosition(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002023 D->getIdentifier(), T,
2024 DI,
2025 ExpandedParameterPackTypes.data(),
2026 ExpandedParameterPackTypes.size(),
2027 ExpandedParameterPackTypesAsWritten.data());
2028 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002029 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00002030 D->getInnerLocStart(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002031 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002032 D->getDepth() - TemplateArgs.getNumLevels(),
2033 D->getPosition(),
2034 D->getIdentifier(), T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002035 D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002036
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002037 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00002038 if (Invalid)
2039 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002040
David Majnemer89189202013-08-28 23:48:32 +00002041 if (D->hasDefaultArgument()) {
2042 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2043 if (!Value.isInvalid())
2044 Param->setDefaultArgument(Value.get(), false);
2045 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002046
2047 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00002048 // scope.
2049 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00002050 return Param;
2051}
2052
Richard Smith1fde8ec2012-09-07 02:06:42 +00002053static void collectUnexpandedParameterPacks(
2054 Sema &S,
2055 TemplateParameterList *Params,
2056 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2057 for (TemplateParameterList::const_iterator I = Params->begin(),
2058 E = Params->end(); I != E; ++I) {
2059 if ((*I)->isTemplateParameterPack())
2060 continue;
2061 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
2062 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2063 Unexpanded);
2064 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
2065 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2066 Unexpanded);
2067 }
2068}
2069
Anders Carlsson4bd78752009-08-28 15:18:15 +00002070Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00002071TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2072 TemplateTemplateParmDecl *D) {
2073 // Instantiate the template parameter list of the template template parameter.
2074 TemplateParameterList *TempParams = D->getTemplateParameters();
2075 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002076 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2077
2078 bool IsExpandedParameterPack = false;
2079
2080 if (D->isExpandedParameterPack()) {
2081 // The template template parameter pack is an already-expanded pack
2082 // expansion of template parameters. Substitute into each of the expanded
2083 // parameters.
2084 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2085 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2086 I != N; ++I) {
2087 LocalInstantiationScope Scope(SemaRef);
2088 TemplateParameterList *Expansion =
2089 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2090 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002091 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002092 ExpandedParams.push_back(Expansion);
2093 }
2094
2095 IsExpandedParameterPack = true;
2096 InstParams = TempParams;
2097 } else if (D->isPackExpansion()) {
2098 // The template template parameter pack expands to a pack of template
2099 // template parameters. Determine whether we need to expand this parameter
2100 // pack into separate parameters.
2101 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2102 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2103 Unexpanded);
2104
2105 // Determine whether the set of unexpanded parameter packs can and should
2106 // be expanded.
2107 bool Expand = true;
2108 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002109 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002110 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2111 TempParams->getSourceRange(),
2112 Unexpanded,
2113 TemplateArgs,
2114 Expand, RetainExpansion,
2115 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002116 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002117
2118 if (Expand) {
2119 for (unsigned I = 0; I != *NumExpansions; ++I) {
2120 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2121 LocalInstantiationScope Scope(SemaRef);
2122 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2123 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002124 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002125 ExpandedParams.push_back(Expansion);
2126 }
2127
2128 // Note that we have an expanded parameter pack. The "type" of this
2129 // expanded parameter pack is the original expansion type, but callers
2130 // will end up using the expanded parameter pack types for type-checking.
2131 IsExpandedParameterPack = true;
2132 InstParams = TempParams;
2133 } else {
2134 // We cannot fully expand the pack expansion now, so just substitute
2135 // into the pattern.
2136 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2137
2138 LocalInstantiationScope Scope(SemaRef);
2139 InstParams = SubstTemplateParams(TempParams);
2140 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002141 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002142 }
2143 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002144 // Perform the actual substitution of template parameters within a new,
2145 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002146 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002147 InstParams = SubstTemplateParams(TempParams);
2148 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002149 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002150 }
2151
Douglas Gregor38fee962009-11-11 16:58:32 +00002152 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002153 TemplateTemplateParmDecl *Param;
2154 if (IsExpandedParameterPack)
2155 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2156 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002157 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00002158 D->getPosition(),
2159 D->getIdentifier(), InstParams,
2160 ExpandedParams);
2161 else
2162 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2163 D->getLocation(),
2164 D->getDepth() - TemplateArgs.getNumLevels(),
2165 D->getPosition(),
2166 D->isParameterPack(),
2167 D->getIdentifier(), InstParams);
David Majnemer89189202013-08-28 23:48:32 +00002168 if (D->hasDefaultArgument()) {
2169 NestedNameSpecifierLoc QualifierLoc =
2170 D->getDefaultArgument().getTemplateQualifierLoc();
2171 QualifierLoc =
2172 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2173 TemplateName TName = SemaRef.SubstTemplateName(
2174 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2175 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2176 if (!TName.isNull())
2177 Param->setDefaultArgument(
2178 TemplateArgumentLoc(TemplateArgument(TName),
2179 D->getDefaultArgument().getTemplateQualifierLoc(),
2180 D->getDefaultArgument().getTemplateNameLoc()),
2181 false);
2182 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002183 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002184
2185 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002186 // scope.
2187 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002188
Douglas Gregor38fee962009-11-11 16:58:32 +00002189 return Param;
2190}
2191
Douglas Gregore0b28662009-11-17 06:07:40 +00002192Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002193 // Using directives are never dependent (and never contain any types or
2194 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002195
Douglas Gregore0b28662009-11-17 06:07:40 +00002196 UsingDirectiveDecl *Inst
2197 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002198 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002199 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002200 D->getIdentLocation(),
2201 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002202 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002203
2204 // Add the using directive to its declaration context
2205 // only if this is not a function or method.
2206 if (!Owner->isFunctionOrMethod())
2207 Owner->addDecl(Inst);
2208
Douglas Gregore0b28662009-11-17 06:07:40 +00002209 return Inst;
2210}
2211
John McCallb96ec562009-12-04 22:46:56 +00002212Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002213
2214 // The nested name specifier may be dependent, for example
2215 // template <typename T> struct t {
2216 // struct s1 { T f1(); };
2217 // struct s2 : s1 { using s1::f1; };
2218 // };
2219 // template struct t<int>;
2220 // Here, in using s1::f1, s1 refers to t<T>::s1;
2221 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002222 NestedNameSpecifierLoc QualifierLoc
2223 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2224 TemplateArgs);
2225 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002226 return nullptr;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002227
2228 // The name info is non-dependent, so no transformation
2229 // is required.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002230 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCallb96ec562009-12-04 22:46:56 +00002231
John McCall84d87672009-12-10 09:41:52 +00002232 // We only need to do redeclaration lookups if we're in a class
2233 // scope (in fact, it's not really even possible in non-class
2234 // scopes).
2235 bool CheckRedeclaration = Owner->isRecord();
2236
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002237 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2238 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002239
John McCallb96ec562009-12-04 22:46:56 +00002240 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002241 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002242 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002243 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002244 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002245
Douglas Gregor0499ab62011-02-25 15:54:31 +00002246 CXXScopeSpec SS;
2247 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002248 if (CheckRedeclaration) {
2249 Prev.setHideTags(false);
2250 SemaRef.LookupQualifiedName(Prev, Owner);
2251
2252 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002253 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2254 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002255 D->getLocation(), Prev))
2256 NewUD->setInvalidDecl();
2257
2258 }
2259
2260 if (!NewUD->isInvalidDecl() &&
Richard Smith7ad0b882014-04-02 21:44:35 +00002261 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00002262 D->getLocation()))
2263 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002264
John McCallb96ec562009-12-04 22:46:56 +00002265 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2266 NewUD->setAccess(D->getAccess());
2267 Owner->addDecl(NewUD);
2268
John McCall84d87672009-12-10 09:41:52 +00002269 // Don't process the shadow decls for an invalid decl.
2270 if (NewUD->isInvalidDecl())
2271 return NewUD;
2272
Richard Smith23d55872012-04-02 01:30:27 +00002273 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00002274 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
Richard Smith23d55872012-04-02 01:30:27 +00002275 return NewUD;
2276 }
2277
John McCalla1d85502009-12-22 22:26:37 +00002278 bool isFunctionScope = Owner->isFunctionOrMethod();
2279
John McCall84d87672009-12-10 09:41:52 +00002280 // Process the shadow decls.
Aaron Ballman91cdc282014-03-13 18:07:29 +00002281 for (auto *Shadow : D->shadows()) {
John McCall84d87672009-12-10 09:41:52 +00002282 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002283 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2284 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002285 if (!InstTarget)
Craig Topperc3ec1492014-05-26 06:22:03 +00002286 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00002287
Craig Topperc3ec1492014-05-26 06:22:03 +00002288 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00002289 if (CheckRedeclaration) {
2290 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2291 continue;
Richard Smith41c79d92014-10-11 00:37:16 +00002292 } else if (UsingShadowDecl *OldPrev =
2293 getPreviousDeclForInstantiation(Shadow)) {
Richard Smithfd8634a2013-10-23 02:17:46 +00002294 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2295 Shadow->getLocation(), OldPrev, TemplateArgs));
2296 }
John McCall84d87672009-12-10 09:41:52 +00002297
Richard Smithfd8634a2013-10-23 02:17:46 +00002298 UsingShadowDecl *InstShadow =
Craig Topperc3ec1492014-05-26 06:22:03 +00002299 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2300 PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002301 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002302
2303 if (isFunctionScope)
2304 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002305 }
John McCallb96ec562009-12-04 22:46:56 +00002306
2307 return NewUD;
2308}
2309
2310Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002311 // Ignore these; we handle them in bulk when processing the UsingDecl.
Craig Topperc3ec1492014-05-26 06:22:03 +00002312 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00002313}
2314
John McCalle61f2ba2009-11-18 02:36:19 +00002315Decl * TemplateDeclInstantiator
2316 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002317 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002318 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002319 TemplateArgs);
2320 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002321 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002322
Anders Carlsson4bd78752009-08-28 15:18:15 +00002323 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002324 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002325
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002326 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Kramerd81108f2012-11-14 15:08:31 +00002327 // Hence, no transformation is required for it.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002328 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002329 NamedDecl *UD =
Craig Topperc3ec1492014-05-26 06:22:03 +00002330 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2331 D->getUsingLoc(), SS, NameInfo, nullptr,
John McCalle61f2ba2009-11-18 02:36:19 +00002332 /*instantiation*/ true,
2333 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor6044d692010-05-19 17:02:24 +00002334 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002335 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2336
John McCalle61f2ba2009-11-18 02:36:19 +00002337 return UD;
2338}
2339
2340Decl * TemplateDeclInstantiator
2341 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002342 NestedNameSpecifierLoc QualifierLoc
2343 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2344 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002345 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002346
John McCalle61f2ba2009-11-18 02:36:19 +00002347 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002348 SS.Adopt(QualifierLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00002349
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002350 DeclarationNameInfo NameInfo
2351 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2352
John McCalle61f2ba2009-11-18 02:36:19 +00002353 NamedDecl *UD =
Craig Topperc3ec1492014-05-26 06:22:03 +00002354 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2355 D->getUsingLoc(), SS, NameInfo, nullptr,
John McCalle61f2ba2009-11-18 02:36:19 +00002356 /*instantiation*/ true,
2357 /*typename*/ false, SourceLocation());
Douglas Gregor6044d692010-05-19 17:02:24 +00002358 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002359 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2360
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002361 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00002362}
2363
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002364
2365Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2366 ClassScopeFunctionSpecializationDecl *Decl) {
2367 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nick Lewycky0b727732015-01-02 01:33:12 +00002368 CXXMethodDecl *NewFD =
2369 cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
2370 if (!NewFD)
2371 return nullptr;
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002372
2373 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2374 Sema::ForRedeclaration);
2375
Nico Weber7b5a7162012-06-25 17:21:05 +00002376 TemplateArgumentListInfo TemplateArgs;
Craig Topperc3ec1492014-05-26 06:22:03 +00002377 TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
Nico Weber7b5a7162012-06-25 17:21:05 +00002378 if (Decl->hasExplicitTemplateArgs()) {
2379 TemplateArgs = Decl->templateArgs();
2380 TemplateArgsPtr = &TemplateArgs;
2381 }
2382
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002383 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002384 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2385 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002386 NewFD->setInvalidDecl();
2387 return NewFD;
2388 }
2389
2390 // Associate the specialization with the pattern.
2391 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2392 assert(Specialization && "Class scope Specialization is null");
2393 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2394
2395 return NewFD;
2396}
2397
Alexey Bataeva769e072013-03-22 06:34:35 +00002398Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2399 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002400 SmallVector<Expr *, 5> Vars;
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002401 for (auto *I : D->varlists()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002402 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
Alexey Bataeva769e072013-03-22 06:34:35 +00002403 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002404 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002405 }
2406
2407 OMPThreadPrivateDecl *TD =
2408 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2409
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002410 TD->setAccess(AS_public);
2411 Owner->addDecl(TD);
2412
Alexey Bataeva769e072013-03-22 06:34:35 +00002413 return TD;
2414}
2415
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002416Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002417 return VisitFunctionDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002418}
2419
2420Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002421 return VisitCXXMethodDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002422}
2423
2424Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2425 llvm_unreachable("There are only CXXRecordDecls in C++");
2426}
2427
2428Decl *
2429TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2430 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00002431 // As a MS extension, we permit class-scope explicit specialization
2432 // of member class templates.
2433 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2434 assert(ClassTemplate->getDeclContext()->isRecord() &&
2435 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2436 "can only instantiate an explicit specialization "
2437 "for a member class template");
2438
2439 // Lookup the already-instantiated declaration in the instantiation
2440 // of the class template. FIXME: Diagnose or assert if this fails?
2441 DeclContext::lookup_result Found
2442 = Owner->lookup(ClassTemplate->getDeclName());
2443 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00002444 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002445 ClassTemplateDecl *InstClassTemplate
2446 = dyn_cast<ClassTemplateDecl>(Found.front());
2447 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00002448 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002449
2450 // Substitute into the template arguments of the class template explicit
2451 // specialization.
2452 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2453 castAs<TemplateSpecializationTypeLoc>();
2454 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2455 Loc.getRAngleLoc());
2456 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2457 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2458 ArgLocs.push_back(Loc.getArgLoc(I));
2459 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2460 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002461 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002462
2463 // Check that the template argument list is well-formed for this
2464 // class template.
2465 SmallVector<TemplateArgument, 4> Converted;
2466 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2467 D->getLocation(),
2468 InstTemplateArgs,
2469 false,
2470 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002471 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002472
2473 // Figure out where to insert this class template explicit specialization
2474 // in the member template's set of class template explicit specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002475 void *InsertPos = nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002476 ClassTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00002477 InstClassTemplate->findSpecialization(Converted, InsertPos);
Richard Smith8a0dde72013-12-14 01:04:22 +00002478
2479 // Check whether we've already seen a conflicting instantiation of this
2480 // declaration (for instance, if there was a prior implicit instantiation).
2481 bool Ignored;
2482 if (PrevDecl &&
2483 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2484 D->getSpecializationKind(),
2485 PrevDecl,
2486 PrevDecl->getSpecializationKind(),
2487 PrevDecl->getPointOfInstantiation(),
2488 Ignored))
Craig Topperc3ec1492014-05-26 06:22:03 +00002489 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002490
2491 // If PrevDecl was a definition and D is also a definition, diagnose.
2492 // This happens in cases like:
2493 //
2494 // template<typename T, typename U>
2495 // struct Outer {
2496 // template<typename X> struct Inner;
2497 // template<> struct Inner<T> {};
2498 // template<> struct Inner<U> {};
2499 // };
2500 //
2501 // Outer<int, int> outer; // error: the explicit specializations of Inner
2502 // // have the same signature.
2503 if (PrevDecl && PrevDecl->getDefinition() &&
2504 D->isThisDeclarationADefinition()) {
2505 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2506 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2507 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00002508 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002509 }
2510
2511 // Create the class template partial specialization declaration.
2512 ClassTemplateSpecializationDecl *InstD
2513 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2514 D->getTagKind(),
2515 Owner,
2516 D->getLocStart(),
2517 D->getLocation(),
2518 InstClassTemplate,
2519 Converted.data(),
2520 Converted.size(),
2521 PrevDecl);
2522
2523 // Add this partial specialization to the set of class template partial
2524 // specializations.
2525 if (!PrevDecl)
2526 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2527
2528 // Substitute the nested name specifier, if any.
2529 if (SubstQualifier(D, InstD))
Craig Topperc3ec1492014-05-26 06:22:03 +00002530 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002531
2532 // Build the canonical type that describes the converted template
2533 // arguments of the class template explicit specialization.
2534 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2535 TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2536 SemaRef.Context.getRecordType(InstD));
2537
2538 // Build the fully-sugared type for this class template
2539 // specialization as the user wrote in the specialization
2540 // itself. This means that we'll pretty-print the type retrieved
2541 // from the specialization's declaration the way that the user
2542 // actually wrote the specialization, rather than formatting the
2543 // name based on the "canonical" representation used to store the
2544 // template arguments in the specialization.
2545 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2546 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2547 CanonType);
2548
2549 InstD->setAccess(D->getAccess());
2550 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2551 InstD->setSpecializationKind(D->getSpecializationKind());
2552 InstD->setTypeAsWritten(WrittenTy);
2553 InstD->setExternLoc(D->getExternLoc());
2554 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2555
2556 Owner->addDecl(InstD);
2557
2558 // Instantiate the members of the class-scope explicit specialization eagerly.
2559 // We don't have support for lazy instantiation of an explicit specialization
2560 // yet, and MSVC eagerly instantiates in this case.
2561 if (D->isThisDeclarationADefinition() &&
2562 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2563 TSK_ImplicitInstantiation,
2564 /*Complain=*/true))
Craig Topperc3ec1492014-05-26 06:22:03 +00002565 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002566
2567 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002568}
2569
Larisse Voufo39a1e502013-08-06 01:03:05 +00002570Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2571 VarTemplateSpecializationDecl *D) {
2572
2573 TemplateArgumentListInfo VarTemplateArgsInfo;
2574 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2575 assert(VarTemplate &&
2576 "A template specialization without specialized template?");
2577
2578 // Substitute the current template arguments.
2579 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2580 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2581 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2582
2583 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2584 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002585 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002586
2587 // Check that the template argument list is well-formed for this template.
2588 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002589 if (SemaRef.CheckTemplateArgumentList(
2590 VarTemplate, VarTemplate->getLocStart(),
2591 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002592 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002593 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002594
2595 // Find the variable template specialization declaration that
2596 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002597 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002598 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002599 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002600 // If we already have a variable template specialization, return it.
2601 return VarSpec;
2602
2603 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2604 VarTemplateArgsInfo, Converted);
2605}
2606
2607Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2608 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2609 const TemplateArgumentListInfo &TemplateArgsInfo,
Craig Topper00bbdcf2014-06-28 23:22:23 +00002610 ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002611
2612 // If this is the variable for an anonymous struct or union,
2613 // instantiate the anonymous struct/union type first.
2614 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2615 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2616 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +00002617 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002618
2619 // Do substitution on the type of the declaration
2620 TypeSourceInfo *DI =
2621 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2622 D->getTypeSpecStartLoc(), D->getDeclName());
2623 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002624 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002625
2626 if (DI->getType()->isFunctionType()) {
2627 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2628 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00002629 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002630 }
2631
2632 // Build the instantiated declaration
2633 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2634 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2635 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2636 Converted.size());
2637 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00002638 if (InsertPos)
2639 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002640
2641 // Substitute the nested name specifier, if any.
2642 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +00002643 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002644
2645 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00002646 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002647
2648 return Var;
2649}
2650
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002651Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2652 llvm_unreachable("@defs is not supported in Objective-C++");
2653}
2654
2655Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2656 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2657 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2658 DiagnosticsEngine::Error,
2659 "cannot instantiate %0 yet");
2660 SemaRef.Diag(D->getLocation(), DiagID)
2661 << D->getDeclKindName();
2662
Craig Topperc3ec1492014-05-26 06:22:03 +00002663 return nullptr;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002664}
2665
2666Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2667 llvm_unreachable("Unexpected decl");
2668}
2669
John McCall76d824f2009-08-25 22:02:44 +00002670Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002671 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00002672 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00002673 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00002674 return nullptr;
Douglas Gregor71ad4772010-02-16 19:28:15 +00002675
Douglas Gregord7e7a512009-03-17 21:15:40 +00002676 return Instantiator.Visit(D);
2677}
2678
John McCall87a44eb2009-08-20 01:44:21 +00002679/// \brief Instantiates a nested template parameter list in the current
2680/// instantiation context.
2681///
2682/// \param L The parameter list to instantiate
2683///
2684/// \returns NULL if there was an error
2685TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00002686TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00002687 // Get errors for all the parameters before bailing out.
2688 bool Invalid = false;
2689
2690 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002691 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00002692 ParamVector Params;
2693 Params.reserve(N);
2694 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2695 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002696 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00002697 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00002698 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00002699 }
2700
2701 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00002702 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +00002703 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00002704
2705 TemplateParameterList *InstL
2706 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2707 L->getLAngleLoc(), &Params.front(), N,
2708 L->getRAngleLoc());
2709 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00002710}
John McCall87a44eb2009-08-20 01:44:21 +00002711
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002712/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002713/// specialization.
2714///
2715/// \param ClassTemplate the (instantiated) class template that is partially
2716// specialized by the instantiation of \p PartialSpec.
2717///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002718/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002719/// specialization that we are instantiating.
2720///
Douglas Gregor869853e2010-11-10 19:44:59 +00002721/// \returns The instantiated partial specialization, if successful; otherwise,
2722/// NULL to indicate an error.
2723ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00002724TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2725 ClassTemplateDecl *ClassTemplate,
2726 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00002727 // Create a local instantiation scope for this class template partial
2728 // specialization, which will contain the instantiations of the template
2729 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00002730 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002731
Douglas Gregor21610382009-10-29 00:04:11 +00002732 // Substitute into the template parameters of the class template partial
2733 // specialization.
2734 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2735 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2736 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002737 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002738
Douglas Gregor21610382009-10-29 00:04:11 +00002739 // Substitute into the template arguments of the class template partial
2740 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002741 const ASTTemplateArgumentListInfo *TemplArgInfo
2742 = PartialSpec->getTemplateArgsAsWritten();
2743 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2744 TemplArgInfo->RAngleLoc);
2745 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2746 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002747 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002748 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002749
Douglas Gregor21610382009-10-29 00:04:11 +00002750 // Check that the template argument list is well-formed for this
2751 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002752 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002753 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00002754 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002755 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002756 false,
2757 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002758 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002759
2760 // Figure out where to insert this class template partial specialization
2761 // in the member template's set of class template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002762 void *InsertPos = nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002763 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00002764 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002765
Douglas Gregor21610382009-10-29 00:04:11 +00002766 // Build the canonical type that describes the converted template
2767 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002768 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00002769 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002770 Converted.data(),
2771 Converted.size());
Douglas Gregor21610382009-10-29 00:04:11 +00002772
2773 // Build the fully-sugared type for this class template
2774 // specialization as the user wrote in the specialization
2775 // itself. This means that we'll pretty-print the type retrieved
2776 // from the specialization's declaration the way that the user
2777 // actually wrote the specialization, rather than formatting the
2778 // name based on the "canonical" representation used to store the
2779 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00002780 TypeSourceInfo *WrittenTy
2781 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2782 TemplateName(ClassTemplate),
2783 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002784 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002785 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002786
Douglas Gregor21610382009-10-29 00:04:11 +00002787 if (PrevDecl) {
2788 // We've already seen a partial specialization with the same template
2789 // parameters and template arguments. This can happen, for example, when
2790 // substituting the outer template arguments ends up causing two
2791 // class template partial specializations of a member class template
2792 // to have identical forms, e.g.,
2793 //
2794 // template<typename T, typename U>
2795 // struct Outer {
2796 // template<typename X, typename Y> struct Inner;
2797 // template<typename Y> struct Inner<T, Y>;
2798 // template<typename Y> struct Inner<U, Y>;
2799 // };
2800 //
2801 // Outer<int, int> outer; // error: the partial specializations of Inner
2802 // // have the same signature.
2803 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00002804 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00002805 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2806 << SemaRef.Context.getTypeDeclType(PrevDecl);
Craig Topperc3ec1492014-05-26 06:22:03 +00002807 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002808 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002809
2810
Douglas Gregor21610382009-10-29 00:04:11 +00002811 // Create the class template partial specialization declaration.
2812 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002813 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002814 PartialSpec->getTagKind(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002815 Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002816 PartialSpec->getLocStart(),
2817 PartialSpec->getLocation(),
Douglas Gregor21610382009-10-29 00:04:11 +00002818 InstParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002819 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002820 Converted.data(),
2821 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00002822 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00002823 CanonType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002824 nullptr);
John McCall3e11ebe2010-03-15 10:12:16 +00002825 // Substitute the nested name specifier, if any.
2826 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00002827 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00002828
Douglas Gregor21610382009-10-29 00:04:11 +00002829 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00002830 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002831
Douglas Gregor21610382009-10-29 00:04:11 +00002832 // Add this partial specialization to the set of class template partial
2833 // specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002834 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
2835 /*InsertPos=*/nullptr);
Douglas Gregor869853e2010-11-10 19:44:59 +00002836 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00002837}
2838
Larisse Voufo39a1e502013-08-06 01:03:05 +00002839/// \brief Instantiate the declaration of a variable template partial
2840/// specialization.
2841///
2842/// \param VarTemplate the (instantiated) variable template that is partially
2843/// specialized by the instantiation of \p PartialSpec.
2844///
2845/// \param PartialSpec the (uninstantiated) variable template partial
2846/// specialization that we are instantiating.
2847///
2848/// \returns The instantiated partial specialization, if successful; otherwise,
2849/// NULL to indicate an error.
2850VarTemplatePartialSpecializationDecl *
2851TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2852 VarTemplateDecl *VarTemplate,
2853 VarTemplatePartialSpecializationDecl *PartialSpec) {
2854 // Create a local instantiation scope for this variable template partial
2855 // specialization, which will contain the instantiations of the template
2856 // parameters.
2857 LocalInstantiationScope Scope(SemaRef);
2858
2859 // Substitute into the template parameters of the variable template partial
2860 // specialization.
2861 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2862 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2863 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002864 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002865
2866 // Substitute into the template arguments of the variable template partial
2867 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002868 const ASTTemplateArgumentListInfo *TemplArgInfo
2869 = PartialSpec->getTemplateArgsAsWritten();
2870 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2871 TemplArgInfo->RAngleLoc);
2872 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2873 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002874 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002875 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002876
2877 // Check that the template argument list is well-formed for this
2878 // class template.
2879 SmallVector<TemplateArgument, 4> Converted;
2880 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2881 InstTemplateArgs, false, Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002882 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002883
2884 // Figure out where to insert this variable template partial specialization
2885 // in the member template's set of variable template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002886 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002887 VarTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00002888 VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002889
2890 // Build the canonical type that describes the converted template
2891 // arguments of the variable template partial specialization.
2892 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2893 TemplateName(VarTemplate), Converted.data(), Converted.size());
2894
2895 // Build the fully-sugared type for this variable template
2896 // specialization as the user wrote in the specialization
2897 // itself. This means that we'll pretty-print the type retrieved
2898 // from the specialization's declaration the way that the user
2899 // actually wrote the specialization, rather than formatting the
2900 // name based on the "canonical" representation used to store the
2901 // template arguments in the specialization.
2902 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2903 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2904 CanonType);
2905
2906 if (PrevDecl) {
2907 // We've already seen a partial specialization with the same template
2908 // parameters and template arguments. This can happen, for example, when
2909 // substituting the outer template arguments ends up causing two
2910 // variable template partial specializations of a member variable template
2911 // to have identical forms, e.g.,
2912 //
2913 // template<typename T, typename U>
2914 // struct Outer {
2915 // template<typename X, typename Y> pair<X,Y> p;
2916 // template<typename Y> pair<T, Y> p;
2917 // template<typename Y> pair<U, Y> p;
2918 // };
2919 //
2920 // Outer<int, int> outer; // error: the partial specializations of Inner
2921 // // have the same signature.
2922 SemaRef.Diag(PartialSpec->getLocation(),
2923 diag::err_var_partial_spec_redeclared)
2924 << WrittenTy->getType();
2925 SemaRef.Diag(PrevDecl->getLocation(),
2926 diag::note_var_prev_partial_spec_here);
Craig Topperc3ec1492014-05-26 06:22:03 +00002927 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002928 }
2929
2930 // Do substitution on the type of the declaration
2931 TypeSourceInfo *DI = SemaRef.SubstType(
2932 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2933 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2934 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002935 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002936
2937 if (DI->getType()->isFunctionType()) {
2938 SemaRef.Diag(PartialSpec->getLocation(),
2939 diag::err_variable_instantiates_to_function)
2940 << PartialSpec->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00002941 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002942 }
2943
2944 // Create the variable template partial specialization declaration.
2945 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2946 VarTemplatePartialSpecializationDecl::Create(
2947 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2948 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2949 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smithb2f61b42013-08-22 23:27:37 +00002950 Converted.size(), InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002951
2952 // Substitute the nested name specifier, if any.
2953 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00002954 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002955
2956 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2957 InstPartialSpec->setTypeAsWritten(WrittenTy);
2958
Larisse Voufo39a1e502013-08-06 01:03:05 +00002959 // Add this partial specialization to the set of variable template partial
2960 // specializations. The instantiation of the initializer is not necessary.
Craig Topperc3ec1492014-05-26 06:22:03 +00002961 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002962
Larisse Voufo4cda4612013-08-22 00:28:27 +00002963 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00002964 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002965
Larisse Voufo39a1e502013-08-06 01:03:05 +00002966 return InstPartialSpec;
2967}
2968
John McCall58f10c32010-03-11 09:03:00 +00002969TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00002970TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002971 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00002972 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2973 assert(OldTInfo && "substituting function without type source info");
2974 assert(Params.empty() && "parameter vector is non-empty at start");
Craig Topperc3ec1492014-05-26 06:22:03 +00002975
2976 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002977 unsigned ThisTypeQuals = 0;
2978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002979 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00002980 ThisTypeQuals = Method->getTypeQualifiers();
2981 }
2982
John McCallb29f78f2010-04-09 17:38:44 +00002983 TypeSourceInfo *NewTInfo
2984 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2985 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002986 D->getDeclName(),
2987 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00002988 if (!NewTInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00002989 return nullptr;
Douglas Gregor21342092009-03-24 00:38:23 +00002990
Reid Klecknera09e44c2013-07-31 21:00:18 +00002991 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2992 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2993 if (NewTInfo != OldTInfo) {
2994 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00002995 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00002996 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00002997 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002998 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00002999 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003000 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00003001 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3002
David Blaikie05785d12013-02-20 22:23:23 +00003003 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00003004 if (OldParam->isParameterPack())
3005 NumArgumentsInExpansion =
3006 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3007 TemplateArgs);
3008 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003009 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00003010 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003011 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00003012 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00003013 Scope->InstantiatedLocal(OldParam, NewParam);
3014 } else {
3015 // Parameter pack expansion: make the instantiation an argument pack.
3016 Scope->MakeInstantiatedLocalArgPack(OldParam);
3017 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003018 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00003019 Params.push_back(NewParam);
3020 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3021 }
Douglas Gregorf3010112011-01-07 16:43:16 +00003022 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003023 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003024 } else {
3025 // The function type itself was not dependent and therefore no
3026 // substitution occurred. However, we still need to instantiate
3027 // the function parameters themselves.
3028 const FunctionProtoType *OldProto =
3029 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00003030 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3031 ++i) {
3032 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00003033 if (!OldParam) {
3034 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00003035 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00003036 continue;
3037 }
3038
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00003039 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00003040 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003041 if (!Parm)
Craig Topperc3ec1492014-05-26 06:22:03 +00003042 return nullptr;
Douglas Gregor95c70ec2010-05-03 15:32:18 +00003043 Params.push_back(Parm);
3044 }
Douglas Gregor940bca72010-04-12 07:48:19 +00003045 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003046 } else {
3047 // If the type of this function, after ignoring parentheses, is not
3048 // *directly* a function type, then we're instantiating a function that
3049 // was declared via a typedef or with attributes, e.g.,
3050 //
3051 // typedef int functype(int, int);
3052 // functype func;
3053 // int __cdecl meth(int, int);
3054 //
3055 // In this case, we'll just go instantiate the ParmVarDecls that we
3056 // synthesized in the method declaration.
3057 SmallVector<QualType, 4> ParamTypes;
3058 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
3059 D->getNumParams(), TemplateArgs, ParamTypes,
3060 &Params))
Craig Topperc3ec1492014-05-26 06:22:03 +00003061 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00003062 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00003063
John McCall58f10c32010-03-11 09:03:00 +00003064 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00003065}
3066
Richard Smithf623c962012-04-17 00:58:00 +00003067/// Introduce the instantiated function parameters into the local
3068/// instantiation scope, and set the parameter names to those used
3069/// in the template.
Richard Smith2e321552014-11-12 02:00:47 +00003070static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
Richard Smithf623c962012-04-17 00:58:00 +00003071 const FunctionDecl *PatternDecl,
3072 LocalInstantiationScope &Scope,
3073 const MultiLevelTemplateArgumentList &TemplateArgs) {
3074 unsigned FParamIdx = 0;
3075 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3076 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3077 if (!PatternParam->isParameterPack()) {
3078 // Simple case: not a parameter pack.
3079 assert(FParamIdx < Function->getNumParams());
3080 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smith2e321552014-11-12 02:00:47 +00003081 FunctionParam->setDeclName(PatternParam->getDeclName());
Richard Smithaae40582014-03-13 00:28:45 +00003082 // If the parameter's type is not dependent, update it to match the type
3083 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3084 // the pattern's type here. If the type is dependent, they can't differ,
Richard Smith2e321552014-11-12 02:00:47 +00003085 // per core issue 1668. Substitute into the type from the pattern, in case
3086 // it's instantiation-dependent.
Richard Smithaae40582014-03-13 00:28:45 +00003087 // FIXME: Updating the type to work around this is at best fragile.
Richard Smith2e321552014-11-12 02:00:47 +00003088 if (!PatternDecl->getType()->isDependentType()) {
3089 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3090 FunctionParam->getLocation(),
3091 FunctionParam->getDeclName());
3092 if (T.isNull())
3093 return true;
3094 FunctionParam->setType(T);
3095 }
Richard Smithaae40582014-03-13 00:28:45 +00003096
Richard Smithf623c962012-04-17 00:58:00 +00003097 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3098 ++FParamIdx;
3099 continue;
3100 }
3101
3102 // Expand the parameter pack.
3103 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003104 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003105 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00003106 assert(NumArgumentsInExpansion &&
3107 "should only be called when all template arguments are known");
Richard Smith2e321552014-11-12 02:00:47 +00003108 QualType PatternType =
3109 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
Richard Smith198223b2012-07-18 01:29:05 +00003110 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00003111 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
NAKAMURA Takumi23224152014-10-17 12:48:37 +00003112 FunctionParam->setDeclName(PatternParam->getDeclName());
Richard Smith2e321552014-11-12 02:00:47 +00003113 if (!PatternDecl->getType()->isDependentType()) {
3114 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3115 QualType T = S.SubstType(PatternType, TemplateArgs,
3116 FunctionParam->getLocation(),
3117 FunctionParam->getDeclName());
3118 if (T.isNull())
3119 return true;
3120 FunctionParam->setType(T);
3121 }
3122
Richard Smithf623c962012-04-17 00:58:00 +00003123 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3124 ++FParamIdx;
3125 }
3126 }
Richard Smithf623c962012-04-17 00:58:00 +00003127
Richard Smith2e321552014-11-12 02:00:47 +00003128 return false;
Richard Smithf623c962012-04-17 00:58:00 +00003129}
3130
3131void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3132 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003133 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3134 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003135 return;
3136
3137 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3138 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003139 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003140 // We hit the instantiation depth limit. Clear the exception specification
3141 // so that our callers don't have to cope with EST_Uninstantiated.
Richard Smith8acb4282014-07-31 21:57:55 +00003142 UpdateExceptionSpec(Decl, EST_None);
Richard Smithf623c962012-04-17 00:58:00 +00003143 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003144 }
Richard Smithf623c962012-04-17 00:58:00 +00003145
3146 // Enter the scope of this instantiation. We don't use
3147 // PushDeclContext because we don't have a scope.
3148 Sema::ContextRAII savedContext(*this, Decl);
3149 LocalInstantiationScope Scope(*this);
3150
3151 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003152 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
Richard Smithf623c962012-04-17 00:58:00 +00003153
Richard Smithd3729422012-04-19 00:08:28 +00003154 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
Richard Smith2e321552014-11-12 02:00:47 +00003155 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3156 TemplateArgs)) {
3157 UpdateExceptionSpec(Decl, EST_None);
3158 return;
3159 }
Richard Smithf623c962012-04-17 00:58:00 +00003160
Richard Smith2e321552014-11-12 02:00:47 +00003161 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3162 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003163}
3164
Mike Stump11289f42009-09-09 15:08:12 +00003165/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003166/// declaration (New) from the corresponding fields of its template (Tmpl).
3167///
3168/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003169bool
3170TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003171 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003172 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003173 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003174
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003175 // Forward the mangling number from the template to the instantiated decl.
3176 SemaRef.Context.setManglingNumber(New,
3177 SemaRef.Context.getManglingNumber(Tmpl));
3178
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003179 // If we are performing substituting explicitly-specified template arguments
3180 // or deduced template arguments into a function template and we reach this
3181 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003182 // to keeping the new function template specialization. We therefore
3183 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003184 // into a template instantiation for this specific function template
3185 // specialization, which is not a SFINAE context, so that we diagnose any
3186 // further errors in the declaration itself.
3187 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3188 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3189 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3190 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003191 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003192 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003193 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003194 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003195 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003196 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003197 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003198 }
3199 }
Mike Stump11289f42009-09-09 15:08:12 +00003200
Douglas Gregor049bdca2009-12-08 17:45:32 +00003201 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3202 assert(Proto && "Function template without prototype?");
3203
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003204 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003205 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003206
Richard Smithf623c962012-04-17 00:58:00 +00003207 // DR1330: In C++11, defer instantiation of a non-trivial
3208 // exception specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003209 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith8acb4282014-07-31 21:57:55 +00003210 EPI.ExceptionSpec.Type != EST_None &&
3211 EPI.ExceptionSpec.Type != EST_DynamicNone &&
3212 EPI.ExceptionSpec.Type != EST_BasicNoexcept) {
Richard Smithd3729422012-04-19 00:08:28 +00003213 FunctionDecl *ExceptionSpecTemplate = Tmpl;
Richard Smith8acb4282014-07-31 21:57:55 +00003214 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3215 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003216 ExceptionSpecificationType NewEST = EST_Uninstantiated;
Richard Smith8acb4282014-07-31 21:57:55 +00003217 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
Richard Smith185be182013-04-10 05:48:59 +00003218 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003219
Richard Smithf623c962012-04-17 00:58:00 +00003220 // Mark the function has having an uninstantiated exception specification.
3221 const FunctionProtoType *NewProto
3222 = New->getType()->getAs<FunctionProtoType>();
3223 assert(NewProto && "Template instantiation without function prototype?");
3224 EPI = NewProto->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00003225 EPI.ExceptionSpec.Type = NewEST;
3226 EPI.ExceptionSpec.SourceDecl = New;
3227 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003228 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003229 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003230 } else {
Richard Smith2e321552014-11-12 02:00:47 +00003231 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003232 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003233 }
3234
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003235 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003236 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003237 Tmpl->isDefined(Definition);
3238
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003239 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3240 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003241
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003242 return false;
3243}
3244
Douglas Gregor21342092009-03-24 00:38:23 +00003245/// \brief Initializes common fields of an instantiated method
3246/// declaration (New) from the corresponding fields of its template
3247/// (Tmpl).
3248///
3249/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003250bool
3251TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003252 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003253 if (InitFunctionInstantiation(New, Tmpl))
3254 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003255
Douglas Gregor21342092009-03-24 00:38:23 +00003256 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003257 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003258 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003259
Douglas Gregor21342092009-03-24 00:38:23 +00003260 // FIXME: New needs a pointer to Tmpl
3261 return false;
3262}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003263
3264/// \brief Instantiate the definition of the given function from its
3265/// template.
3266///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003267/// \param PointOfInstantiation the point at which the instantiation was
3268/// required. Note that this is not precisely a "point of instantiation"
3269/// for the function, but it's close.
3270///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003271/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003272/// function template specialization or member function of a class template
3273/// specialization.
3274///
3275/// \param Recursive if true, recursively instantiates any functions that
3276/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003277///
3278/// \param DefinitionRequired if true, then we are performing an explicit
3279/// instantiation where the body of the function is required. Complain if
3280/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003281void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003282 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003283 bool Recursive,
3284 bool DefinitionRequired) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003285 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00003286 return;
3287
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003288 // Never instantiate an explicit specialization except if it is a class scope
3289 // explicit specialization.
3290 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3291 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003292 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003293
Douglas Gregor24c332b2009-05-14 21:06:31 +00003294 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003295 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003296 assert(PatternDecl && "instantiating a non-template");
3297
3298 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3299 assert(PatternDecl && "template definition is not a template");
3300 if (!Pattern) {
3301 // Try to find a defaulted definition
3302 PatternDecl->isDefined(PatternDecl);
Alexis Hunt92a0adf2011-05-25 22:02:25 +00003303 }
Alexis Hunt23f6b832011-05-27 20:00:14 +00003304 assert(PatternDecl && "template definition is not a template");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003305
Francois Pichet1c229c02011-04-22 22:18:13 +00003306 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003307 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003308 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00003309 PendingInstantiations.push_back(
3310 std::make_pair(Function, PointOfInstantiation));
3311 return;
3312 }
3313
Nico Weberae4bb8c2014-08-15 23:21:41 +00003314 // If we're performing recursive template instantiation, create our own
3315 // queue of pending implicit instantiations that we will instantiate later,
3316 // while we're still within our own instantiation context.
3317 // This has to happen before LateTemplateParser below is called, so that
3318 // it marks vtables used in late parsed templates as used.
3319 SavePendingLocalImplicitInstantiationsRAII
3320 SavedPendingLocalImplicitInstantiations(*this);
Nico Weber7a92e1a2015-01-18 01:50:35 +00003321 SavePendingInstantiationsAndVTableUsesRAII
3322 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
Nico Weberae4bb8c2014-08-15 23:21:41 +00003323
David Majnemerf0a84f22013-08-16 08:29:13 +00003324 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003325 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003326 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003327 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003328 // FIXME: Optimize to allow individual templates to be deserialized.
3329 if (PatternDecl->isFromASTFile())
3330 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3331
3332 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3333 assert(LPT && "missing LateParsedTemplate");
3334 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet1c229c02011-04-22 22:18:13 +00003335 Pattern = PatternDecl->getBody(PatternDecl);
3336 }
3337
Alexis Hunt23f6b832011-05-27 20:00:14 +00003338 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003339 if (DefinitionRequired) {
3340 if (Function->getPrimaryTemplate())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003341 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003342 diag::err_explicit_instantiation_undefined_func_template)
3343 << Function->getPrimaryTemplate();
3344 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003345 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003346 diag::err_explicit_instantiation_undefined_member)
3347 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003348
Douglas Gregora8b89d22009-10-15 14:05:49 +00003349 if (PatternDecl)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003350 Diag(PatternDecl->getLocation(),
Douglas Gregora8b89d22009-10-15 14:05:49 +00003351 diag::note_explicit_instantiation_here);
Douglas Gregorfd7224f2010-05-17 17:57:54 +00003352 Function->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003353 } else if (Function->getTemplateSpecializationKind()
3354 == TSK_ExplicitInstantiationDefinition) {
Nico Weberae4bb8c2014-08-15 23:21:41 +00003355 assert(!Recursive);
Chandler Carruth54080172010-08-25 08:44:16 +00003356 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003357 std::make_pair(Function, PointOfInstantiation));
Douglas Gregora8b89d22009-10-15 14:05:49 +00003358 }
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003359
Douglas Gregor24c332b2009-05-14 21:06:31 +00003360 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00003361 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003362
Richard Smith2a7d4812013-05-04 07:00:32 +00003363 // C++1y [temp.explicit]p10:
3364 // Except for inline functions, declarations with types deduced from their
3365 // initializer or return value, and class template specializations, other
3366 // explicit instantiation declarations have the effect of suppressing the
3367 // implicit instantiation of the entity to which they refer.
Alp Toker314cc812014-01-25 16:55:45 +00003368 if (Function->getTemplateSpecializationKind() ==
3369 TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003370 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00003371 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003372 return;
Mike Stump11289f42009-09-09 15:08:12 +00003373
Richard Smith195d8ef2014-05-29 03:15:31 +00003374 if (PatternDecl->isInlined()) {
3375 // Function, and all later redeclarations of it (from imported modules,
3376 // for instance), are now implicitly inline.
3377 for (auto *D = Function->getMostRecentDecl(); /**/;
3378 D = D->getPreviousDecl()) {
3379 D->setImplicitlyInline();
3380 if (D == Function)
3381 break;
3382 }
3383 }
Richard Smithf3814ad2013-01-25 00:08:28 +00003384
Douglas Gregor85673582009-05-18 17:01:57 +00003385 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003386 if (Inst.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003387 return;
3388
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00003389 // Copy the inner loc start from the pattern.
3390 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3391
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003392 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00003393 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00003394
Douglas Gregorb4850462009-05-14 23:26:13 +00003395 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003396 // recorded, unless we're actually a member function within a local
3397 // class, in which case we need to merge our results with the parent
3398 // scope (of the enclosing function).
3399 bool MergeWithParentScope = false;
3400 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3401 MergeWithParentScope = Rec->isLocalClass();
3402
3403 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00003404
Richard Smithbd305122012-12-11 01:14:52 +00003405 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003406 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00003407 else {
Richard Smithcc928662014-10-17 20:37:29 +00003408 MultiLevelTemplateArgumentList TemplateArgs =
3409 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3410
3411 // Substitute into the qualifier; we can get a substitution failure here
3412 // through evil use of alias templates.
3413 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3414 // of the) lexical context of the pattern?
3415 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3416
Craig Topperc3ec1492014-05-26 06:22:03 +00003417 ActOnStartOfFunctionDef(nullptr, Function);
Richard Smithbd305122012-12-11 01:14:52 +00003418
3419 // Enter the scope of this instantiation. We don't use
3420 // PushDeclContext because we don't have a scope.
3421 Sema::ContextRAII savedContext(*this, Function);
3422
Richard Smith2e321552014-11-12 02:00:47 +00003423 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3424 TemplateArgs))
3425 return;
Richard Smithbd305122012-12-11 01:14:52 +00003426
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003427 // If this is a constructor, instantiate the member initializers.
3428 if (const CXXConstructorDecl *Ctor =
3429 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3430 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3431 TemplateArgs);
3432 }
3433
3434 // Instantiate the function body.
3435 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3436
3437 if (Body.isInvalid())
3438 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003439
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003440 ActOnFinishFunctionBody(Function, Body.get(),
3441 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00003442
3443 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3444
Richard Smithd28ac5b2014-03-22 23:33:22 +00003445 if (auto *Listener = getASTMutationListener())
3446 Listener->FunctionDefinitionInstantiated(Function);
Richard Smith0ac1b8f2014-03-22 01:43:32 +00003447
Richard Smithbd305122012-12-11 01:14:52 +00003448 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00003449 }
3450
Douglas Gregor28ad4b52009-05-26 20:50:29 +00003451 DeclGroupRef DG(Function);
3452 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003453
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003454 // This class may have local implicit instantiations that need to be
3455 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003456 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003457 Scope.Exit();
3458
Douglas Gregordda7ced2009-06-30 17:20:14 +00003459 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003460 // Define any pending vtables.
3461 DefineUsedVTables();
3462
Douglas Gregordda7ced2009-06-30 17:20:14 +00003463 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003464 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003465 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003466
Nico Weber7a92e1a2015-01-18 01:50:35 +00003467 // PendingInstantiations and VTableUses are restored through
3468 // SavePendingInstantiationsAndVTableUses's destructor.
Douglas Gregordda7ced2009-06-30 17:20:14 +00003469 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003470}
3471
Larisse Voufo39a1e502013-08-06 01:03:05 +00003472VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3473 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3474 const TemplateArgumentList &TemplateArgList,
3475 const TemplateArgumentListInfo &TemplateArgsInfo,
3476 SmallVectorImpl<TemplateArgument> &Converted,
3477 SourceLocation PointOfInstantiation, void *InsertPos,
3478 LateInstantiatedAttrVec *LateAttrs,
3479 LocalInstantiationScope *StartingScope) {
3480 if (FromVar->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00003481 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003482
3483 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003484 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003485 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003486
3487 MultiLevelTemplateArgumentList TemplateArgLists;
3488 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3489
Richard Smith8809a0c2013-09-27 20:14:12 +00003490 // Instantiate the first declaration of the variable template: for a partial
3491 // specialization of a static data member template, the first declaration may
3492 // or may not be the declaration in the class; if it's in the class, we want
3493 // to instantiate a member in the class (a declaration), and if it's outside,
3494 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00003495 //
3496 // If we're instantiating an explicitly-specialized member template or member
3497 // partial specialization, don't do this. The member specialization completely
3498 // replaces the original declaration in this case.
3499 bool IsMemberSpec = false;
3500 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3501 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3502 IsMemberSpec = PartialSpec->isMemberSpecialization();
3503 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3504 IsMemberSpec = FromTemplate->isMemberSpecialization();
3505 if (!IsMemberSpec)
3506 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00003507
Manuel Klimek5843add2013-09-30 13:29:01 +00003508 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3509 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3510 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003511
3512 // TODO: Set LateAttrs and StartingScope ...
3513
3514 return cast_or_null<VarTemplateSpecializationDecl>(
3515 Instantiator.VisitVarTemplateSpecializationDecl(
3516 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3517}
3518
3519/// \brief Instantiates a variable template specialization by completing it
3520/// with appropriate type information and initializer.
3521VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3522 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3523 const MultiLevelTemplateArgumentList &TemplateArgs) {
3524
3525 // Do substitution on the type of the declaration
3526 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00003527 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003528 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3529 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003530 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003531
3532 // Update the type of this variable template specialization.
3533 VarSpec->setType(DI->getType());
3534
3535 // Instantiate the initializer.
3536 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3537
3538 return VarSpec;
3539}
3540
3541/// BuildVariableInstantiation - Used after a new variable has been created.
3542/// Sets basic variable data and decides whether to postpone the
3543/// variable instantiation.
3544void Sema::BuildVariableInstantiation(
3545 VarDecl *NewVar, VarDecl *OldVar,
3546 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003547 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3548 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003549 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003550
Richard Smith541b38b2013-09-20 01:15:31 +00003551 // If we are instantiating a local extern declaration, the
3552 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003553 // If we are instantiating a static data member defined
3554 // out-of-line, the instantiation will have the same lexical
3555 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00003556 if (OldVar->isLocalExternDecl()) {
3557 NewVar->setLocalExternDecl();
3558 NewVar->setLexicalDeclContext(Owner);
3559 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003560 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3561 NewVar->setTSCSpec(OldVar->getTSCSpec());
3562 NewVar->setInitStyle(OldVar->getInitStyle());
3563 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3564 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00003565 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00003566 NewVar->setPreviousDeclInSameBlockScope(
3567 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003568 NewVar->setAccess(OldVar->getAccess());
3569
Richard Smith0b551192013-09-23 23:12:22 +00003570 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00003571 if (OldVar->isUsed(false))
3572 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003573 NewVar->setReferenced(OldVar->isReferenced());
3574 }
3575
David Majnemer50ce8352013-09-17 23:57:10 +00003576 // See if the old variable had a type-specifier that defined an anonymous tag.
3577 // If it did, mark the new variable as being the declarator for the new
3578 // anonymous tag.
3579 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3580 TagDecl *OldTag = OldTagType->getDecl();
3581 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3582 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3583 assert(!NewTag->hasNameForLinkage() &&
3584 !NewTag->hasDeclaratorForAnonDecl());
3585 NewTag->setDeclaratorForAnonDecl(NewVar);
3586 }
3587 }
3588
Larisse Voufo39a1e502013-08-06 01:03:05 +00003589 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3590
Richard Smith541b38b2013-09-20 01:15:31 +00003591 LookupResult Previous(
3592 *this, NewVar->getDeclName(), NewVar->getLocation(),
3593 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3594 : Sema::LookupOrdinaryName,
3595 Sema::ForRedeclaration);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003596
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00003597 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3598 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3599 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00003600 // We have a previous declaration. Use that one, so we merge with the
3601 // right type.
3602 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3603 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3604 Previous.addDecl(NewPrev);
3605 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3606 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003607 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003608 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003609
Richard Smith541b38b2013-09-20 01:15:31 +00003610 if (!InstantiatingVarTemplate) {
3611 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3612 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003613 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00003614 }
3615
3616 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003617 if (NewVar->getDeclContext()->isFunctionOrMethod())
3618 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3619 }
3620
3621 // Link instantiations of static data members back to the template from
3622 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003623 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003624 NewVar->setInstantiationOfStaticDataMember(OldVar,
3625 TSK_ImplicitInstantiation);
3626
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003627 // Forward the mangling number from the template to the instantiated decl.
3628 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00003629 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003630
Richard Smith8809a0c2013-09-27 20:14:12 +00003631 // Delay instantiation of the initializer for variable templates until a
Richard Smithd292b242014-03-16 01:00:40 +00003632 // definition of the variable is needed. We need it right away if the type
3633 // contains 'auto'.
3634 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3635 !InstantiatingVarTemplate) ||
3636 NewVar->getType()->isUndeducedType())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003637 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3638
3639 // Diagnose unused local variables with dependent types, where the diagnostic
3640 // will have been deferred.
3641 if (!NewVar->isInvalidDecl() &&
Nico Weber72889432014-09-06 01:25:55 +00003642 NewVar->getDeclContext()->isFunctionOrMethod() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003643 OldVar->getType()->isDependentType())
3644 DiagnoseUnusedDecl(NewVar);
3645}
3646
3647/// \brief Instantiate the initializer of a variable.
3648void Sema::InstantiateVariableInitializer(
3649 VarDecl *Var, VarDecl *OldVar,
3650 const MultiLevelTemplateArgumentList &TemplateArgs) {
3651
3652 if (Var->getAnyInitializer())
3653 // We already have an initializer in the class.
3654 return;
3655
3656 if (OldVar->getInit()) {
3657 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3658 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3659 else
3660 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3661
3662 // Instantiate the initializer.
3663 ExprResult Init =
3664 SubstInitializer(OldVar->getInit(), TemplateArgs,
3665 OldVar->getInitStyle() == VarDecl::CallInit);
3666 if (!Init.isInvalid()) {
3667 bool TypeMayContainAuto = true;
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00003668 Expr *InitExpr = Init.get();
3669
Richard Smith95b83e92014-07-10 20:53:43 +00003670 if (Var->hasAttr<DLLImportAttr>() &&
3671 (!InitExpr ||
3672 !InitExpr->isConstantInitializer(getASTContext(), false))) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00003673 // Do not dynamically initialize dllimport variables.
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00003674 } else if (InitExpr) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003675 bool DirectInit = OldVar->isDirectInit();
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00003676 AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003677 } else
3678 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3679 } else {
3680 // FIXME: Not too happy about invalidating the declaration
3681 // because of a bogus initializer.
3682 Var->setInvalidDecl();
3683 }
3684
3685 PopExpressionEvaluationContext();
3686 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3687 !Var->isCXXForRangeDecl())
3688 ActOnUninitializedDecl(Var, false);
3689}
3690
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003691/// \brief Instantiate the definition of the given variable from its
3692/// template.
3693///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003694/// \param PointOfInstantiation the point at which the instantiation was
3695/// required. Note that this is not precisely a "point of instantiation"
3696/// for the function, but it's close.
3697///
3698/// \param Var the already-instantiated declaration of a static member
3699/// variable of a class template specialization.
3700///
3701/// \param Recursive if true, recursively instantiates any functions that
3702/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003703///
3704/// \param DefinitionRequired if true, then we are performing an explicit
3705/// instantiation where an out-of-line definition of the member variable
3706/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003707void Sema::InstantiateStaticDataMemberDefinition(
3708 SourceLocation PointOfInstantiation,
3709 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003710 bool Recursive,
3711 bool DefinitionRequired) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003712 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3713 DefinitionRequired);
3714}
3715
3716void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3717 VarDecl *Var, bool Recursive,
3718 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003719 if (Var->isInvalidDecl())
3720 return;
Mike Stump11289f42009-09-09 15:08:12 +00003721
Larisse Voufo39a1e502013-08-06 01:03:05 +00003722 VarTemplateSpecializationDecl *VarSpec =
3723 dyn_cast<VarTemplateSpecializationDecl>(Var);
Craig Topperc3ec1492014-05-26 06:22:03 +00003724 VarDecl *PatternDecl = nullptr, *Def = nullptr;
Richard Smith8809a0c2013-09-27 20:14:12 +00003725 MultiLevelTemplateArgumentList TemplateArgs =
3726 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00003727
Larisse Voufo39a1e502013-08-06 01:03:05 +00003728 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003729 // If this is a variable template specialization, make sure that it is
3730 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003731 bool InstantiationDependent = false;
3732 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3733 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3734 "Only instantiate variable template specializations that are "
3735 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00003736 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003737
Richard Smith8809a0c2013-09-27 20:14:12 +00003738 // Find the variable initialization that we'll be substituting. If the
3739 // pattern was instantiated from a member template, look back further to
3740 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003741 assert(VarSpec->getSpecializedTemplate() &&
3742 "Specialization without specialized template?");
3743 llvm::PointerUnion<VarTemplateDecl *,
3744 VarTemplatePartialSpecializationDecl *> PatternPtr =
3745 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003746 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003747 VarTemplatePartialSpecializationDecl *Tmpl =
3748 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3749 while (VarTemplatePartialSpecializationDecl *From =
3750 Tmpl->getInstantiatedFromMember()) {
3751 if (Tmpl->isMemberSpecialization())
3752 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003753
Richard Smith8809a0c2013-09-27 20:14:12 +00003754 Tmpl = From;
3755 }
3756 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003757 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00003758 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3759 while (VarTemplateDecl *From =
3760 Tmpl->getInstantiatedFromMemberTemplate()) {
3761 if (Tmpl->isMemberSpecialization())
3762 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003763
Richard Smith8809a0c2013-09-27 20:14:12 +00003764 Tmpl = From;
3765 }
3766 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003767 }
Richard Smith8809a0c2013-09-27 20:14:12 +00003768
3769 // If this is a static data member template, there might be an
3770 // uninstantiated initializer on the declaration. If so, instantiate
3771 // it now.
3772 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00003773 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00003774 !Var->hasInit()) {
3775 // FIXME: Factor out the duplicated instantiation context setup/tear down
3776 // code here.
3777 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003778 if (Inst.isInvalid())
Richard Smith8809a0c2013-09-27 20:14:12 +00003779 return;
3780
3781 // If we're performing recursive template instantiation, create our own
3782 // queue of pending implicit instantiations that we will instantiate
3783 // later, while we're still within our own instantiation context.
Nico Weber7a92e1a2015-01-18 01:50:35 +00003784 SavePendingInstantiationsAndVTableUsesRAII
3785 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
Richard Smith8809a0c2013-09-27 20:14:12 +00003786
3787 LocalInstantiationScope Local(*this);
3788
3789 // Enter the scope of this instantiation. We don't use
3790 // PushDeclContext because we don't have a scope.
3791 ContextRAII PreviousContext(*this, Var->getDeclContext());
3792 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3793 PreviousContext.pop();
3794
3795 // FIXME: Need to inform the ASTConsumer that we instantiated the
3796 // initializer?
3797
3798 // This variable may have local implicit instantiations that need to be
3799 // instantiated within this scope.
3800 PerformPendingInstantiations(/*LocalOnly=*/true);
3801
3802 Local.Exit();
3803
3804 if (Recursive) {
3805 // Define any newly required vtables.
3806 DefineUsedVTables();
3807
3808 // Instantiate any pending implicit instantiations found during the
3809 // instantiation of this template.
3810 PerformPendingInstantiations();
3811
Nico Weber7a92e1a2015-01-18 01:50:35 +00003812 // PendingInstantiations and VTableUses are restored through
3813 // SavePendingInstantiationsAndVTableUses's destructor.
Richard Smith8809a0c2013-09-27 20:14:12 +00003814 }
3815 }
3816
3817 // Find actual definition
3818 Def = PatternDecl->getDefinition(getASTContext());
3819 } else {
3820 // If this is a static data member, find its out-of-line definition.
3821 assert(Var->isStaticDataMember() && "not a static data member?");
3822 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3823
3824 assert(PatternDecl && "data member was not instantiated from a template?");
3825 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3826 Def = PatternDecl->getOutOfLineDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003827 }
3828
Richard Smith8809a0c2013-09-27 20:14:12 +00003829 // If we don't have a definition of the variable template, we won't perform
3830 // any instantiation. Rather, we rely on the user to instantiate this
3831 // definition (or provide a specialization for it) in another translation
3832 // unit.
3833 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003834 if (DefinitionRequired) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003835 if (VarSpec)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003836 Diag(PointOfInstantiation,
Richard Smith8809a0c2013-09-27 20:14:12 +00003837 diag::err_explicit_instantiation_undefined_var_template) << Var;
3838 else
Larisse Voufo39a1e502013-08-06 01:03:05 +00003839 Diag(PointOfInstantiation,
3840 diag::err_explicit_instantiation_undefined_member)
Richard Smith8809a0c2013-09-27 20:14:12 +00003841 << 2 << Var->getDeclName() << Var->getDeclContext();
3842 Diag(PatternDecl->getLocation(),
3843 diag::note_explicit_instantiation_here);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003844 if (VarSpec)
3845 Var->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003846 } else if (Var->getTemplateSpecializationKind()
3847 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003848 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003849 std::make_pair(Var, PointOfInstantiation));
3850 }
3851
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003852 return;
3853 }
3854
Rafael Espindola189fa742012-03-05 10:54:55 +00003855 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3856
Douglas Gregor86d142a2009-10-08 07:24:58 +00003857 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00003858 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003859 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003860
Larisse Voufo39a1e502013-08-06 01:03:05 +00003861 // C++11 [temp.explicit]p10:
3862 // Except for inline functions, [...] explicit instantiation declarations
3863 // have the effect of suppressing the implicit instantiation of the entity
3864 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00003865 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003866 return;
Mike Stump11289f42009-09-09 15:08:12 +00003867
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003868 // Make sure to pass the instantiated variable to the consumer at the end.
3869 struct PassToConsumerRAII {
3870 ASTConsumer &Consumer;
3871 VarDecl *Var;
3872
3873 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3874 : Consumer(Consumer), Var(Var) { }
3875
3876 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00003877 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003878 }
3879 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003880
Reid Klecknere07140e2015-04-15 01:08:06 +00003881 // If we already have a definition, we're done.
3882 if (VarDecl *Def = Var->getDefinition()) {
3883 // We may be explicitly instantiating something we've already implicitly
3884 // instantiated.
3885 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3886 PointOfInstantiation);
Richard Smith8809a0c2013-09-27 20:14:12 +00003887 return;
Reid Klecknere07140e2015-04-15 01:08:06 +00003888 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00003889
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003890 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003891 if (Inst.isInvalid())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003892 return;
Mike Stump11289f42009-09-09 15:08:12 +00003893
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003894 // If we're performing recursive template instantiation, create our own
3895 // queue of pending implicit instantiations that we will instantiate later,
3896 // while we're still within our own instantiation context.
David Majnemerfd6c685f2013-11-27 22:57:44 +00003897 SavePendingLocalImplicitInstantiationsRAII
3898 SavedPendingLocalImplicitInstantiations(*this);
Nico Weber7a92e1a2015-01-18 01:50:35 +00003899 SavePendingInstantiationsAndVTableUsesRAII
3900 SavePendingInstantiationsAndVTableUses(*this, /*Enabled=*/Recursive);
Mike Stump11289f42009-09-09 15:08:12 +00003901
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003902 // Enter the scope of this instantiation. We don't use
3903 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003904 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00003905 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00003906
Larisse Voufo39a1e502013-08-06 01:03:05 +00003907 VarDecl *OldVar = Var;
3908 if (!VarSpec)
3909 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00003910 TemplateArgs));
3911 else if (Var->isStaticDataMember() &&
3912 Var->getLexicalDeclContext()->isRecord()) {
3913 // We need to instantiate the definition of a static data member template,
3914 // and all we have is the in-class declaration of it. Instantiate a separate
3915 // declaration of the definition.
3916 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3917 TemplateArgs);
3918 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
Craig Topperc3ec1492014-05-26 06:22:03 +00003919 VarSpec->getSpecializedTemplate(), Def, nullptr,
Richard Smith8809a0c2013-09-27 20:14:12 +00003920 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3921 if (Var) {
3922 llvm::PointerUnion<VarTemplateDecl *,
3923 VarTemplatePartialSpecializationDecl *> PatternPtr =
3924 VarSpec->getSpecializedTemplateOrPartial();
3925 if (VarTemplatePartialSpecializationDecl *Partial =
3926 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3927 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3928 Partial, &VarSpec->getTemplateInstantiationArgs());
3929
3930 // Merge the definition with the declaration.
3931 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3932 LookupOrdinaryName, ForRedeclaration);
3933 R.addDecl(OldVar);
3934 MergeVarDecl(Var, R);
3935
3936 // Attach the initializer.
3937 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3938 }
3939 } else
3940 // Complete the existing variable's definition with an appropriately
3941 // substituted type and initializer.
3942 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003943
3944 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003945
3946 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003947 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00003948 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3949 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003950 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003951
3952 // This variable may have local implicit instantiations that need to be
3953 // instantiated within this scope.
3954 PerformPendingInstantiations(/*LocalOnly=*/true);
3955
Douglas Gregora86bc002012-02-16 21:36:18 +00003956 Local.Exit();
3957
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003958 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003959 // Define any newly required vtables.
3960 DefineUsedVTables();
3961
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003962 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003963 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003964 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003965
Nico Weber7a92e1a2015-01-18 01:50:35 +00003966 // PendingInstantiations and VTableUses are restored through
3967 // SavePendingInstantiationsAndVTableUses's destructor.
Mike Stump11289f42009-09-09 15:08:12 +00003968 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003969}
Douglas Gregor51783312009-05-27 05:35:12 +00003970
Anders Carlsson70553942009-08-29 05:16:22 +00003971void
3972Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3973 const CXXConstructorDecl *Tmpl,
3974 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003975
Richard Trieu9becef62011-09-09 03:18:59 +00003976 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00003977 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003978
Anders Carlsson70553942009-08-29 05:16:22 +00003979 // Instantiate all the initializers.
Aaron Ballman0ad78302014-03-13 17:34:31 +00003980 for (const auto *Init : Tmpl->inits()) {
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00003981 // Only instantiate written initializers, let Sema re-construct implicit
3982 // ones.
3983 if (!Init->isWritten())
3984 continue;
3985
Douglas Gregor44e7df62011-01-04 00:32:56 +00003986 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003987
Douglas Gregor44e7df62011-01-04 00:32:56 +00003988 if (Init->isPackExpansion()) {
3989 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003990 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00003991 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003992 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00003993 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003994 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003995 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00003996 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003997 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003998 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00003999 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004000 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004001 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004002 NumExpansions)) {
4003 AnyErrors = true;
4004 New->setInvalidDecl();
4005 continue;
4006 }
4007 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004008
4009 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004010 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004011 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4012
4013 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004014 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4015 /*CXXDirectInit=*/true);
4016 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004017 AnyErrors = true;
4018 break;
4019 }
4020
4021 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004022 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004023 TemplateArgs,
4024 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004025 New->getDeclName());
4026 if (!BaseTInfo) {
4027 AnyErrors = true;
4028 break;
4029 }
4030
4031 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004032 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004033 BaseTInfo, TempInit.get(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004034 New->getParent(),
4035 SourceLocation());
4036 if (NewInit.isInvalid()) {
4037 AnyErrors = true;
4038 break;
4039 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004040
Douglas Gregor44e7df62011-01-04 00:32:56 +00004041 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004042 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004043
Douglas Gregor44e7df62011-01-04 00:32:56 +00004044 continue;
4045 }
4046
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004047 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004048 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4049 /*CXXDirectInit=*/true);
4050 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004051 AnyErrors = true;
4052 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004053 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004054
Anders Carlsson70553942009-08-29 05:16:22 +00004055 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004056 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4057 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4058 TemplateArgs,
4059 Init->getSourceLocation(),
4060 New->getDeclName());
4061 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004062 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004063 New->setInvalidDecl();
4064 continue;
4065 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004066
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004067 if (Init->isBaseInitializer())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004068 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004069 New->getParent(), EllipsisLoc);
4070 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004071 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004072 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004073 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004074 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004075 Init->getMemberLocation(),
4076 Init->getMember(),
4077 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004078 if (!Member) {
4079 AnyErrors = true;
4080 New->setInvalidDecl();
4081 continue;
4082 }
Mike Stump11289f42009-09-09 15:08:12 +00004083
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004084 NewInit = BuildMemberInitializer(Member, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004085 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004086 } else if (Init->isIndirectMemberInitializer()) {
4087 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004088 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004089 Init->getMemberLocation(),
4090 Init->getIndirectMember(), TemplateArgs));
4091
Douglas Gregor55e6b312011-03-04 19:46:35 +00004092 if (!IndirectMember) {
4093 AnyErrors = true;
4094 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004095 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004096 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004097
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004098 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004099 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004100 }
4101
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004102 if (NewInit.isInvalid()) {
4103 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004104 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004105 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004106 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004107 }
4108 }
Mike Stump11289f42009-09-09 15:08:12 +00004109
Anders Carlsson70553942009-08-29 05:16:22 +00004110 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004111 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004112 /*FIXME: ColonLoc */
4113 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004114 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004115 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004116}
4117
John McCall59660882009-08-29 08:11:13 +00004118// TODO: this could be templated if the various decl types used the
4119// same method name.
4120static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4121 ClassTemplateDecl *Instance) {
4122 Pattern = Pattern->getCanonicalDecl();
4123
4124 do {
4125 Instance = Instance->getCanonicalDecl();
4126 if (Pattern == Instance) return true;
4127 Instance = Instance->getInstantiatedFromMemberTemplate();
4128 } while (Instance);
4129
4130 return false;
4131}
4132
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004133static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4134 FunctionTemplateDecl *Instance) {
4135 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004136
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004137 do {
4138 Instance = Instance->getCanonicalDecl();
4139 if (Pattern == Instance) return true;
4140 Instance = Instance->getInstantiatedFromMemberTemplate();
4141 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004142
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004143 return false;
4144}
4145
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004146static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004147isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4148 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004149 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004150 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4151 do {
4152 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4153 Instance->getCanonicalDecl());
4154 if (Pattern == Instance)
4155 return true;
4156 Instance = Instance->getInstantiatedFromMember();
4157 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004158
Douglas Gregor21610382009-10-29 00:04:11 +00004159 return false;
4160}
4161
John McCall59660882009-08-29 08:11:13 +00004162static bool isInstantiationOf(CXXRecordDecl *Pattern,
4163 CXXRecordDecl *Instance) {
4164 Pattern = Pattern->getCanonicalDecl();
4165
4166 do {
4167 Instance = Instance->getCanonicalDecl();
4168 if (Pattern == Instance) return true;
4169 Instance = Instance->getInstantiatedFromMemberClass();
4170 } while (Instance);
4171
4172 return false;
4173}
4174
4175static bool isInstantiationOf(FunctionDecl *Pattern,
4176 FunctionDecl *Instance) {
4177 Pattern = Pattern->getCanonicalDecl();
4178
4179 do {
4180 Instance = Instance->getCanonicalDecl();
4181 if (Pattern == Instance) return true;
4182 Instance = Instance->getInstantiatedFromMemberFunction();
4183 } while (Instance);
4184
4185 return false;
4186}
4187
4188static bool isInstantiationOf(EnumDecl *Pattern,
4189 EnumDecl *Instance) {
4190 Pattern = Pattern->getCanonicalDecl();
4191
4192 do {
4193 Instance = Instance->getCanonicalDecl();
4194 if (Pattern == Instance) return true;
4195 Instance = Instance->getInstantiatedFromMemberEnum();
4196 } while (Instance);
4197
4198 return false;
4199}
4200
John McCallb96ec562009-12-04 22:46:56 +00004201static bool isInstantiationOf(UsingShadowDecl *Pattern,
4202 UsingShadowDecl *Instance,
4203 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00004204 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4205 Pattern);
John McCallb96ec562009-12-04 22:46:56 +00004206}
4207
4208static bool isInstantiationOf(UsingDecl *Pattern,
4209 UsingDecl *Instance,
4210 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00004211 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
John McCallb96ec562009-12-04 22:46:56 +00004212}
4213
John McCalle61f2ba2009-11-18 02:36:19 +00004214static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4215 UsingDecl *Instance,
4216 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00004217 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
John McCalle61f2ba2009-11-18 02:36:19 +00004218}
4219
4220static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004221 UsingDecl *Instance,
4222 ASTContext &C) {
Richard Smith32952e12014-10-14 02:00:47 +00004223 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004224}
4225
John McCall59660882009-08-29 08:11:13 +00004226static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4227 VarDecl *Instance) {
4228 assert(Instance->isStaticDataMember());
4229
4230 Pattern = Pattern->getCanonicalDecl();
4231
4232 do {
4233 Instance = Instance->getCanonicalDecl();
4234 if (Pattern == Instance) return true;
4235 Instance = Instance->getInstantiatedFromStaticDataMember();
4236 } while (Instance);
4237
4238 return false;
4239}
4240
John McCallb96ec562009-12-04 22:46:56 +00004241// Other is the prospective instantiation
4242// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004243static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004244 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004245 if (UnresolvedUsingTypenameDecl *UUD
4246 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4247 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4248 return isInstantiationOf(UUD, UD, Ctx);
4249 }
4250 }
4251
4252 if (UnresolvedUsingValueDecl *UUD
4253 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004254 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4255 return isInstantiationOf(UUD, UD, Ctx);
4256 }
4257 }
Douglas Gregor51783312009-05-27 05:35:12 +00004258
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004259 return false;
4260 }
Mike Stump11289f42009-09-09 15:08:12 +00004261
John McCall59660882009-08-29 08:11:13 +00004262 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4263 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004264
John McCall59660882009-08-29 08:11:13 +00004265 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4266 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004267
John McCall59660882009-08-29 08:11:13 +00004268 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4269 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004270
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004271 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004272 if (Var->isStaticDataMember())
4273 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4274
4275 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4276 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004277
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004278 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4279 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4280
Douglas Gregor21610382009-10-29 00:04:11 +00004281 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4282 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4283 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4284 PartialSpec);
4285
Anders Carlsson5da84842009-09-01 04:26:58 +00004286 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4287 if (!Field->getDeclName()) {
4288 // This is an unnamed field.
Richard Smith32952e12014-10-14 02:00:47 +00004289 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4290 cast<FieldDecl>(D));
Anders Carlsson5da84842009-09-01 04:26:58 +00004291 }
4292 }
Mike Stump11289f42009-09-09 15:08:12 +00004293
John McCallb96ec562009-12-04 22:46:56 +00004294 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4295 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4296
4297 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4298 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4299
Douglas Gregor51783312009-05-27 05:35:12 +00004300 return D->getDeclName() && isa<NamedDecl>(Other) &&
4301 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4302}
4303
4304template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004305static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004306 NamedDecl *D,
4307 ForwardIterator first,
4308 ForwardIterator last) {
4309 for (; first != last; ++first)
4310 if (isInstantiationOf(Ctx, D, *first))
4311 return cast<NamedDecl>(*first);
4312
Craig Topperc3ec1492014-05-26 06:22:03 +00004313 return nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00004314}
4315
John McCallaa74a0c2009-08-28 07:59:38 +00004316/// \brief Finds the instantiation of the given declaration context
4317/// within the current instantiation.
4318///
4319/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004320DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004321 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004322 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004323 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00004324 return cast_or_null<DeclContext>(ID);
4325 } else return DC;
4326}
4327
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004328/// \brief Find the instantiation of the given declaration within the
4329/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004330///
4331/// This routine is intended to be used when \p D is a declaration
4332/// referenced from within a template, that needs to mapped into the
4333/// corresponding declaration within an instantiation. For example,
4334/// given:
4335///
4336/// \code
4337/// template<typename T>
4338/// struct X {
4339/// enum Kind {
4340/// KnownValue = sizeof(T)
4341/// };
4342///
4343/// bool getKind() const { return KnownValue; }
4344/// };
4345///
4346/// template struct X<int>;
4347/// \endcode
4348///
Serge Pavloved5fe902013-07-10 04:59:14 +00004349/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4350/// \p EnumConstantDecl for \p KnownValue (which refers to
4351/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4352/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4353/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004354NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00004355 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00004356 DeclContext *ParentDC = D->getDeclContext();
Faisal Vali2cba1332013-10-23 06:44:28 +00004357 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4358 // parameters (p below) can have their ParentDC set to the translation-unit
4359 // - thus we can not consistently check if the ParentDC of such a parameter
4360 // is Dependent or/and a FunctionOrMethod.
4361 // For e.g. this code, during Template argument deduction tries to
4362 // find an instantiated decl for (T y) when the ParentDC for y is
4363 // the translation unit.
4364 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00004365 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00004366 // Foo(baz);
4367 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4368 // it gets here, always has a FunctionOrMethod as its ParentDC??
4369 // For now:
4370 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4371 // whose type is not instantiation dependent, do nothing to the decl
4372 // - otherwise find its instantiated decl.
4373 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4374 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4375 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00004376 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00004377 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00004378 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4379 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004380 // D is a local of some kind. Look into the map of local
4381 // declarations to their instantiations.
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00004382 if (CurrentInstantiationScope) {
4383 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4384 if (Decl *FD = Found->dyn_cast<Decl *>())
4385 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004386
Alexey Samsonov2c0aac22014-09-03 18:45:45 +00004387 int PackIdx = ArgumentPackSubstitutionIndex;
4388 assert(PackIdx != -1 &&
4389 "found declaration pack but not pack expanding");
4390 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4391 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4392 }
Chris Lattnercab02a62011-02-17 20:34:02 +00004393 }
4394
Serge Pavlov7cd8f602013-07-15 06:14:07 +00004395 // If we're performing a partial substitution during template argument
4396 // deduction, we may not have values for template parameters yet. They
4397 // just map to themselves.
4398 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4399 isa<TemplateTemplateParmDecl>(D))
4400 return D;
4401
Serge Pavlov074a5182013-08-10 12:00:21 +00004402 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00004403 return nullptr;
Serge Pavlov074a5182013-08-10 12:00:21 +00004404
Chris Lattnercab02a62011-02-17 20:34:02 +00004405 // If we didn't find the decl, then we must have a label decl that hasn't
4406 // been found yet. Lazily instantiate it and return it now.
4407 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004408
Chris Lattnercab02a62011-02-17 20:34:02 +00004409 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4410 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004411
Chris Lattnercab02a62011-02-17 20:34:02 +00004412 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4413 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004414 }
Douglas Gregor51783312009-05-27 05:35:12 +00004415
Larisse Voufo39a1e502013-08-06 01:03:05 +00004416 // For variable template specializations, update those that are still
4417 // type-dependent.
4418 if (VarTemplateSpecializationDecl *VarSpec =
4419 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4420 bool InstantiationDependent = false;
4421 const TemplateArgumentListInfo &VarTemplateArgs =
4422 VarSpec->getTemplateArgsInfo();
4423 if (TemplateSpecializationType::anyDependentTemplateArguments(
4424 VarTemplateArgs, InstantiationDependent))
4425 D = cast<NamedDecl>(
4426 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4427 return D;
4428 }
4429
Douglas Gregor64621e62009-09-16 18:34:49 +00004430 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4431 if (!Record->isDependentContext())
4432 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004433
Douglas Gregor4109afa2011-11-07 17:43:18 +00004434 // Determine whether this record is the "templated" declaration describing
4435 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00004436 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00004437 if (ClassTemplate)
4438 ClassTemplate = ClassTemplate->getCanonicalDecl();
4439 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4440 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4441 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004442
Douglas Gregor4109afa2011-11-07 17:43:18 +00004443 // Walk the current context to find either the record or an instantiation of
4444 // it.
4445 DeclContext *DC = CurContext;
4446 while (!DC->isFileContext()) {
4447 // If we're performing substitution while we're inside the template
4448 // definition, we'll find our own context. We're done.
4449 if (DC->Equals(Record))
4450 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004451
Douglas Gregor4109afa2011-11-07 17:43:18 +00004452 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4453 // Check whether we're in the process of instantiating a class template
4454 // specialization of the template we're mapping.
4455 if (ClassTemplateSpecializationDecl *InstSpec
4456 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4457 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4458 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4459 return InstRecord;
4460 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004461
Douglas Gregor4109afa2011-11-07 17:43:18 +00004462 // Check whether we're in the process of instantiating a member class.
4463 if (isInstantiationOf(Record, InstRecord))
4464 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00004465 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004466
Douglas Gregor4109afa2011-11-07 17:43:18 +00004467 // Move to the outer template scope.
4468 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4469 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4470 DC = FD->getLexicalDeclContext();
4471 continue;
4472 }
John McCall59660882009-08-29 08:11:13 +00004473 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004474
Douglas Gregor4109afa2011-11-07 17:43:18 +00004475 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00004476 }
Douglas Gregord225fa02010-02-05 22:40:03 +00004477
Douglas Gregor64621e62009-09-16 18:34:49 +00004478 // Fall through to deal with other dependent record types (e.g.,
4479 // anonymous unions in class templates).
4480 }
John McCall59660882009-08-29 08:11:13 +00004481
Douglas Gregor64621e62009-09-16 18:34:49 +00004482 if (!ParentDC->isDependentContext())
4483 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004484
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004485 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004486 if (!ParentDC)
Craig Topperc3ec1492014-05-26 06:22:03 +00004487 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004488
Douglas Gregor51783312009-05-27 05:35:12 +00004489 if (ParentDC != D->getDeclContext()) {
4490 // We performed some kind of instantiation in the parent context,
4491 // so now we need to look into the instantiated parent context to
4492 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004493
John McCalle78aac42010-03-10 03:28:59 +00004494 // If our context used to be dependent, we may need to instantiate
4495 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00004496 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00004497 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004498 if (!Spec->isDependentContext()) {
4499 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00004500 const RecordType *Tag = T->getAs<RecordType>();
4501 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00004502 if (Tag->isBeingDefined())
4503 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00004504 if (!Tag->isBeingDefined() &&
4505 RequireCompleteType(Loc, T, diag::err_incomplete_type))
Craig Topperc3ec1492014-05-26 06:22:03 +00004506 return nullptr;
Douglas Gregor25edf432010-11-05 23:22:45 +00004507
4508 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004509 }
4510 }
4511
Craig Topperc3ec1492014-05-26 06:22:03 +00004512 NamedDecl *Result = nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00004513 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004514 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00004515 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00004516 } else {
4517 // Since we don't have a name for the entity we're looking for,
4518 // our only option is to walk through all of the declarations to
4519 // find that name. This will occur in a few cases:
4520 //
4521 // - anonymous struct/union within a template
4522 // - unnamed class/struct/union/enum within a template
4523 //
4524 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00004525 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004526 ParentDC->decls_begin(),
4527 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00004528 }
Mike Stump11289f42009-09-09 15:08:12 +00004529
Douglas Gregor528ad932011-03-06 20:12:45 +00004530 if (!Result) {
4531 if (isa<UsingShadowDecl>(D)) {
4532 // UsingShadowDecls can instantiate to nothing because of using hiding.
4533 } else if (Diags.hasErrorOccurred()) {
4534 // We've already complained about something, so most likely this
4535 // declaration failed to instantiate. There's no point in complaining
4536 // further, since this is normal in invalid code.
4537 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004538 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00004539 // instantiated, and we haven't gotten around to instantiating this
4540 // member yet. This can happen when the code uses forward declarations
4541 // of member classes, and introduces ordering dependencies via
4542 // template instantiation.
4543 Diag(Loc, diag::err_member_not_yet_instantiated)
4544 << D->getDeclName()
4545 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4546 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00004547 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4548 // This enumeration constant was found when the template was defined,
4549 // but can't be found in the instantiation. This can happen if an
4550 // unscoped enumeration member is explicitly specialized.
4551 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4552 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4553 TemplateArgs));
4554 assert(Spec->getTemplateSpecializationKind() ==
4555 TSK_ExplicitSpecialization);
4556 Diag(Loc, diag::err_enumerator_does_not_exist)
4557 << D->getDeclName()
4558 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4559 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4560 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00004561 } else {
4562 // We should have found something, but didn't.
4563 llvm_unreachable("Unable to find instantiation of declaration!");
4564 }
4565 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004566
Douglas Gregor51783312009-05-27 05:35:12 +00004567 D = Result;
4568 }
4569
Douglas Gregor51783312009-05-27 05:35:12 +00004570 return D;
4571}
Douglas Gregor77b50e12009-06-22 23:06:13 +00004572
Mike Stump11289f42009-09-09 15:08:12 +00004573/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00004574/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00004575void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004576 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00004577 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004578 PendingImplicitInstantiation Inst;
4579
4580 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00004581 Inst = PendingInstantiations.front();
4582 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004583 } else {
4584 Inst = PendingLocalImplicitInstantiations.front();
4585 PendingLocalImplicitInstantiations.pop_front();
4586 }
Mike Stump11289f42009-09-09 15:08:12 +00004587
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004588 // Instantiate function definitions
4589 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallfaf5fb42010-08-26 23:41:50 +00004590 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4591 "instantiating function definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004592 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4593 TSK_ExplicitInstantiationDefinition;
4594 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4595 DefinitionRequired);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004596 continue;
4597 }
Mike Stump11289f42009-09-09 15:08:12 +00004598
Larisse Voufo39a1e502013-08-06 01:03:05 +00004599 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004600 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004601
4602 assert((Var->isStaticDataMember() ||
4603 isa<VarTemplateSpecializationDecl>(Var)) &&
4604 "Not a static data member, nor a variable template"
4605 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00004606
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004607 // Don't try to instantiate declarations if the most recent redeclaration
4608 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004609 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004610 continue;
4611
4612 // Check if the most recent declaration has changed the specialization kind
4613 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004614 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004615 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00004616 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004617 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004618 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004619 continue; // No longer need to instantiate this type.
4620 case TSK_ExplicitInstantiationDefinition:
4621 // We only need an instantiation if the pending instantiation *is* the
4622 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004623 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004624 case TSK_ImplicitInstantiation:
4625 break;
4626 }
4627
Larisse Voufo39a1e502013-08-06 01:03:05 +00004628 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4629 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004630 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4631 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004632
4633 // Instantiate static data member definitions or variable template
4634 // specializations.
4635 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4636 DefinitionRequired);
Douglas Gregor77b50e12009-06-22 23:06:13 +00004637 }
4638}
John McCallc62bb642010-03-24 05:22:00 +00004639
4640void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4641 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00004642 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00004643 switch (DD->getKind()) {
4644 case DependentDiagnostic::Access:
4645 HandleDependentAccessCheck(*DD, TemplateArgs);
4646 break;
4647 }
4648 }
4649}