blob: 60ec5bbad936a85c858f30a8768a72e306cbf66f [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
John McCall3e11ebe2010-03-15 10:12:16 +000039bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
40 DeclaratorDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000041 if (!OldDecl->getQualifierLoc())
42 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000043
Douglas Gregor14454802011-02-25 02:25:35 +000044 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000045 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000046 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000047
Douglas Gregor14454802011-02-25 02:25:35 +000048 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000049 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000050
Douglas Gregor14454802011-02-25 02:25:35 +000051 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000052 return false;
53}
54
55bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
56 TagDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000057 if (!OldDecl->getQualifierLoc())
58 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000059
Douglas Gregor14454802011-02-25 02:25:35 +000060 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000061 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000062 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000063
Douglas Gregor14454802011-02-25 02:25:35 +000064 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000065 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000066
Douglas Gregor14454802011-02-25 02:25:35 +000067 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000068 return false;
69}
70
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000071// Include attribute instantiation code.
72#include "clang/Sema/AttrTemplateInstantiate.inc"
73
Richard Smith44c247f2013-02-22 08:32:16 +000074static void instantiateDependentAlignedAttr(
75 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
76 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
77 if (Aligned->isAlignmentExpr()) {
78 // The alignment expression is a constant expression.
79 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
80 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
81 if (!Result.isInvalid())
82 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
83 Aligned->getSpellingListIndex(), IsPackExpansion);
84 } else {
85 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
86 TemplateArgs, Aligned->getLocation(),
87 DeclarationName());
88 if (Result)
89 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
90 Aligned->getSpellingListIndex(), IsPackExpansion);
91 }
92}
93
94static void instantiateDependentAlignedAttr(
95 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
96 const AlignedAttr *Aligned, Decl *New) {
97 if (!Aligned->isPackExpansion()) {
98 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
99 return;
100 }
101
102 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
103 if (Aligned->isAlignmentExpr())
104 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
105 Unexpanded);
106 else
107 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
108 Unexpanded);
109 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
110
111 // Determine whether we can expand this attribute pack yet.
112 bool Expand = true, RetainExpansion = false;
113 Optional<unsigned> NumExpansions;
114 // FIXME: Use the actual location of the ellipsis.
115 SourceLocation EllipsisLoc = Aligned->getLocation();
116 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
117 Unexpanded, TemplateArgs, Expand,
118 RetainExpansion, NumExpansions))
119 return;
120
121 if (!Expand) {
122 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
123 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
124 } else {
125 for (unsigned I = 0; I != *NumExpansions; ++I) {
126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
128 }
129 }
130}
131
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000132static void instantiateDependentEnableIfAttr(
133 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
134 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000135 Expr *Cond = nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000136 {
137 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
138 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
139 if (Result.isInvalid())
140 return;
141 Cond = Result.takeAs<Expr>();
142 }
143 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
144 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
145 if (Converted.isInvalid())
146 return;
147 Cond = Converted.take();
148 }
149
150 SmallVector<PartialDiagnosticAt, 8> Diags;
151 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
152 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
153 Diags)) {
154 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
155 for (int I = 0, N = Diags.size(); I != N; ++I)
156 S.Diag(Diags[I].first, Diags[I].second);
157 return;
158 }
159
Aaron Ballman36a53502014-01-16 13:03:14 +0000160 EnableIfAttr *EIA = new (S.getASTContext())
161 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
162 A->getMessage(),
163 A->getSpellingListIndex());
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000164 New->addAttr(EIA);
165}
166
John McCall6602bb12010-08-01 02:01:53 +0000167void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000168 const Decl *Tmpl, Decl *New,
169 LateInstantiatedAttrVec *LateAttrs,
170 LocalInstantiationScope *OuterMostScope) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000171 for (const auto *TmplAttr : Tmpl->attrs()) {
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000172 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000173 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
174 if (Aligned && Aligned->isAlignmentDependent()) {
175 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
176 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000177 }
178
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000179 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
180 if (EnableIf && EnableIf->getCond()->isValueDependent()) {
181 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
182 New);
183 continue;
184 }
185
Richard Smith44c247f2013-02-22 08:32:16 +0000186 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000187 if (TmplAttr->isLateParsed() && LateAttrs) {
188 // Late parsed attributes must be instantiated and attached after the
189 // enclosing class has been instantiated. See Sema::InstantiateClass.
Craig Topperc3ec1492014-05-26 06:22:03 +0000190 LocalInstantiationScope *Saved = nullptr;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000191 if (CurrentInstantiationScope)
192 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
193 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
194 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000195 // Allow 'this' within late-parsed attributes.
196 NamedDecl *ND = dyn_cast<NamedDecl>(New);
197 CXXRecordDecl *ThisContext =
198 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
199 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
200 ND && ND->isCXXInstanceMember());
201
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000202 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
203 *this, TemplateArgs);
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000204 if (NewAttr)
205 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000206 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000207 }
208}
209
Douglas Gregor8a655532009-03-25 15:45:12 +0000210Decl *
211TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000212 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000213}
214
215Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000216TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
217 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
218 D->getIdentifier());
219 Owner->addDecl(Inst);
220 return Inst;
221}
222
223Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000224TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000225 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000226}
227
John McCalld8d0d432010-02-16 06:53:13 +0000228Decl *
229TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
230 NamespaceAliasDecl *Inst
231 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
232 D->getNamespaceLoc(),
233 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000234 D->getIdentifier(),
235 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000236 D->getTargetNameLoc(),
237 D->getNamespace());
238 Owner->addDecl(Inst);
239 return Inst;
240}
241
Richard Smith3f1b5d02011-05-05 21:57:07 +0000242Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
243 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000244 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000245 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000246 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000247 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000248 DI = SemaRef.SubstType(DI, TemplateArgs,
249 D->getLocation(), D->getDeclName());
250 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000251 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000252 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000253 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000254 } else {
255 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000256 }
Mike Stump11289f42009-09-09 15:08:12 +0000257
Richard Smith2ddcbab2012-10-23 00:32:41 +0000258 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
259 // libstdc++ relies upon this bug in its implementation of common_type.
260 // If we happen to be processing that implementation, fake up the g++ ?:
261 // semantics. See LWG issue 2141 for more information on the bug.
262 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
263 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
264 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
265 DT->isReferenceType() &&
266 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
267 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
268 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
269 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
270 // Fold it to the (non-reference) type which g++ would have produced.
271 DI = SemaRef.Context.getTrivialTypeSourceInfo(
272 DI->getType().getNonReferenceType());
273
Douglas Gregord7e7a512009-03-17 21:15:40 +0000274 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000275 TypedefNameDecl *Typedef;
276 if (IsTypeAlias)
277 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
278 D->getLocation(), D->getIdentifier(), DI);
279 else
280 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
281 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000282 if (Invalid)
283 Typedef->setInvalidDecl();
284
John McCall04fcd0d2011-02-01 08:20:08 +0000285 // If the old typedef was the name for linkage purposes of an anonymous
286 // tag decl, re-establish that relationship for the new typedef.
287 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
288 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000289 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000290 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000291 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000292 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000293 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000294 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000295
Douglas Gregorec9fd132012-01-14 16:38:05 +0000296 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000297 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
298 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000299 if (!InstPrev)
Craig Topperc3ec1492014-05-26 06:22:03 +0000300 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000301
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000302 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
303
304 // If the typedef types are not identical, reject them.
305 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
306
Rafael Espindola8db352d2013-10-17 15:37:26 +0000307 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000308 }
309
John McCall6602bb12010-08-01 02:01:53 +0000310 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000311
John McCall401982f2010-01-20 21:53:11 +0000312 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000313
Douglas Gregord7e7a512009-03-17 21:15:40 +0000314 return Typedef;
315}
316
Richard Smithdda56e42011-04-15 14:24:37 +0000317Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000318 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
319 Owner->addDecl(Typedef);
320 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000321}
322
323Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000324 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
325 Owner->addDecl(Typedef);
326 return Typedef;
327}
328
329Decl *
330TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
331 // Create a local instantiation scope for this type alias template, which
332 // will contain the instantiations of the template parameters.
333 LocalInstantiationScope Scope(SemaRef);
334
335 TemplateParameterList *TempParams = D->getTemplateParameters();
336 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
337 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000338 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000339
340 TypeAliasDecl *Pattern = D->getTemplatedDecl();
341
Craig Topperc3ec1492014-05-26 06:22:03 +0000342 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000343 if (Pattern->getPreviousDecl()) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000344 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000345 if (!Found.empty()) {
346 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000347 }
348 }
349
350 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
351 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
352 if (!AliasInst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000353 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000354
355 TypeAliasTemplateDecl *Inst
356 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
357 D->getDeclName(), InstParams, AliasInst);
358 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000359 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000360
361 Inst->setAccess(D->getAccess());
362
363 if (!PrevAliasTemplate)
364 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000365
Richard Smith3f1b5d02011-05-05 21:57:07 +0000366 Owner->addDecl(Inst);
367
368 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000369}
370
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000371Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000372 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000373}
374
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000375Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
376 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000377
Douglas Gregor04163182010-05-21 00:31:19 +0000378 // If this is the variable for an anonymous struct or union,
379 // instantiate the anonymous struct/union type first.
380 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
381 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
382 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +0000383 return nullptr;
Douglas Gregor04163182010-05-21 00:31:19 +0000384
John McCall76d824f2009-08-25 22:02:44 +0000385 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000386 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000387 TemplateArgs,
388 D->getTypeSpecStartLoc(),
389 D->getDeclName());
390 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +0000391 return nullptr;
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000392
Douglas Gregor61623342010-09-12 07:37:24 +0000393 if (DI->getType()->isFunctionType()) {
394 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
395 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000396 return nullptr;
Douglas Gregor61623342010-09-12 07:37:24 +0000397 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000398
Richard Smith541b38b2013-09-20 01:15:31 +0000399 DeclContext *DC = Owner;
400 if (D->isLocalExternDecl())
401 SemaRef.adjustContextForLocalExternDecl(DC);
402
Larisse Voufo39a1e502013-08-06 01:03:05 +0000403 // Build the instantiated declaration.
Richard Smith541b38b2013-09-20 01:15:31 +0000404 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000405 D->getLocation(), D->getIdentifier(),
Larisse Voufo39a1e502013-08-06 01:03:05 +0000406 DI->getType(), DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000407
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000408 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000409 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000410 SemaRef.inferObjCARCLifetime(Var))
411 Var->setInvalidDecl();
412
Larisse Voufo39a1e502013-08-06 01:03:05 +0000413 // Substitute the nested name specifier, if any.
414 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +0000415 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000416
Richard Smith541b38b2013-09-20 01:15:31 +0000417 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000418 StartingScope, InstantiatingVarTemplate);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000419
420 if (D->isNRVOVariable()) {
421 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
422 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
423 Var->setNRVOVariable(true);
424 }
425
Alexander Kornienko83a4e182014-05-27 21:29:22 +0000426 Var->setImplicit(D->isImplicit());
427
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000428 return Var;
429}
430
Abramo Bagnarad7340582010-06-05 05:09:32 +0000431Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
432 AccessSpecDecl* AD
433 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
434 D->getAccessSpecifierLoc(), D->getColonLoc());
435 Owner->addHiddenDecl(AD);
436 return AD;
437}
438
Douglas Gregord7e7a512009-03-17 21:15:40 +0000439Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
440 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000441 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000442 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000443 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000444 DI = SemaRef.SubstType(DI, TemplateArgs,
445 D->getLocation(), D->getDeclName());
446 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000447 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000448 Invalid = true;
449 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000450 // C++ [temp.arg.type]p3:
451 // If a declaration acquires a function type through a type
452 // dependent on a template-parameter and this causes a
453 // declaration that does not use the syntactic form of a
454 // function declarator to have function type, the program is
455 // ill-formed.
456 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000457 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000458 Invalid = true;
459 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000460 } else {
461 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000462 }
463
464 Expr *BitWidth = D->getBitWidth();
465 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +0000466 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000467 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000468 // The bit-width expression is a constant expression.
469 EnterExpressionEvaluationContext Unevaluated(SemaRef,
470 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000471
John McCalldadc5752010-08-24 06:29:42 +0000472 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000473 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000474 if (InstantiatedBitWidth.isInvalid()) {
475 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +0000476 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000477 } else
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000478 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000479 }
480
John McCall90459c52009-10-22 23:33:21 +0000481 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
482 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000483 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000484 D->getLocation(),
485 D->isMutable(),
486 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000487 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000488 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000489 D->getAccess(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000490 nullptr);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000491 if (!Field) {
492 cast<Decl>(Owner)->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +0000493 return nullptr;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000494 }
Mike Stump11289f42009-09-09 15:08:12 +0000495
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000496 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000497
Richard Smith848e1f12013-02-01 08:12:08 +0000498 if (Field->hasAttrs())
499 SemaRef.CheckAlignasUnderalignment(Field);
500
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000501 if (Invalid)
502 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000503
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000504 if (!Field->getDeclName()) {
505 // Keep track of where this decl came from.
506 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000507 }
Douglas Gregor04163182010-05-21 00:31:19 +0000508 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
509 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000510 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000511 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000514 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000515 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000516 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000517
518 return Field;
519}
520
John McCall5e77d762013-04-16 07:28:30 +0000521Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
522 bool Invalid = false;
523 TypeSourceInfo *DI = D->getTypeSourceInfo();
524
525 if (DI->getType()->isVariablyModifiedType()) {
526 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +0000527 << D;
John McCall5e77d762013-04-16 07:28:30 +0000528 Invalid = true;
529 } else if (DI->getType()->isInstantiationDependentType()) {
530 DI = SemaRef.SubstType(DI, TemplateArgs,
531 D->getLocation(), D->getDeclName());
532 if (!DI) {
533 DI = D->getTypeSourceInfo();
534 Invalid = true;
535 } else if (DI->getType()->isFunctionType()) {
536 // C++ [temp.arg.type]p3:
537 // If a declaration acquires a function type through a type
538 // dependent on a template-parameter and this causes a
539 // declaration that does not use the syntactic form of a
540 // function declarator to have function type, the program is
541 // ill-formed.
542 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
543 << DI->getType();
544 Invalid = true;
545 }
546 } else {
547 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
548 }
549
Richard Smithf7981722013-11-22 09:01:48 +0000550 MSPropertyDecl *Property = MSPropertyDecl::Create(
551 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
552 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000553
554 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
555 StartingScope);
556
557 if (Invalid)
558 Property->setInvalidDecl();
559
560 Property->setAccess(D->getAccess());
561 Owner->addDecl(Property);
562
563 return Property;
564}
565
Francois Pichet783dd6e2010-11-21 06:08:52 +0000566Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
567 NamedDecl **NamedChain =
568 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
569
570 int i = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +0000571 for (auto *PI : D->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +0000572 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000573 TemplateArgs);
574 if (!Next)
Craig Topperc3ec1492014-05-26 06:22:03 +0000575 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000576
Douglas Gregor55e6b312011-03-04 19:46:35 +0000577 NamedChain[i++] = Next;
578 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000579
Francois Pichetdbafc192010-12-09 10:07:54 +0000580 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet783dd6e2010-11-21 06:08:52 +0000581 IndirectFieldDecl* IndirectField
582 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichetdbafc192010-12-09 10:07:54 +0000583 D->getIdentifier(), T,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000584 NamedChain, D->getChainingSize());
585
586
587 IndirectField->setImplicit(D->isImplicit());
588 IndirectField->setAccess(D->getAccess());
589 Owner->addDecl(IndirectField);
590 return IndirectField;
591}
592
John McCallaa74a0c2009-08-28 07:59:38 +0000593Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000594 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000595 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000596 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000597 TypeSourceInfo *InstTy;
598 // If this is an unsupported friend, don't bother substituting template
599 // arguments into it. The actual type referred to won't be used by any
600 // parts of Clang, and may not be valid for instantiating. Just use the
601 // same info for the instantiated friend.
602 if (D->isUnsupportedFriend()) {
603 InstTy = Ty;
604 } else {
605 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
606 D->getLocation(), DeclarationName());
607 }
608 if (!InstTy)
Craig Topperc3ec1492014-05-26 06:22:03 +0000609 return nullptr;
John McCallaa74a0c2009-08-28 07:59:38 +0000610
Richard Smitha31a89a2012-09-20 01:31:00 +0000611 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000612 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000613 if (!FD)
Craig Topperc3ec1492014-05-26 06:22:03 +0000614 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000615
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000616 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000617 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000618 Owner->addDecl(FD);
619 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000620 }
621
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000622 NamedDecl *ND = D->getFriendDecl();
623 assert(ND && "friend decl must be a decl or a type!");
624
John McCallb9c78482010-04-08 09:05:18 +0000625 // All of the Visit implementations for the various potential friend
626 // declarations have to be carefully written to work for friend
627 // objects, with the most important detail being that the target
628 // decl should almost certainly not be placed in Owner.
629 Decl *NewND = Visit(ND);
Craig Topperc3ec1492014-05-26 06:22:03 +0000630 if (!NewND) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000631
John McCallaa74a0c2009-08-28 07:59:38 +0000632 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000633 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000634 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000635 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000636 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000637 Owner->addDecl(FD);
638 return FD;
John McCall58de3582009-08-14 02:03:10 +0000639}
640
Douglas Gregord7e7a512009-03-17 21:15:40 +0000641Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
642 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000643
Richard Smith764d2fe2011-12-20 02:08:33 +0000644 // The expression in a static assertion is a constant expression.
645 EnterExpressionEvaluationContext Unevaluated(SemaRef,
646 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000647
John McCalldadc5752010-08-24 06:29:42 +0000648 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000649 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000650 if (InstantiatedAssertExpr.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +0000651 return nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000652
Richard Smithded9c2e2012-07-11 22:37:56 +0000653 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000654 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000655 D->getMessage(),
656 D->getRParenLoc(),
657 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000658}
659
660Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000661 EnumDecl *PrevDecl = nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +0000662 if (D->getPreviousDecl()) {
663 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
664 D->getPreviousDecl(),
665 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +0000666 if (!Prev) return nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +0000667 PrevDecl = cast<EnumDecl>(Prev);
668 }
669
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000670 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000671 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000672 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000673 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000674 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000675 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000676 // If we have type source information for the underlying type, it means it
677 // has been explicitly set by the user. Perform substitution on it before
678 // moving on.
679 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000680 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
681 DeclarationName());
682 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000683 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000684 else
685 Enum->setIntegerTypeSourceInfo(NewTI);
686 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000687 assert(!D->getIntegerType()->isDependentType()
688 && "Dependent type without type source info");
689 Enum->setIntegerType(D->getIntegerType());
690 }
691 }
692
John McCall811a0f52010-10-22 23:36:17 +0000693 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
694
Richard Smith4b38ded2012-03-14 23:13:10 +0000695 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000696 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +0000697 // Forward the mangling number from the template to the instantiated decl.
698 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
Craig Topperc3ec1492014-05-26 06:22:03 +0000699 if (SubstQualifier(D, Enum)) return nullptr;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000700 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +0000701
Richard Smith258a7442012-03-26 04:08:46 +0000702 EnumDecl *Def = D->getDefinition();
703 if (Def && Def != D) {
704 // If this is an out-of-line definition of an enum member template, check
705 // that the underlying types match in the instantiation of both
706 // declarations.
707 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
708 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
709 QualType DefnUnderlying =
710 SemaRef.SubstType(TI->getType(), TemplateArgs,
711 UnderlyingLoc, DeclarationName());
712 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
713 DefnUnderlying, Enum);
714 }
715 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000716
Richard Smith4b38ded2012-03-14 23:13:10 +0000717 // C++11 [temp.inst]p1: The implicit instantiation of a class template
718 // specialization causes the implicit instantiation of the declarations, but
719 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +0000720 //
721 // DR1484 clarifies that enumeration definitions inside of a template
722 // declaration aren't considered entities that can be separately instantiated
723 // from the rest of the entity they are declared inside of.
724 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
725 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +0000726 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +0000727 }
Richard Smith4b38ded2012-03-14 23:13:10 +0000728
729 return Enum;
730}
731
732void TemplateDeclInstantiator::InstantiateEnumDefinition(
733 EnumDecl *Enum, EnumDecl *Pattern) {
734 Enum->startDefinition();
735
Richard Smith7d137e32012-03-23 03:33:32 +0000736 // Update the location to refer to the definition.
737 Enum->setLocation(Pattern->getLocation());
738
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000739 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000740
Craig Topperc3ec1492014-05-26 06:22:03 +0000741 EnumConstantDecl *LastEnumConst = nullptr;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000742 for (auto *EC : Pattern->enumerators()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000743 // The specified value for the enumerator.
Craig Topperc3ec1492014-05-26 06:22:03 +0000744 ExprResult Value = SemaRef.Owned((Expr *)nullptr);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000745 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000746 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +0000747 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +0000748 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000749
John McCall76d824f2009-08-25 22:02:44 +0000750 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000751 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000752
753 // Drop the initial value and continue.
754 bool isInvalid = false;
755 if (Value.isInvalid()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000756 Value = SemaRef.Owned((Expr *)nullptr);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000757 isInvalid = true;
758 }
759
Mike Stump11289f42009-09-09 15:08:12 +0000760 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +0000761 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
762 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +0000763 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000764
765 if (isInvalid) {
766 if (EnumConst)
767 EnumConst->setInvalidDecl();
768 Enum->setInvalidDecl();
769 }
770
771 if (EnumConst) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000772 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +0000773
John McCallf9b528c2010-01-23 22:37:59 +0000774 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000775 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +0000776 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000777 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000778
Richard Smith4b38ded2012-03-14 23:13:10 +0000779 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
780 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000781 // If the enumeration is within a function or method, record the enum
782 // constant as a local.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000783 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000784 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000785 }
786 }
Mike Stump11289f42009-09-09 15:08:12 +0000787
Richard Smith4b38ded2012-03-14 23:13:10 +0000788 // FIXME: Fixup LBraceLoc
789 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
790 Enum->getRBraceLoc(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +0000791 Enumerators,
Craig Topperc3ec1492014-05-26 06:22:03 +0000792 nullptr, nullptr);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000793}
794
Douglas Gregor9106b822009-03-25 15:04:13 +0000795Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000796 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +0000797}
798
John McCall87a44eb2009-08-20 01:44:21 +0000799Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000800 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
801
Douglas Gregor954de172009-10-31 17:21:17 +0000802 // Create a local instantiation scope for this class template, which
803 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +0000804 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +0000805 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000806 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000807 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000808 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +0000809
810 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +0000811
812 // Instantiate the qualifier. We have to do this first in case
813 // we're a friend declaration, because if we are then we need to put
814 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +0000815 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
816 if (QualifierLoc) {
817 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
818 TemplateArgs);
819 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +0000820 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000821 }
822
Craig Topperc3ec1492014-05-26 06:22:03 +0000823 CXXRecordDecl *PrevDecl = nullptr;
824 ClassTemplateDecl *PrevClassTemplate = nullptr;
John McCall598b4402010-03-25 06:39:04 +0000825
Douglas Gregorec9fd132012-01-14 16:38:05 +0000826 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky61478912010-11-08 23:29:42 +0000827 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000828 if (!Found.empty()) {
829 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +0000830 if (PrevClassTemplate)
831 PrevDecl = PrevClassTemplate->getTemplatedDecl();
832 }
833 }
834
John McCall598b4402010-03-25 06:39:04 +0000835 // If this isn't a friend, then it's a member template, in which
836 // case we just want to build the instantiation in the
837 // specialization. If it is a friend, we want to build it in
838 // the appropriate context.
839 DeclContext *DC = Owner;
840 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +0000841 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000842 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +0000843 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +0000844 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +0000845 if (!DC) return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000846 } else {
847 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
848 Pattern->getDeclContext(),
849 TemplateArgs);
850 }
851
852 // Look for a previous declaration of the template in the owning
853 // context.
854 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
855 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
856 SemaRef.LookupQualifiedName(R, DC);
857
858 if (R.isSingleResult()) {
859 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
860 if (PrevClassTemplate)
861 PrevDecl = PrevClassTemplate->getTemplatedDecl();
862 }
863
Douglas Gregor14454802011-02-25 02:25:35 +0000864 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000865 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +0000866 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +0000867 << QualifierLoc.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000868 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000869 }
870
Douglas Gregor01e09d92010-04-08 18:16:15 +0000871 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +0000872 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +0000873 bool Complain = true;
874
875 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
876 // template for struct std::tr1::__detail::_Map_base, where the
877 // template parameters of the friend declaration don't match the
878 // template parameters of the original declaration. In this one
879 // case, we don't complain about the ill-formed friend
880 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000881 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +0000882 Pattern->getIdentifier()->isStr("_Map_base") &&
883 DC->isNamespace() &&
884 cast<NamespaceDecl>(DC)->getIdentifier() &&
885 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
886 DeclContext *DCParent = DC->getParent();
887 if (DCParent->isNamespace() &&
888 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
889 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
890 DeclContext *DCParent2 = DCParent->getParent();
891 if (DCParent2->isNamespace() &&
892 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
893 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
894 DCParent2->getParent()->isTranslationUnit())
895 Complain = false;
896 }
897 }
898
John McCall598b4402010-03-25 06:39:04 +0000899 TemplateParameterList *PrevParams
900 = PrevClassTemplate->getTemplateParameters();
901
902 // Make sure the parameter lists match.
903 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000904 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +0000905 Sema::TPL_TemplateMatch)) {
906 if (Complain)
Craig Topperc3ec1492014-05-26 06:22:03 +0000907 return nullptr;
Douglas Gregor01e09d92010-04-08 18:16:15 +0000908
909 AdoptedPreviousTemplateParams = true;
910 InstParams = PrevParams;
911 }
John McCall598b4402010-03-25 06:39:04 +0000912
913 // Do some additional validation, then merge default arguments
914 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +0000915 if (!AdoptedPreviousTemplateParams &&
916 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +0000917 Sema::TPC_ClassTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +0000918 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000919 }
920 }
921
John McCall87a44eb2009-08-20 01:44:21 +0000922 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +0000923 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000924 Pattern->getLocStart(), Pattern->getLocation(),
925 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000926 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +0000927
Douglas Gregor14454802011-02-25 02:25:35 +0000928 if (QualifierLoc)
929 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +0000930
John McCall87a44eb2009-08-20 01:44:21 +0000931 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +0000932 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
933 D->getIdentifier(), InstParams, RecordInst,
934 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +0000935 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +0000936
John McCall598b4402010-03-25 06:39:04 +0000937 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +0000938 if (PrevClassTemplate)
939 Inst->setAccess(PrevClassTemplate->getAccess());
940 else
941 Inst->setAccess(D->getAccess());
942
Richard Smith64017682013-07-17 23:53:16 +0000943 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +0000944 // TODO: do we want to track the instantiation progeny of this
945 // friend target decl?
946 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000947 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +0000948 if (!PrevClassTemplate)
949 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +0000950 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000951
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000952 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +0000953 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +0000954 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +0000955
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000956 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +0000957 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +0000958 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000959 Inst->setLexicalDeclContext(Owner);
960 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000961 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000962 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000963
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000964 if (D->isOutOfLine()) {
965 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
966 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
967 }
968
John McCall87a44eb2009-08-20 01:44:21 +0000969 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +0000970
971 if (!PrevClassTemplate) {
972 // Queue up any out-of-line partial specializations of this member
973 // class template; the client will force their instantiation once
974 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000975 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +0000976 D->getPartialSpecializations(PartialSpecs);
977 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000978 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +0000979 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
980 }
981
John McCall87a44eb2009-08-20 01:44:21 +0000982 return Inst;
983}
984
Douglas Gregore704c9d2009-08-27 16:57:43 +0000985Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +0000986TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
987 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +0000988 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000989
Douglas Gregor21610382009-10-29 00:04:11 +0000990 // Lookup the already-instantiated declaration in the instantiation
991 // of the class template and return that.
992 DeclContext::lookup_result Found
993 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000994 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +0000995 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000996
Douglas Gregor21610382009-10-29 00:04:11 +0000997 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +0000998 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +0000999 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00001000 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001001
Douglas Gregor869853e2010-11-10 19:44:59 +00001002 if (ClassTemplatePartialSpecializationDecl *Result
1003 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1004 return Result;
1005
1006 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001007}
1008
Larisse Voufo39a1e502013-08-06 01:03:05 +00001009Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1010 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1011 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001012
1013 // Create a local instantiation scope for this variable template, which
1014 // will contain the instantiations of the template parameters.
1015 LocalInstantiationScope Scope(SemaRef);
1016 TemplateParameterList *TempParams = D->getTemplateParameters();
1017 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1018 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001019 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001020
1021 VarDecl *Pattern = D->getTemplatedDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001022 VarTemplateDecl *PrevVarTemplate = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001023
1024 if (Pattern->getPreviousDecl()) {
1025 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1026 if (!Found.empty())
1027 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1028 }
1029
Richard Smith1c34fb72013-08-13 18:18:50 +00001030 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001031 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1032 /*InstantiatingVarTemplate=*/true));
Larisse Voufo39a1e502013-08-06 01:03:05 +00001033
1034 DeclContext *DC = Owner;
1035
Larisse Voufo39a1e502013-08-06 01:03:05 +00001036 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1037 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001038 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001039 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001040 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001041
1042 Inst->setAccess(D->getAccess());
1043 if (!PrevVarTemplate)
1044 Inst->setInstantiatedFromMemberTemplate(D);
1045
1046 if (D->isOutOfLine()) {
1047 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1048 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1049 }
1050
1051 Owner->addDecl(Inst);
1052
1053 if (!PrevVarTemplate) {
1054 // Queue up any out-of-line partial specializations of this member
1055 // variable template; the client will force their instantiation once
1056 // the enclosing class has been instantiated.
1057 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1058 D->getPartialSpecializations(PartialSpecs);
1059 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001060 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001061 OutOfLineVarPartialSpecs.push_back(
1062 std::make_pair(Inst, PartialSpecs[I]));
1063 }
1064
1065 return Inst;
1066}
1067
1068Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1069 VarTemplatePartialSpecializationDecl *D) {
1070 assert(D->isStaticDataMember() &&
1071 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001072
1073 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1074
1075 // Lookup the already-instantiated declaration and return that.
1076 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1077 assert(!Found.empty() && "Instantiation found nothing?");
1078
1079 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1080 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1081
1082 if (VarTemplatePartialSpecializationDecl *Result =
1083 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1084 return Result;
1085
1086 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1087}
1088
Douglas Gregore4b05162009-10-07 17:21:34 +00001089Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001090TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001091 // Create a local instantiation scope for this function template, which
1092 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001093 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001094 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001095 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001096
Douglas Gregore704c9d2009-08-27 16:57:43 +00001097 TemplateParameterList *TempParams = D->getTemplateParameters();
1098 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001099 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001100 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001101
Craig Topperc3ec1492014-05-26 06:22:03 +00001102 FunctionDecl *Instantiated = nullptr;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001103 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001104 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001105 InstParams));
1106 else
1107 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001108 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001109 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001110
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001111 if (!Instantiated)
Craig Topperc3ec1492014-05-26 06:22:03 +00001112 return nullptr;
Douglas Gregore704c9d2009-08-27 16:57:43 +00001113
Mike Stump11289f42009-09-09 15:08:12 +00001114 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001115 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001116 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001117 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001118 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001119 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001120 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001121
John McCall30837102010-03-26 23:10:15 +00001122 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1123
John McCall2079d0b2009-12-14 23:19:40 +00001124 // Link the instantiation back to the pattern *unless* this is a
1125 // non-definition friend declaration.
1126 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001127 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001128 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001129
John McCall30837102010-03-26 23:10:15 +00001130 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001131 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001132 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001133 } else if (InstTemplate->getDeclContext()->isRecord() &&
1134 !D->getPreviousDecl()) {
1135 SemaRef.CheckFriendAccess(InstTemplate);
1136 }
John McCall30837102010-03-26 23:10:15 +00001137
Douglas Gregore704c9d2009-08-27 16:57:43 +00001138 return InstTemplate;
1139}
1140
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001141Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001142 CXXRecordDecl *PrevDecl = nullptr;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001143 if (D->isInjectedClassName())
1144 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001145 else if (D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001146 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregorec9fd132012-01-14 16:38:05 +00001147 D->getPreviousDecl(),
John McCalle9f92a02009-12-15 22:29:06 +00001148 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001149 if (!Prev) return nullptr;
John McCalle9f92a02009-12-15 22:29:06 +00001150 PrevDecl = cast<CXXRecordDecl>(Prev);
1151 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001152
1153 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001154 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001155 D->getLocStart(), D->getLocation(),
1156 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001157
1158 // Substitute the nested name specifier, if any.
1159 if (SubstQualifier(D, Record))
Craig Topperc3ec1492014-05-26 06:22:03 +00001160 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00001161
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001162 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001163 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1164 // the tag decls introduced by friend class declarations don't have an access
1165 // specifier. Remove once this area of the code gets sorted out.
1166 if (D->getAccess() != AS_none)
1167 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001168 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001169 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001170
John McCallaa74a0c2009-08-28 07:59:38 +00001171 // If the original function was part of a friend declaration,
1172 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001173 if (D->getFriendObjectKind())
1174 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001175
Douglas Gregor04163182010-05-21 00:31:19 +00001176 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001177 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001178 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001179
1180 if (D->isLocalClass())
1181 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001182
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001183 // Forward the mangling number from the template to the instantiated decl.
1184 SemaRef.Context.setManglingNumber(Record,
1185 SemaRef.Context.getManglingNumber(D));
1186
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001187 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001188
1189 // DR1484 clarifies that the members of a local class are instantiated as part
1190 // of the instantiation of their enclosing entity.
1191 if (D->isCompleteDefinition() && D->isLocalClass()) {
David Majnemera64cb5a2014-02-22 00:17:46 +00001192 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1193 TSK_ImplicitInstantiation,
1194 /*Complain=*/true);
1195 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1196 TSK_ImplicitInstantiation);
David Majnemer192d1792013-11-27 08:20:38 +00001197 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001198 return Record;
1199}
1200
Douglas Gregor89f593a2012-09-13 21:56:43 +00001201/// \brief Adjust the given function type for an instantiation of the
1202/// given declaration, to cope with modifications to the function's type that
1203/// aren't reflected in the type-source information.
1204///
1205/// \param D The declaration we're instantiating.
1206/// \param TInfo The already-instantiated type.
1207static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1208 FunctionDecl *D,
1209 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001210 const FunctionProtoType *OrigFunc
1211 = D->getType()->castAs<FunctionProtoType>();
1212 const FunctionProtoType *NewFunc
1213 = TInfo->getType()->castAs<FunctionProtoType>();
1214 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1215 return TInfo->getType();
1216
1217 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1218 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001219 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001220 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001221}
1222
John McCallaa74a0c2009-08-28 07:59:38 +00001223/// Normal class members are of more specific types and therefore
1224/// don't make it here. This function serves two purposes:
1225/// 1) instantiating function templates
1226/// 2) substituting friend declarations
Douglas Gregor33636e62009-12-24 20:56:24 +00001227Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001228 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001229 // Check whether there is already a function template specialization for
1230 // this declaration.
1231 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001232 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001233 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001234
Craig Topperc3ec1492014-05-26 06:22:03 +00001235 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001236 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001237 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001238 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001239
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001240 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001241 if (SpecFunc)
1242 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001243 }
Mike Stump11289f42009-09-09 15:08:12 +00001244
John McCall2f88d7d2010-03-27 05:57:59 +00001245 bool isFriend;
1246 if (FunctionTemplate)
1247 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1248 else
1249 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1250
Craig Topperc3ec1492014-05-26 06:22:03 +00001251 bool MergeWithParentScope = (TemplateParams != nullptr) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001252 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001253 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001254 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001255 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001256
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001257 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001258 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001259 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001260 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001261 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001262
Douglas Gregor14454802011-02-25 02:25:35 +00001263 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1264 if (QualifierLoc) {
1265 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1266 TemplateArgs);
1267 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001268 return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001269 }
1270
John McCallce410662010-02-06 01:50:47 +00001271 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001272 // in the enclosing namespace; otherwise we need to find the instantiated
1273 // context.
John McCallce410662010-02-06 01:50:47 +00001274 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001275 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001276 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001277 SemaRef.adjustContextForLocalExternDecl(DC);
1278 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001279 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001280 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001281 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001282 if (!DC) return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001283 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001284 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001285 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001286 }
John McCallce410662010-02-06 01:50:47 +00001287
John McCallaa74a0c2009-08-28 07:59:38 +00001288 FunctionDecl *Function =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001289 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara0d4fce12012-10-04 21:40:42 +00001290 D->getNameInfo(), T, TInfo,
Rafael Espindola9dd86de2013-04-16 02:29:15 +00001291 D->getCanonicalDecl()->getStorageClass(),
Richard Smitha77a0a62011-08-15 21:04:07 +00001292 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001293 D->isConstexpr());
Enea Zaffanella25723ce2013-07-19 18:02:36 +00001294 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCall3e11ebe2010-03-15 10:12:16 +00001295
Richard Smithf3814ad2013-01-25 00:08:28 +00001296 if (D->isInlined())
1297 Function->setImplicitlyInline();
1298
Douglas Gregor14454802011-02-25 02:25:35 +00001299 if (QualifierLoc)
1300 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001301
Richard Smith541b38b2013-09-20 01:15:31 +00001302 if (D->isLocalExternDecl())
1303 Function->setLocalExternDecl();
1304
John McCall30837102010-03-26 23:10:15 +00001305 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001306 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001307 assert(D->getDeclContext()->isFileContext());
1308 LexicalDC = D->getDeclContext();
1309 }
1310
1311 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001312
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001313 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001314 for (unsigned P = 0; P < Params.size(); ++P)
1315 if (Params[P])
1316 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001317 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001318
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001319 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001320 if (TemplateParams) {
1321 // Our resulting instantiation is actually a function template, since we
1322 // are substituting only the outer template parameters. For example, given
1323 //
1324 // template<typename T>
1325 // struct X {
1326 // template<typename U> friend void f(T, U);
1327 // };
1328 //
1329 // X<int> x;
1330 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001331 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001332 // which means substituting int for T, but leaving "f" as a friend function
1333 // template.
1334 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001335 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001336 Function->getLocation(),
1337 Function->getDeclName(),
1338 TemplateParams, Function);
1339 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001340
1341 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001342
1343 if (isFriend && D->isThisDeclarationADefinition()) {
1344 // TODO: should we remember this connection regardless of whether
1345 // the friend declaration provided a body?
1346 FunctionTemplate->setInstantiatedFromMemberTemplate(
1347 D->getDescribedFunctionTemplate());
1348 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001349 } else if (FunctionTemplate) {
1350 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001351 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001352 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001353 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001354 Innermost.begin(),
1355 Innermost.size()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001356 /*InsertPos=*/nullptr);
Chandler Carruth48b28312011-08-18 09:09:59 +00001357 } else if (isFriend) {
1358 // Note, we need this connection even if the friend doesn't have a body.
1359 // Its body may exist but not have been attached yet due to deferred
1360 // parsing.
1361 // FIXME: It might be cleaner to set this when attaching the body to the
1362 // friend function declaration, however that would require finding all the
1363 // instantiations and modifying them.
John McCalle0b2ddb2010-03-26 04:53:08 +00001364 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001365 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001366
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001367 if (InitFunctionInstantiation(Function, D))
1368 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001369
John McCallb9c78482010-04-08 09:05:18 +00001370 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001371
Richard Smith541b38b2013-09-20 01:15:31 +00001372 LookupResult Previous(
1373 SemaRef, Function->getDeclName(), SourceLocation(),
1374 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1375 : Sema::LookupOrdinaryName,
1376 Sema::ForRedeclaration);
John McCall1f82f242009-11-18 22:49:29 +00001377
John McCallb9c78482010-04-08 09:05:18 +00001378 if (DependentFunctionTemplateSpecializationInfo *Info
1379 = D->getDependentSpecializationInfo()) {
1380 assert(isFriend && "non-friend has dependent specialization info?");
1381
1382 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001383 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001384
1385 // Instantiate the explicit template arguments.
1386 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1387 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001388 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1389 ExplicitArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00001390 return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001391
1392 // Map the candidate templates to their instantiations.
1393 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1394 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1395 Info->getTemplate(I),
1396 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001397 if (!Temp) return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001398
1399 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1400 }
1401
1402 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1403 &ExplicitArgs,
1404 Previous))
1405 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001406
John McCallb9c78482010-04-08 09:05:18 +00001407 isExplicitSpecialization = true;
1408
1409 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001410 // Look only into the namespace where the friend would be declared to
1411 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001412 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001413 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001414
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001415 // In C++, the previous declaration we find might be a tag type
1416 // (class or enum). In this case, the new declaration will hide the
1417 // tag type. Note that this does does not apply if we're declaring a
1418 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001419 if (Previous.isSingleTagDecl())
1420 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001421 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001422
Craig Topperc3ec1492014-05-26 06:22:03 +00001423 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001424 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001425
John McCallb9467b62010-04-24 01:30:58 +00001426 NamedDecl *PrincipalDecl = (TemplateParams
1427 ? cast<NamedDecl>(FunctionTemplate)
1428 : Function);
1429
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001430 // If the original function was part of a friend declaration,
1431 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001432 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001433 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001434 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001435
Richard Smith91dfaac2014-02-03 02:37:59 +00001436 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001437
Richard Smith91dfaac2014-02-03 02:37:59 +00001438 // C++11 [temp.friend]p4 (DR329):
1439 // When a function is defined in a friend function declaration in a class
1440 // template, the function is instantiated when the function is odr-used.
1441 // The same restrictions on multiple declarations and definitions that
1442 // apply to non-template function declarations and definitions also apply
1443 // to these implicit definitions.
1444 if (D->isThisDeclarationADefinition()) {
Douglas Gregorb92ea592010-05-18 05:45:02 +00001445 // Check for a function body.
Craig Topperc3ec1492014-05-26 06:22:03 +00001446 const FunctionDecl *Definition = nullptr;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001447 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001448 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001449 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1450 << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001451 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001452 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001453 // Check for redefinitions due to other instantiations of this or
1454 // a similar friend function.
Aaron Ballman86c93902014-03-06 23:45:36 +00001455 else for (auto R : Function->redecls()) {
1456 if (R == Function)
Gabor Greif122f1eb2010-08-28 15:42:30 +00001457 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00001458
1459 // If some prior declaration of this function has been used, we need
1460 // to instantiate its definition.
1461 if (!QueuedInstantiation && R->isUsed(false)) {
1462 if (MemberSpecializationInfo *MSInfo =
1463 Function->getMemberSpecializationInfo()) {
1464 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1465 SourceLocation Loc = R->getLocation(); // FIXME
1466 MSInfo->setPointOfInstantiation(Loc);
1467 SemaRef.PendingLocalImplicitInstantiations.push_back(
1468 std::make_pair(Function, Loc));
1469 QueuedInstantiation = true;
Gabor Greif718d5152010-08-30 21:10:05 +00001470 }
1471 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001472 }
1473
1474 // If some prior declaration of this function was a friend with an
1475 // uninstantiated definition, reject it.
1476 if (R->getFriendObjectKind()) {
1477 if (const FunctionDecl *RPattern =
1478 R->getTemplateInstantiationPattern()) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001479 if (RPattern->isDefined(RPattern)) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001480 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001481 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001482 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregorb92ea592010-05-18 05:45:02 +00001483 break;
1484 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001485 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001486 }
1487 }
1488 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001489 }
1490
Richard Smith541b38b2013-09-20 01:15:31 +00001491 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1492 DC->makeDeclVisibleInContext(PrincipalDecl);
1493
John McCallb9467b62010-04-24 01:30:58 +00001494 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1495 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1496 PrincipalDecl->setNonMemberOperator();
1497
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001498 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001499 return Function;
1500}
1501
Douglas Gregore704c9d2009-08-27 16:57:43 +00001502Decl *
1503TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001504 TemplateParameterList *TemplateParams,
1505 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001506 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001507 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001508 // We are creating a function template specialization from a function
1509 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001510 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001511 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001512
Craig Topperc3ec1492014-05-26 06:22:03 +00001513 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001514 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001515 = FunctionTemplate->findSpecialization(Innermost.begin(),
1516 Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001517 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001518
Douglas Gregor97628d62009-08-21 00:16:32 +00001519 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001520 if (SpecFunc)
1521 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001522 }
1523
John McCall2f88d7d2010-03-27 05:57:59 +00001524 bool isFriend;
1525 if (FunctionTemplate)
1526 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1527 else
1528 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1529
Craig Topperc3ec1492014-05-26 06:22:03 +00001530 bool MergeWithParentScope = (TemplateParams != nullptr) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001531 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001532 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001533 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001534
John McCalld0e23ec2010-10-19 02:26:41 +00001535 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001536 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001537 unsigned NumTempParamLists = 0;
1538 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1539 TempParamLists.set_size(NumTempParamLists);
1540 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1541 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1542 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1543 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001544 return nullptr;
John McCalld0e23ec2010-10-19 02:26:41 +00001545 TempParamLists[I] = InstParams;
1546 }
1547 }
1548
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001549 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001550 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001551 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001552 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001553 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001554
Douglas Gregor14454802011-02-25 02:25:35 +00001555 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1556 if (QualifierLoc) {
1557 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001558 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001559 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001560 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001561 }
1562
1563 DeclContext *DC = Owner;
1564 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001565 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001566 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001567 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001568 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001569
1570 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00001571 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001572 } else {
1573 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1574 D->getDeclContext(),
1575 TemplateArgs);
1576 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001577 if (!DC) return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001578 }
1579
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001580 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001581 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Craig Topperc3ec1492014-05-26 06:22:03 +00001582 CXXMethodDecl *Method = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001583
Abramo Bagnaradff19302011-03-08 08:55:46 +00001584 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001585 DeclarationNameInfo NameInfo
1586 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001587 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001588 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001589 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001590 Constructor->isExplicit(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001591 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001592 false, Constructor->isConstexpr());
Richard Smith4c163a02013-05-17 02:19:35 +00001593
Richard Smith185be182013-04-10 05:48:59 +00001594 // Claim that the instantiation of a constructor or constructor template
1595 // inherits the same constructor that the template does.
Richard Smith4c163a02013-05-17 02:19:35 +00001596 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1597 Constructor->getInheritedConstructor())) {
1598 // If we're instantiating a specialization of a function template, our
1599 // "inherited constructor" will actually itself be a function template.
1600 // Instantiate a declaration of it, too.
1601 if (FunctionTemplate) {
1602 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1603 !Inh->getParent()->isDependentContext() &&
1604 "inheriting constructor template in dependent context?");
1605 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1606 Inh);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001607 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00001608 return nullptr;
Richard Smith4c163a02013-05-17 02:19:35 +00001609 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1610 LocalInstantiationScope LocalScope(SemaRef);
1611
1612 // Use the same template arguments that we deduced for the inheriting
1613 // constructor. There's no way they could be deduced differently.
1614 MultiLevelTemplateArgumentList InheritedArgs;
1615 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1616 Inh = cast_or_null<CXXConstructorDecl>(
1617 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1618 if (!Inh)
Craig Topperc3ec1492014-05-26 06:22:03 +00001619 return nullptr;
Richard Smith4c163a02013-05-17 02:19:35 +00001620 }
Richard Smith185be182013-04-10 05:48:59 +00001621 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smith4c163a02013-05-17 02:19:35 +00001622 }
Douglas Gregore8394862009-08-21 22:43:28 +00001623 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001624 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001625 StartLoc, NameInfo, T, TInfo,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001626 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001627 false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001628 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001629 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001630 StartLoc, NameInfo, T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001631 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001632 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001633 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001634 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001635 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001636 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001637 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001638 StartLoc, NameInfo, T, TInfo,
Rafael Espindola29cda592013-04-15 12:38:20 +00001639 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001640 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001641 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001642
Richard Smithf3814ad2013-01-25 00:08:28 +00001643 if (D->isInlined())
1644 Method->setImplicitlyInline();
1645
Douglas Gregor14454802011-02-25 02:25:35 +00001646 if (QualifierLoc)
1647 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001648
Douglas Gregore704c9d2009-08-27 16:57:43 +00001649 if (TemplateParams) {
1650 // Our resulting instantiation is actually a function template, since we
1651 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001652 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001653 // template<typename T>
1654 // struct X {
1655 // template<typename U> void f(T, U);
1656 // };
1657 //
1658 // X<int> x;
1659 //
1660 // We are instantiating the member template "f" within X<int>, which means
1661 // substituting int for T, but leaving "f" as a member function template.
1662 // Build the function template itself.
1663 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1664 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001665 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001666 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001667 if (isFriend) {
1668 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001669 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001670 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001671 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001672 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001673 } else if (FunctionTemplate) {
1674 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001675 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001676 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001677 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001678 Innermost.begin(),
1679 Innermost.size()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001680 /*InsertPos=*/nullptr);
John McCall2f88d7d2010-03-27 05:57:59 +00001681 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001682 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001683 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001684 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001685
Mike Stump11289f42009-09-09 15:08:12 +00001686 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001687 // out-of-line, the instantiation will have the same lexical
1688 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001689 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00001690 if (NumTempParamLists)
1691 Method->setTemplateParameterListsInfo(SemaRef.Context,
1692 NumTempParamLists,
1693 TempParamLists.data());
1694
John McCall2f88d7d2010-03-27 05:57:59 +00001695 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001696 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001697 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001698 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001699
Douglas Gregor21342092009-03-24 00:38:23 +00001700 // Attach the parameters
1701 for (unsigned P = 0; P < Params.size(); ++P)
1702 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00001703 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00001704
1705 if (InitMethodInstantiation(Method, D))
1706 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001707
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001708 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1709 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001710
John McCall2f88d7d2010-03-27 05:57:59 +00001711 if (!FunctionTemplate || TemplateParams || isFriend) {
1712 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001713
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001714 // In C++, the previous declaration we find might be a tag type
1715 // (class or enum). In this case, the new declaration will hide the
1716 // tag type. Note that this does does not apply if we're declaring a
1717 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001718 if (Previous.isSingleTagDecl())
1719 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001720 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001721
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001722 if (!IsClassScopeSpecialization)
Craig Topperc3ec1492014-05-26 06:22:03 +00001723 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001724
Douglas Gregor21920e372009-12-01 17:24:26 +00001725 if (D->isPure())
1726 SemaRef.CheckPureMethod(Method, SourceRange());
1727
John McCalla0a96892012-08-10 03:15:35 +00001728 // Propagate access. For a non-friend declaration, the access is
1729 // whatever we're propagating from. For a friend, it should be the
1730 // previous declaration we just found.
1731 if (isFriend && Method->getPreviousDecl())
1732 Method->setAccess(Method->getPreviousDecl()->getAccess());
1733 else
1734 Method->setAccess(D->getAccess());
1735 if (FunctionTemplate)
1736 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00001737
Anders Carlsson7c812f52011-01-20 06:52:44 +00001738 SemaRef.CheckOverrideControl(Method);
1739
Eli Friedman41340732011-11-15 22:39:08 +00001740 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00001741 if (D->isExplicitlyDefaulted())
1742 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001743 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00001744 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001745
John McCalla0a96892012-08-10 03:15:35 +00001746 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00001747 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00001748 // do nothing
1749
1750 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00001751 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00001752 // do nothing
1753
1754 // Otherwise, check access to friends and make them visible.
1755 } else if (isFriend) {
1756 // We only need to re-check access for methods which we didn't
1757 // manage to match during parsing.
1758 if (!D->getPreviousDecl())
1759 SemaRef.CheckFriendAccess(Method);
1760
1761 Record->makeDeclVisibleInContext(Method);
1762
1763 // Otherwise, add the declaration. We don't need to do this for
1764 // class-scope specializations because we'll have matched them with
1765 // the appropriate template.
1766 } else if (!IsClassScopeSpecialization) {
1767 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001768 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001769
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001770 return Method;
1771}
1772
Douglas Gregor4044d992009-03-24 16:43:20 +00001773Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001774 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001775}
1776
Douglas Gregor654b07e2009-03-24 00:15:49 +00001777Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001778 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001779}
1780
Douglas Gregor1880ba52009-03-25 00:34:44 +00001781Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001782 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001783}
1784
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00001785Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00001786 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1787 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001788}
1789
John McCall87a44eb2009-08-20 01:44:21 +00001790Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1791 TemplateTypeParmDecl *D) {
1792 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00001793 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00001794
John McCall87a44eb2009-08-20 01:44:21 +00001795 TemplateTypeParmDecl *Inst =
Abramo Bagnarab3185b02011-03-06 15:48:19 +00001796 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1797 D->getLocStart(), D->getLocation(),
Chandler Carruth08836322011-05-01 00:51:33 +00001798 D->getDepth() - TemplateArgs.getNumLevels(),
1799 D->getIndex(), D->getIdentifier(),
John McCall87a44eb2009-08-20 01:44:21 +00001800 D->wasDeclaredWithTypename(),
1801 D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001802 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00001803
David Majnemer89189202013-08-28 23:48:32 +00001804 if (D->hasDefaultArgument()) {
1805 TypeSourceInfo *InstantiatedDefaultArg =
1806 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1807 D->getDefaultArgumentLoc(), D->getDeclName());
1808 if (InstantiatedDefaultArg)
1809 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1810 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001811
1812 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001813 // scope.
1814 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001815
John McCall87a44eb2009-08-20 01:44:21 +00001816 return Inst;
1817}
1818
Douglas Gregor6b815c82009-10-23 23:25:44 +00001819Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1820 NonTypeTemplateParmDecl *D) {
1821 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001822 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001823 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1824 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001825 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001826 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001827 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001828 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001829
1830 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001831 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001832 // expansion of types. Substitute into each of the expanded types.
1833 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1834 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1835 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1836 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1837 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001838 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001839 D->getDeclName());
1840 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001841 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001842
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001843 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1844 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1845 D->getLocation());
1846 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001847 return nullptr;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001848 ExpandedParameterPackTypes.push_back(NewT);
1849 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001850
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001851 IsExpandedParameterPack = true;
1852 DI = D->getTypeSourceInfo();
1853 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00001854 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001855 // The non-type template parameter pack's type is a pack expansion of types.
1856 // Determine whether we need to expand this parameter pack into separate
1857 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00001858 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001859 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001860 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001861 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001862
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001863 // Determine whether the set of unexpanded parameter packs can and should
1864 // be expanded.
1865 bool Expand = true;
1866 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001867 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001868 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00001869 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001870 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1871 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001872 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001873 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001874 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001875 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00001876 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001877
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001878 if (Expand) {
1879 for (unsigned I = 0; I != *NumExpansions; ++I) {
1880 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1881 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001882 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001883 D->getDeclName());
1884 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001885 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001886
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001887 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1888 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1889 NewDI->getType(),
1890 D->getLocation());
1891 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001892 return nullptr;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001893 ExpandedParameterPackTypes.push_back(NewT);
1894 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001895
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001896 // Note that we have an expanded parameter pack. The "type" of this
1897 // expanded parameter pack is the original expansion type, but callers
1898 // will end up using the expanded parameter pack types for type-checking.
1899 IsExpandedParameterPack = true;
1900 DI = D->getTypeSourceInfo();
1901 T = DI->getType();
1902 } else {
1903 // We cannot fully expand the pack expansion now, so substitute into the
1904 // pattern and create a new pack expansion type.
1905 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1906 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001907 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001908 D->getDeclName());
1909 if (!NewPattern)
Craig Topperc3ec1492014-05-26 06:22:03 +00001910 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001911
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001912 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1913 NumExpansions);
1914 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001915 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001916
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001917 T = DI->getType();
1918 }
1919 } else {
1920 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001921 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001922 D->getLocation(), D->getDeclName());
1923 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001924 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001925
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001926 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001927 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001928 D->getLocation());
1929 if (T.isNull()) {
1930 T = SemaRef.Context.IntTy;
1931 Invalid = true;
1932 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00001933 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001934
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001935 NonTypeTemplateParmDecl *Param;
1936 if (IsExpandedParameterPack)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001937 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001938 D->getInnerLocStart(),
1939 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001940 D->getDepth() - TemplateArgs.getNumLevels(),
1941 D->getPosition(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001942 D->getIdentifier(), T,
1943 DI,
1944 ExpandedParameterPackTypes.data(),
1945 ExpandedParameterPackTypes.size(),
1946 ExpandedParameterPackTypesAsWritten.data());
1947 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001948 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001949 D->getInnerLocStart(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001950 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001951 D->getDepth() - TemplateArgs.getNumLevels(),
1952 D->getPosition(),
1953 D->getIdentifier(), T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001954 D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001955
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001956 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001957 if (Invalid)
1958 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001959
David Majnemer89189202013-08-28 23:48:32 +00001960 if (D->hasDefaultArgument()) {
1961 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1962 if (!Value.isInvalid())
1963 Param->setDefaultArgument(Value.get(), false);
1964 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001965
1966 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001967 // scope.
1968 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001969 return Param;
1970}
1971
Richard Smith1fde8ec2012-09-07 02:06:42 +00001972static void collectUnexpandedParameterPacks(
1973 Sema &S,
1974 TemplateParameterList *Params,
1975 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1976 for (TemplateParameterList::const_iterator I = Params->begin(),
1977 E = Params->end(); I != E; ++I) {
1978 if ((*I)->isTemplateParameterPack())
1979 continue;
1980 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1981 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1982 Unexpanded);
1983 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1984 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1985 Unexpanded);
1986 }
1987}
1988
Anders Carlsson4bd78752009-08-28 15:18:15 +00001989Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00001990TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1991 TemplateTemplateParmDecl *D) {
1992 // Instantiate the template parameter list of the template template parameter.
1993 TemplateParameterList *TempParams = D->getTemplateParameters();
1994 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001995 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1996
1997 bool IsExpandedParameterPack = false;
1998
1999 if (D->isExpandedParameterPack()) {
2000 // The template template parameter pack is an already-expanded pack
2001 // expansion of template parameters. Substitute into each of the expanded
2002 // parameters.
2003 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2004 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2005 I != N; ++I) {
2006 LocalInstantiationScope Scope(SemaRef);
2007 TemplateParameterList *Expansion =
2008 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2009 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002010 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002011 ExpandedParams.push_back(Expansion);
2012 }
2013
2014 IsExpandedParameterPack = true;
2015 InstParams = TempParams;
2016 } else if (D->isPackExpansion()) {
2017 // The template template parameter pack expands to a pack of template
2018 // template parameters. Determine whether we need to expand this parameter
2019 // pack into separate parameters.
2020 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2021 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2022 Unexpanded);
2023
2024 // Determine whether the set of unexpanded parameter packs can and should
2025 // be expanded.
2026 bool Expand = true;
2027 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002028 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002029 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2030 TempParams->getSourceRange(),
2031 Unexpanded,
2032 TemplateArgs,
2033 Expand, RetainExpansion,
2034 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002035 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002036
2037 if (Expand) {
2038 for (unsigned I = 0; I != *NumExpansions; ++I) {
2039 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2040 LocalInstantiationScope Scope(SemaRef);
2041 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2042 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002043 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002044 ExpandedParams.push_back(Expansion);
2045 }
2046
2047 // Note that we have an expanded parameter pack. The "type" of this
2048 // expanded parameter pack is the original expansion type, but callers
2049 // will end up using the expanded parameter pack types for type-checking.
2050 IsExpandedParameterPack = true;
2051 InstParams = TempParams;
2052 } else {
2053 // We cannot fully expand the pack expansion now, so just substitute
2054 // into the pattern.
2055 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2056
2057 LocalInstantiationScope Scope(SemaRef);
2058 InstParams = SubstTemplateParams(TempParams);
2059 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002060 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002061 }
2062 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002063 // Perform the actual substitution of template parameters within a new,
2064 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002065 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002066 InstParams = SubstTemplateParams(TempParams);
2067 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002068 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002069 }
2070
Douglas Gregor38fee962009-11-11 16:58:32 +00002071 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002072 TemplateTemplateParmDecl *Param;
2073 if (IsExpandedParameterPack)
2074 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2075 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002076 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00002077 D->getPosition(),
2078 D->getIdentifier(), InstParams,
2079 ExpandedParams);
2080 else
2081 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2082 D->getLocation(),
2083 D->getDepth() - TemplateArgs.getNumLevels(),
2084 D->getPosition(),
2085 D->isParameterPack(),
2086 D->getIdentifier(), InstParams);
David Majnemer89189202013-08-28 23:48:32 +00002087 if (D->hasDefaultArgument()) {
2088 NestedNameSpecifierLoc QualifierLoc =
2089 D->getDefaultArgument().getTemplateQualifierLoc();
2090 QualifierLoc =
2091 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2092 TemplateName TName = SemaRef.SubstTemplateName(
2093 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2094 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2095 if (!TName.isNull())
2096 Param->setDefaultArgument(
2097 TemplateArgumentLoc(TemplateArgument(TName),
2098 D->getDefaultArgument().getTemplateQualifierLoc(),
2099 D->getDefaultArgument().getTemplateNameLoc()),
2100 false);
2101 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002102 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002103
2104 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002105 // scope.
2106 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002107
Douglas Gregor38fee962009-11-11 16:58:32 +00002108 return Param;
2109}
2110
Douglas Gregore0b28662009-11-17 06:07:40 +00002111Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002112 // Using directives are never dependent (and never contain any types or
2113 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002114
Douglas Gregore0b28662009-11-17 06:07:40 +00002115 UsingDirectiveDecl *Inst
2116 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002117 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002118 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002119 D->getIdentLocation(),
2120 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002121 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002122
2123 // Add the using directive to its declaration context
2124 // only if this is not a function or method.
2125 if (!Owner->isFunctionOrMethod())
2126 Owner->addDecl(Inst);
2127
Douglas Gregore0b28662009-11-17 06:07:40 +00002128 return Inst;
2129}
2130
John McCallb96ec562009-12-04 22:46:56 +00002131Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002132
2133 // The nested name specifier may be dependent, for example
2134 // template <typename T> struct t {
2135 // struct s1 { T f1(); };
2136 // struct s2 : s1 { using s1::f1; };
2137 // };
2138 // template struct t<int>;
2139 // Here, in using s1::f1, s1 refers to t<T>::s1;
2140 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002141 NestedNameSpecifierLoc QualifierLoc
2142 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2143 TemplateArgs);
2144 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002145 return nullptr;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002146
2147 // The name info is non-dependent, so no transformation
2148 // is required.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002149 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCallb96ec562009-12-04 22:46:56 +00002150
John McCall84d87672009-12-10 09:41:52 +00002151 // We only need to do redeclaration lookups if we're in a class
2152 // scope (in fact, it's not really even possible in non-class
2153 // scopes).
2154 bool CheckRedeclaration = Owner->isRecord();
2155
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002156 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2157 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002158
John McCallb96ec562009-12-04 22:46:56 +00002159 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002160 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002161 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002162 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002163 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002164
Douglas Gregor0499ab62011-02-25 15:54:31 +00002165 CXXScopeSpec SS;
2166 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002167 if (CheckRedeclaration) {
2168 Prev.setHideTags(false);
2169 SemaRef.LookupQualifiedName(Prev, Owner);
2170
2171 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002172 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2173 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002174 D->getLocation(), Prev))
2175 NewUD->setInvalidDecl();
2176
2177 }
2178
2179 if (!NewUD->isInvalidDecl() &&
Richard Smith7ad0b882014-04-02 21:44:35 +00002180 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00002181 D->getLocation()))
2182 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002183
John McCallb96ec562009-12-04 22:46:56 +00002184 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2185 NewUD->setAccess(D->getAccess());
2186 Owner->addDecl(NewUD);
2187
John McCall84d87672009-12-10 09:41:52 +00002188 // Don't process the shadow decls for an invalid decl.
2189 if (NewUD->isInvalidDecl())
2190 return NewUD;
2191
Richard Smith23d55872012-04-02 01:30:27 +00002192 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00002193 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
Richard Smith23d55872012-04-02 01:30:27 +00002194 return NewUD;
2195 }
2196
John McCalla1d85502009-12-22 22:26:37 +00002197 bool isFunctionScope = Owner->isFunctionOrMethod();
2198
John McCall84d87672009-12-10 09:41:52 +00002199 // Process the shadow decls.
Aaron Ballman91cdc282014-03-13 18:07:29 +00002200 for (auto *Shadow : D->shadows()) {
John McCall84d87672009-12-10 09:41:52 +00002201 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002202 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2203 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002204 if (!InstTarget)
Craig Topperc3ec1492014-05-26 06:22:03 +00002205 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00002206
Craig Topperc3ec1492014-05-26 06:22:03 +00002207 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00002208 if (CheckRedeclaration) {
2209 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2210 continue;
2211 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2212 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2213 Shadow->getLocation(), OldPrev, TemplateArgs));
2214 }
John McCall84d87672009-12-10 09:41:52 +00002215
Richard Smithfd8634a2013-10-23 02:17:46 +00002216 UsingShadowDecl *InstShadow =
Craig Topperc3ec1492014-05-26 06:22:03 +00002217 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2218 PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002219 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002220
2221 if (isFunctionScope)
2222 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002223 }
John McCallb96ec562009-12-04 22:46:56 +00002224
2225 return NewUD;
2226}
2227
2228Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002229 // Ignore these; we handle them in bulk when processing the UsingDecl.
Craig Topperc3ec1492014-05-26 06:22:03 +00002230 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00002231}
2232
John McCalle61f2ba2009-11-18 02:36:19 +00002233Decl * TemplateDeclInstantiator
2234 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002235 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002236 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002237 TemplateArgs);
2238 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002239 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002240
Anders Carlsson4bd78752009-08-28 15:18:15 +00002241 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002242 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002243
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002244 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Kramerd81108f2012-11-14 15:08:31 +00002245 // Hence, no transformation is required for it.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002246 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002247 NamedDecl *UD =
Craig Topperc3ec1492014-05-26 06:22:03 +00002248 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2249 D->getUsingLoc(), SS, NameInfo, nullptr,
John McCalle61f2ba2009-11-18 02:36:19 +00002250 /*instantiation*/ true,
2251 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor6044d692010-05-19 17:02:24 +00002252 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002253 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2254
John McCalle61f2ba2009-11-18 02:36:19 +00002255 return UD;
2256}
2257
2258Decl * TemplateDeclInstantiator
2259 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002260 NestedNameSpecifierLoc QualifierLoc
2261 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2262 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002263 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002264
John McCalle61f2ba2009-11-18 02:36:19 +00002265 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002266 SS.Adopt(QualifierLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00002267
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002268 DeclarationNameInfo NameInfo
2269 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2270
John McCalle61f2ba2009-11-18 02:36:19 +00002271 NamedDecl *UD =
Craig Topperc3ec1492014-05-26 06:22:03 +00002272 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2273 D->getUsingLoc(), SS, NameInfo, nullptr,
John McCalle61f2ba2009-11-18 02:36:19 +00002274 /*instantiation*/ true,
2275 /*typename*/ false, SourceLocation());
Douglas Gregor6044d692010-05-19 17:02:24 +00002276 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002277 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2278
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002279 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00002280}
2281
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002282
2283Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2284 ClassScopeFunctionSpecializationDecl *Decl) {
2285 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber7b5a7162012-06-25 17:21:05 +00002286 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
Craig Topperc3ec1492014-05-26 06:22:03 +00002287 nullptr, true));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002288
2289 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2290 Sema::ForRedeclaration);
2291
Nico Weber7b5a7162012-06-25 17:21:05 +00002292 TemplateArgumentListInfo TemplateArgs;
Craig Topperc3ec1492014-05-26 06:22:03 +00002293 TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
Nico Weber7b5a7162012-06-25 17:21:05 +00002294 if (Decl->hasExplicitTemplateArgs()) {
2295 TemplateArgs = Decl->templateArgs();
2296 TemplateArgsPtr = &TemplateArgs;
2297 }
2298
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002299 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002300 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2301 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002302 NewFD->setInvalidDecl();
2303 return NewFD;
2304 }
2305
2306 // Associate the specialization with the pattern.
2307 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2308 assert(Specialization && "Class scope Specialization is null");
2309 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2310
2311 return NewFD;
2312}
2313
Alexey Bataeva769e072013-03-22 06:34:35 +00002314Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2315 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002316 SmallVector<Expr *, 5> Vars;
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002317 for (auto *I : D->varlists()) {
2318 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).take();
Alexey Bataeva769e072013-03-22 06:34:35 +00002319 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002320 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002321 }
2322
2323 OMPThreadPrivateDecl *TD =
2324 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2325
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002326 TD->setAccess(AS_public);
2327 Owner->addDecl(TD);
2328
Alexey Bataeva769e072013-03-22 06:34:35 +00002329 return TD;
2330}
2331
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002332Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002333 return VisitFunctionDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002334}
2335
2336Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002337 return VisitCXXMethodDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002338}
2339
2340Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2341 llvm_unreachable("There are only CXXRecordDecls in C++");
2342}
2343
2344Decl *
2345TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2346 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00002347 // As a MS extension, we permit class-scope explicit specialization
2348 // of member class templates.
2349 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2350 assert(ClassTemplate->getDeclContext()->isRecord() &&
2351 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2352 "can only instantiate an explicit specialization "
2353 "for a member class template");
2354
2355 // Lookup the already-instantiated declaration in the instantiation
2356 // of the class template. FIXME: Diagnose or assert if this fails?
2357 DeclContext::lookup_result Found
2358 = Owner->lookup(ClassTemplate->getDeclName());
2359 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00002360 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002361 ClassTemplateDecl *InstClassTemplate
2362 = dyn_cast<ClassTemplateDecl>(Found.front());
2363 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00002364 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002365
2366 // Substitute into the template arguments of the class template explicit
2367 // specialization.
2368 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2369 castAs<TemplateSpecializationTypeLoc>();
2370 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2371 Loc.getRAngleLoc());
2372 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2373 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2374 ArgLocs.push_back(Loc.getArgLoc(I));
2375 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2376 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002377 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002378
2379 // Check that the template argument list is well-formed for this
2380 // class template.
2381 SmallVector<TemplateArgument, 4> Converted;
2382 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2383 D->getLocation(),
2384 InstTemplateArgs,
2385 false,
2386 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002387 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002388
2389 // Figure out where to insert this class template explicit specialization
2390 // in the member template's set of class template explicit specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002391 void *InsertPos = nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002392 ClassTemplateSpecializationDecl *PrevDecl =
2393 InstClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2394 InsertPos);
2395
2396 // Check whether we've already seen a conflicting instantiation of this
2397 // declaration (for instance, if there was a prior implicit instantiation).
2398 bool Ignored;
2399 if (PrevDecl &&
2400 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2401 D->getSpecializationKind(),
2402 PrevDecl,
2403 PrevDecl->getSpecializationKind(),
2404 PrevDecl->getPointOfInstantiation(),
2405 Ignored))
Craig Topperc3ec1492014-05-26 06:22:03 +00002406 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002407
2408 // If PrevDecl was a definition and D is also a definition, diagnose.
2409 // This happens in cases like:
2410 //
2411 // template<typename T, typename U>
2412 // struct Outer {
2413 // template<typename X> struct Inner;
2414 // template<> struct Inner<T> {};
2415 // template<> struct Inner<U> {};
2416 // };
2417 //
2418 // Outer<int, int> outer; // error: the explicit specializations of Inner
2419 // // have the same signature.
2420 if (PrevDecl && PrevDecl->getDefinition() &&
2421 D->isThisDeclarationADefinition()) {
2422 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2423 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2424 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00002425 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002426 }
2427
2428 // Create the class template partial specialization declaration.
2429 ClassTemplateSpecializationDecl *InstD
2430 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2431 D->getTagKind(),
2432 Owner,
2433 D->getLocStart(),
2434 D->getLocation(),
2435 InstClassTemplate,
2436 Converted.data(),
2437 Converted.size(),
2438 PrevDecl);
2439
2440 // Add this partial specialization to the set of class template partial
2441 // specializations.
2442 if (!PrevDecl)
2443 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2444
2445 // Substitute the nested name specifier, if any.
2446 if (SubstQualifier(D, InstD))
Craig Topperc3ec1492014-05-26 06:22:03 +00002447 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002448
2449 // Build the canonical type that describes the converted template
2450 // arguments of the class template explicit specialization.
2451 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2452 TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2453 SemaRef.Context.getRecordType(InstD));
2454
2455 // Build the fully-sugared type for this class template
2456 // specialization as the user wrote in the specialization
2457 // itself. This means that we'll pretty-print the type retrieved
2458 // from the specialization's declaration the way that the user
2459 // actually wrote the specialization, rather than formatting the
2460 // name based on the "canonical" representation used to store the
2461 // template arguments in the specialization.
2462 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2463 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2464 CanonType);
2465
2466 InstD->setAccess(D->getAccess());
2467 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2468 InstD->setSpecializationKind(D->getSpecializationKind());
2469 InstD->setTypeAsWritten(WrittenTy);
2470 InstD->setExternLoc(D->getExternLoc());
2471 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2472
2473 Owner->addDecl(InstD);
2474
2475 // Instantiate the members of the class-scope explicit specialization eagerly.
2476 // We don't have support for lazy instantiation of an explicit specialization
2477 // yet, and MSVC eagerly instantiates in this case.
2478 if (D->isThisDeclarationADefinition() &&
2479 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2480 TSK_ImplicitInstantiation,
2481 /*Complain=*/true))
Craig Topperc3ec1492014-05-26 06:22:03 +00002482 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002483
2484 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002485}
2486
Larisse Voufo39a1e502013-08-06 01:03:05 +00002487Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2488 VarTemplateSpecializationDecl *D) {
2489
2490 TemplateArgumentListInfo VarTemplateArgsInfo;
2491 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2492 assert(VarTemplate &&
2493 "A template specialization without specialized template?");
2494
2495 // Substitute the current template arguments.
2496 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2497 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2498 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2499
2500 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2501 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002502 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002503
2504 // Check that the template argument list is well-formed for this template.
2505 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002506 if (SemaRef.CheckTemplateArgumentList(
2507 VarTemplate, VarTemplate->getLocStart(),
2508 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002509 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002510 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002511
2512 // Find the variable template specialization declaration that
2513 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002514 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002515 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2516 Converted.data(), Converted.size(), InsertPos))
2517 // If we already have a variable template specialization, return it.
2518 return VarSpec;
2519
2520 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2521 VarTemplateArgsInfo, Converted);
2522}
2523
2524Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2525 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2526 const TemplateArgumentListInfo &TemplateArgsInfo,
Richard Smith8809a0c2013-09-27 20:14:12 +00002527 llvm::ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002528
2529 // If this is the variable for an anonymous struct or union,
2530 // instantiate the anonymous struct/union type first.
2531 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2532 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2533 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +00002534 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002535
2536 // Do substitution on the type of the declaration
2537 TypeSourceInfo *DI =
2538 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2539 D->getTypeSpecStartLoc(), D->getDeclName());
2540 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002541 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002542
2543 if (DI->getType()->isFunctionType()) {
2544 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2545 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00002546 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002547 }
2548
2549 // Build the instantiated declaration
2550 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2551 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2552 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2553 Converted.size());
2554 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00002555 if (InsertPos)
2556 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002557
2558 // Substitute the nested name specifier, if any.
2559 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +00002560 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002561
2562 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00002563 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002564
2565 return Var;
2566}
2567
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002568Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2569 llvm_unreachable("@defs is not supported in Objective-C++");
2570}
2571
2572Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2573 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2574 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2575 DiagnosticsEngine::Error,
2576 "cannot instantiate %0 yet");
2577 SemaRef.Diag(D->getLocation(), DiagID)
2578 << D->getDeclKindName();
2579
Craig Topperc3ec1492014-05-26 06:22:03 +00002580 return nullptr;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002581}
2582
2583Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2584 llvm_unreachable("Unexpected decl");
2585}
2586
John McCall76d824f2009-08-25 22:02:44 +00002587Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002588 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00002589 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00002590 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00002591 return nullptr;
Douglas Gregor71ad4772010-02-16 19:28:15 +00002592
Douglas Gregord7e7a512009-03-17 21:15:40 +00002593 return Instantiator.Visit(D);
2594}
2595
John McCall87a44eb2009-08-20 01:44:21 +00002596/// \brief Instantiates a nested template parameter list in the current
2597/// instantiation context.
2598///
2599/// \param L The parameter list to instantiate
2600///
2601/// \returns NULL if there was an error
2602TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00002603TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00002604 // Get errors for all the parameters before bailing out.
2605 bool Invalid = false;
2606
2607 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002608 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00002609 ParamVector Params;
2610 Params.reserve(N);
2611 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2612 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002613 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00002614 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00002615 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00002616 }
2617
2618 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00002619 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +00002620 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00002621
2622 TemplateParameterList *InstL
2623 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2624 L->getLAngleLoc(), &Params.front(), N,
2625 L->getRAngleLoc());
2626 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00002627}
John McCall87a44eb2009-08-20 01:44:21 +00002628
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002629/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002630/// specialization.
2631///
2632/// \param ClassTemplate the (instantiated) class template that is partially
2633// specialized by the instantiation of \p PartialSpec.
2634///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002635/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002636/// specialization that we are instantiating.
2637///
Douglas Gregor869853e2010-11-10 19:44:59 +00002638/// \returns The instantiated partial specialization, if successful; otherwise,
2639/// NULL to indicate an error.
2640ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00002641TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2642 ClassTemplateDecl *ClassTemplate,
2643 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00002644 // Create a local instantiation scope for this class template partial
2645 // specialization, which will contain the instantiations of the template
2646 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00002647 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002648
Douglas Gregor21610382009-10-29 00:04:11 +00002649 // Substitute into the template parameters of the class template partial
2650 // specialization.
2651 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2652 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2653 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002654 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002655
Douglas Gregor21610382009-10-29 00:04:11 +00002656 // Substitute into the template arguments of the class template partial
2657 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002658 const ASTTemplateArgumentListInfo *TemplArgInfo
2659 = PartialSpec->getTemplateArgsAsWritten();
2660 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2661 TemplArgInfo->RAngleLoc);
2662 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2663 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002664 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002665 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002666
Douglas Gregor21610382009-10-29 00:04:11 +00002667 // Check that the template argument list is well-formed for this
2668 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002669 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002670 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00002671 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002672 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002673 false,
2674 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002675 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002676
2677 // Figure out where to insert this class template partial specialization
2678 // in the member template's set of class template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002679 void *InsertPos = nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002680 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002681 = ClassTemplate->findPartialSpecialization(Converted.data(),
2682 Converted.size(), InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002683
Douglas Gregor21610382009-10-29 00:04:11 +00002684 // Build the canonical type that describes the converted template
2685 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002686 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00002687 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002688 Converted.data(),
2689 Converted.size());
Douglas Gregor21610382009-10-29 00:04:11 +00002690
2691 // Build the fully-sugared type for this class template
2692 // specialization as the user wrote in the specialization
2693 // itself. This means that we'll pretty-print the type retrieved
2694 // from the specialization's declaration the way that the user
2695 // actually wrote the specialization, rather than formatting the
2696 // name based on the "canonical" representation used to store the
2697 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00002698 TypeSourceInfo *WrittenTy
2699 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2700 TemplateName(ClassTemplate),
2701 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002702 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002703 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002704
Douglas Gregor21610382009-10-29 00:04:11 +00002705 if (PrevDecl) {
2706 // We've already seen a partial specialization with the same template
2707 // parameters and template arguments. This can happen, for example, when
2708 // substituting the outer template arguments ends up causing two
2709 // class template partial specializations of a member class template
2710 // to have identical forms, e.g.,
2711 //
2712 // template<typename T, typename U>
2713 // struct Outer {
2714 // template<typename X, typename Y> struct Inner;
2715 // template<typename Y> struct Inner<T, Y>;
2716 // template<typename Y> struct Inner<U, Y>;
2717 // };
2718 //
2719 // Outer<int, int> outer; // error: the partial specializations of Inner
2720 // // have the same signature.
2721 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00002722 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00002723 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2724 << SemaRef.Context.getTypeDeclType(PrevDecl);
Craig Topperc3ec1492014-05-26 06:22:03 +00002725 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002726 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002727
2728
Douglas Gregor21610382009-10-29 00:04:11 +00002729 // Create the class template partial specialization declaration.
2730 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002731 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002732 PartialSpec->getTagKind(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002733 Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002734 PartialSpec->getLocStart(),
2735 PartialSpec->getLocation(),
Douglas Gregor21610382009-10-29 00:04:11 +00002736 InstParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002737 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002738 Converted.data(),
2739 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00002740 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00002741 CanonType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002742 nullptr);
John McCall3e11ebe2010-03-15 10:12:16 +00002743 // Substitute the nested name specifier, if any.
2744 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00002745 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00002746
Douglas Gregor21610382009-10-29 00:04:11 +00002747 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00002748 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002749
Douglas Gregor21610382009-10-29 00:04:11 +00002750 // Add this partial specialization to the set of class template partial
2751 // specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002752 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
2753 /*InsertPos=*/nullptr);
Douglas Gregor869853e2010-11-10 19:44:59 +00002754 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00002755}
2756
Larisse Voufo39a1e502013-08-06 01:03:05 +00002757/// \brief Instantiate the declaration of a variable template partial
2758/// specialization.
2759///
2760/// \param VarTemplate the (instantiated) variable template that is partially
2761/// specialized by the instantiation of \p PartialSpec.
2762///
2763/// \param PartialSpec the (uninstantiated) variable template partial
2764/// specialization that we are instantiating.
2765///
2766/// \returns The instantiated partial specialization, if successful; otherwise,
2767/// NULL to indicate an error.
2768VarTemplatePartialSpecializationDecl *
2769TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2770 VarTemplateDecl *VarTemplate,
2771 VarTemplatePartialSpecializationDecl *PartialSpec) {
2772 // Create a local instantiation scope for this variable template partial
2773 // specialization, which will contain the instantiations of the template
2774 // parameters.
2775 LocalInstantiationScope Scope(SemaRef);
2776
2777 // Substitute into the template parameters of the variable template partial
2778 // specialization.
2779 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2780 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2781 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002782 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002783
2784 // Substitute into the template arguments of the variable template partial
2785 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002786 const ASTTemplateArgumentListInfo *TemplArgInfo
2787 = PartialSpec->getTemplateArgsAsWritten();
2788 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2789 TemplArgInfo->RAngleLoc);
2790 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2791 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002792 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002793 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002794
2795 // Check that the template argument list is well-formed for this
2796 // class template.
2797 SmallVector<TemplateArgument, 4> Converted;
2798 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2799 InstTemplateArgs, false, Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002800 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002801
2802 // Figure out where to insert this variable template partial specialization
2803 // in the member template's set of variable template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002804 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002805 VarTemplateSpecializationDecl *PrevDecl =
2806 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2807 InsertPos);
2808
2809 // Build the canonical type that describes the converted template
2810 // arguments of the variable template partial specialization.
2811 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2812 TemplateName(VarTemplate), Converted.data(), Converted.size());
2813
2814 // Build the fully-sugared type for this variable template
2815 // specialization as the user wrote in the specialization
2816 // itself. This means that we'll pretty-print the type retrieved
2817 // from the specialization's declaration the way that the user
2818 // actually wrote the specialization, rather than formatting the
2819 // name based on the "canonical" representation used to store the
2820 // template arguments in the specialization.
2821 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2822 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2823 CanonType);
2824
2825 if (PrevDecl) {
2826 // We've already seen a partial specialization with the same template
2827 // parameters and template arguments. This can happen, for example, when
2828 // substituting the outer template arguments ends up causing two
2829 // variable template partial specializations of a member variable template
2830 // to have identical forms, e.g.,
2831 //
2832 // template<typename T, typename U>
2833 // struct Outer {
2834 // template<typename X, typename Y> pair<X,Y> p;
2835 // template<typename Y> pair<T, Y> p;
2836 // template<typename Y> pair<U, Y> p;
2837 // };
2838 //
2839 // Outer<int, int> outer; // error: the partial specializations of Inner
2840 // // have the same signature.
2841 SemaRef.Diag(PartialSpec->getLocation(),
2842 diag::err_var_partial_spec_redeclared)
2843 << WrittenTy->getType();
2844 SemaRef.Diag(PrevDecl->getLocation(),
2845 diag::note_var_prev_partial_spec_here);
Craig Topperc3ec1492014-05-26 06:22:03 +00002846 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002847 }
2848
2849 // Do substitution on the type of the declaration
2850 TypeSourceInfo *DI = SemaRef.SubstType(
2851 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2852 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2853 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002854 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002855
2856 if (DI->getType()->isFunctionType()) {
2857 SemaRef.Diag(PartialSpec->getLocation(),
2858 diag::err_variable_instantiates_to_function)
2859 << PartialSpec->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00002860 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002861 }
2862
2863 // Create the variable template partial specialization declaration.
2864 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2865 VarTemplatePartialSpecializationDecl::Create(
2866 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2867 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2868 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smithb2f61b42013-08-22 23:27:37 +00002869 Converted.size(), InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002870
2871 // Substitute the nested name specifier, if any.
2872 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00002873 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002874
2875 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2876 InstPartialSpec->setTypeAsWritten(WrittenTy);
2877
Larisse Voufo39a1e502013-08-06 01:03:05 +00002878 // Add this partial specialization to the set of variable template partial
2879 // specializations. The instantiation of the initializer is not necessary.
Craig Topperc3ec1492014-05-26 06:22:03 +00002880 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002881
Larisse Voufo4cda4612013-08-22 00:28:27 +00002882 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00002883 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002884
Larisse Voufo39a1e502013-08-06 01:03:05 +00002885 return InstPartialSpec;
2886}
2887
John McCall58f10c32010-03-11 09:03:00 +00002888TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00002889TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002890 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00002891 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2892 assert(OldTInfo && "substituting function without type source info");
2893 assert(Params.empty() && "parameter vector is non-empty at start");
Craig Topperc3ec1492014-05-26 06:22:03 +00002894
2895 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002896 unsigned ThisTypeQuals = 0;
2897 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002898 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00002899 ThisTypeQuals = Method->getTypeQualifiers();
2900 }
2901
John McCallb29f78f2010-04-09 17:38:44 +00002902 TypeSourceInfo *NewTInfo
2903 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2904 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002905 D->getDeclName(),
2906 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00002907 if (!NewTInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00002908 return nullptr;
Douglas Gregor21342092009-03-24 00:38:23 +00002909
Reid Klecknera09e44c2013-07-31 21:00:18 +00002910 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2911 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2912 if (NewTInfo != OldTInfo) {
2913 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00002914 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00002915 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00002916 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002917 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00002918 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002919 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00002920 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2921
David Blaikie05785d12013-02-20 22:23:23 +00002922 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00002923 if (OldParam->isParameterPack())
2924 NumArgumentsInExpansion =
2925 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2926 TemplateArgs);
2927 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002928 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00002929 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002930 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00002931 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00002932 Scope->InstantiatedLocal(OldParam, NewParam);
2933 } else {
2934 // Parameter pack expansion: make the instantiation an argument pack.
2935 Scope->MakeInstantiatedLocalArgPack(OldParam);
2936 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002937 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00002938 Params.push_back(NewParam);
2939 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2940 }
Douglas Gregorf3010112011-01-07 16:43:16 +00002941 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002942 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002943 } else {
2944 // The function type itself was not dependent and therefore no
2945 // substitution occurred. However, we still need to instantiate
2946 // the function parameters themselves.
2947 const FunctionProtoType *OldProto =
2948 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002949 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
2950 ++i) {
2951 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00002952 if (!OldParam) {
2953 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00002954 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00002955 continue;
2956 }
2957
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002958 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00002959 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002960 if (!Parm)
Craig Topperc3ec1492014-05-26 06:22:03 +00002961 return nullptr;
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002962 Params.push_back(Parm);
2963 }
Douglas Gregor940bca72010-04-12 07:48:19 +00002964 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002965 } else {
2966 // If the type of this function, after ignoring parentheses, is not
2967 // *directly* a function type, then we're instantiating a function that
2968 // was declared via a typedef or with attributes, e.g.,
2969 //
2970 // typedef int functype(int, int);
2971 // functype func;
2972 // int __cdecl meth(int, int);
2973 //
2974 // In this case, we'll just go instantiate the ParmVarDecls that we
2975 // synthesized in the method declaration.
2976 SmallVector<QualType, 4> ParamTypes;
2977 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2978 D->getNumParams(), TemplateArgs, ParamTypes,
2979 &Params))
Craig Topperc3ec1492014-05-26 06:22:03 +00002980 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00002981 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002982
John McCall58f10c32010-03-11 09:03:00 +00002983 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00002984}
2985
Richard Smithf623c962012-04-17 00:58:00 +00002986/// Introduce the instantiated function parameters into the local
2987/// instantiation scope, and set the parameter names to those used
2988/// in the template.
2989static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2990 const FunctionDecl *PatternDecl,
2991 LocalInstantiationScope &Scope,
2992 const MultiLevelTemplateArgumentList &TemplateArgs) {
2993 unsigned FParamIdx = 0;
2994 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2995 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2996 if (!PatternParam->isParameterPack()) {
2997 // Simple case: not a parameter pack.
2998 assert(FParamIdx < Function->getNumParams());
2999 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smithaae40582014-03-13 00:28:45 +00003000 // If the parameter's type is not dependent, update it to match the type
3001 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3002 // the pattern's type here. If the type is dependent, they can't differ,
3003 // per core issue 1668.
3004 // FIXME: Updating the type to work around this is at best fragile.
3005 if (!PatternDecl->getType()->isDependentType())
3006 FunctionParam->setType(PatternParam->getType());
3007
Richard Smithf623c962012-04-17 00:58:00 +00003008 FunctionParam->setDeclName(PatternParam->getDeclName());
3009 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3010 ++FParamIdx;
3011 continue;
3012 }
3013
3014 // Expand the parameter pack.
3015 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003016 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003017 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00003018 assert(NumArgumentsInExpansion &&
3019 "should only be called when all template arguments are known");
3020 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00003021 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smithaae40582014-03-13 00:28:45 +00003022 if (!PatternDecl->getType()->isDependentType())
3023 FunctionParam->setType(PatternParam->getType());
3024
Richard Smithf623c962012-04-17 00:58:00 +00003025 FunctionParam->setDeclName(PatternParam->getDeclName());
3026 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3027 ++FParamIdx;
3028 }
3029 }
3030}
3031
3032static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
3033 const FunctionProtoType *Proto,
3034 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smithd3729422012-04-19 00:08:28 +00003035 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
3036
Richard Smithf623c962012-04-17 00:58:00 +00003037 // C++11 [expr.prim.general]p3:
3038 // If a declaration declares a member function or member function
3039 // template of a class X, the expression this is a prvalue of type
3040 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3041 // and the end of the function-definition, member-declarator, or
3042 // declarator.
Craig Topperc3ec1492014-05-26 06:22:03 +00003043 CXXRecordDecl *ThisContext = nullptr;
Richard Smithf623c962012-04-17 00:58:00 +00003044 unsigned ThisTypeQuals = 0;
3045 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
3046 ThisContext = Method->getParent();
3047 ThisTypeQuals = Method->getTypeQualifiers();
3048 }
3049 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003050 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithf623c962012-04-17 00:58:00 +00003051
3052 // The function has an exception specification or a "noreturn"
3053 // attribute. Substitute into each of the exception types.
3054 SmallVector<QualType, 4> Exceptions;
3055 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
3056 // FIXME: Poor location information!
3057 if (const PackExpansionType *PackExpansion
3058 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
3059 // We have a pack expansion. Instantiate it.
3060 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3061 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
3062 Unexpanded);
3063 assert(!Unexpanded.empty() &&
3064 "Pack expansion without parameter packs?");
3065
3066 bool Expand = false;
3067 bool RetainExpansion = false;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003068 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithf623c962012-04-17 00:58:00 +00003069 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
3070 SourceRange(),
3071 Unexpanded,
3072 TemplateArgs,
3073 Expand,
3074 RetainExpansion,
3075 NumExpansions))
3076 break;
3077
3078 if (!Expand) {
3079 // We can't expand this pack expansion into separate arguments yet;
3080 // just substitute into the pattern and create a new pack expansion
3081 // type.
3082 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3083 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3084 TemplateArgs,
3085 New->getLocation(), New->getDeclName());
3086 if (T.isNull())
3087 break;
3088
3089 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
3090 Exceptions.push_back(T);
3091 continue;
3092 }
3093
3094 // Substitute into the pack expansion pattern for each template
3095 bool Invalid = false;
3096 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
3097 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
3098
3099 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3100 TemplateArgs,
3101 New->getLocation(), New->getDeclName());
3102 if (T.isNull()) {
3103 Invalid = true;
3104 break;
3105 }
3106
3107 Exceptions.push_back(T);
3108 }
3109
3110 if (Invalid)
3111 break;
3112
3113 continue;
3114 }
3115
3116 QualType T
3117 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
3118 New->getLocation(), New->getDeclName());
3119 if (T.isNull() ||
3120 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
3121 continue;
3122
3123 Exceptions.push_back(T);
3124 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003125 Expr *NoexceptExpr = nullptr;
Richard Smithf623c962012-04-17 00:58:00 +00003126 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
3127 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3128 Sema::ConstantEvaluated);
3129 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
3130 if (E.isUsable())
3131 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
3132
3133 if (E.isUsable()) {
3134 NoexceptExpr = E.take();
3135 if (!NoexceptExpr->isTypeDependent() &&
3136 !NoexceptExpr->isValueDependent())
Douglas Gregore2b37442012-05-04 22:38:52 +00003137 NoexceptExpr
3138 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003139 nullptr, diag::err_noexcept_needs_constant_expression,
Douglas Gregore2b37442012-05-04 22:38:52 +00003140 /*AllowFold*/ false).take();
Richard Smithf623c962012-04-17 00:58:00 +00003141 }
3142 }
3143
Richard Smith564417a2014-03-20 21:47:22 +00003144 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithf623c962012-04-17 00:58:00 +00003145 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
3146 EPI.NumExceptions = Exceptions.size();
3147 EPI.Exceptions = Exceptions.data();
3148 EPI.NoexceptExpr = NoexceptExpr;
3149
Richard Smith564417a2014-03-20 21:47:22 +00003150 SemaRef.UpdateExceptionSpec(New, EPI);
Richard Smithf623c962012-04-17 00:58:00 +00003151}
3152
3153void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3154 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003155 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3156 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003157 return;
3158
3159 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3160 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003161 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003162 // We hit the instantiation depth limit. Clear the exception specification
3163 // so that our callers don't have to cope with EST_Uninstantiated.
Richard Smith564417a2014-03-20 21:47:22 +00003164 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003165 EPI.ExceptionSpecType = EST_None;
Richard Smith564417a2014-03-20 21:47:22 +00003166 UpdateExceptionSpec(Decl, EPI);
Richard Smithf623c962012-04-17 00:58:00 +00003167 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003168 }
Richard Smithf623c962012-04-17 00:58:00 +00003169
3170 // Enter the scope of this instantiation. We don't use
3171 // PushDeclContext because we don't have a scope.
3172 Sema::ContextRAII savedContext(*this, Decl);
3173 LocalInstantiationScope Scope(*this);
3174
3175 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003176 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
Richard Smithf623c962012-04-17 00:58:00 +00003177
Richard Smithd3729422012-04-19 00:08:28 +00003178 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3179 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003180
Richard Smithd3729422012-04-19 00:08:28 +00003181 ::InstantiateExceptionSpec(*this, Decl,
3182 Template->getType()->castAs<FunctionProtoType>(),
3183 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003184}
3185
Mike Stump11289f42009-09-09 15:08:12 +00003186/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003187/// declaration (New) from the corresponding fields of its template (Tmpl).
3188///
3189/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003190bool
3191TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003192 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003193 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003194 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003195
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003196 // Forward the mangling number from the template to the instantiated decl.
3197 SemaRef.Context.setManglingNumber(New,
3198 SemaRef.Context.getManglingNumber(Tmpl));
3199
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003200 // If we are performing substituting explicitly-specified template arguments
3201 // or deduced template arguments into a function template and we reach this
3202 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003203 // to keeping the new function template specialization. We therefore
3204 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003205 // into a template instantiation for this specific function template
3206 // specialization, which is not a SFINAE context, so that we diagnose any
3207 // further errors in the declaration itself.
3208 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3209 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3210 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3211 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003212 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003213 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003214 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003215 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003216 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003217 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003218 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003219 }
3220 }
Mike Stump11289f42009-09-09 15:08:12 +00003221
Douglas Gregor049bdca2009-12-08 17:45:32 +00003222 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3223 assert(Proto && "Function template without prototype?");
3224
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003225 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003226 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003227
Richard Smithf623c962012-04-17 00:58:00 +00003228 // DR1330: In C++11, defer instantiation of a non-trivial
3229 // exception specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003230 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithf623c962012-04-17 00:58:00 +00003231 EPI.ExceptionSpecType != EST_None &&
3232 EPI.ExceptionSpecType != EST_DynamicNone &&
3233 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smithd3729422012-04-19 00:08:28 +00003234 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3235 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3236 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003237 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3238 if (EPI.ExceptionSpecType == EST_Unevaluated)
3239 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003240
Richard Smithf623c962012-04-17 00:58:00 +00003241 // Mark the function has having an uninstantiated exception specification.
3242 const FunctionProtoType *NewProto
3243 = New->getType()->getAs<FunctionProtoType>();
3244 assert(NewProto && "Template instantiation without function prototype?");
3245 EPI = NewProto->getExtProtoInfo();
Richard Smith185be182013-04-10 05:48:59 +00003246 EPI.ExceptionSpecType = NewEST;
Richard Smithf623c962012-04-17 00:58:00 +00003247 EPI.ExceptionSpecDecl = New;
Richard Smithd3729422012-04-19 00:08:28 +00003248 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003249 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003250 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003251 } else {
3252 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3253 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003254 }
3255
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003256 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003257 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003258 Tmpl->isDefined(Definition);
3259
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003260 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3261 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003262
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003263 return false;
3264}
3265
Douglas Gregor21342092009-03-24 00:38:23 +00003266/// \brief Initializes common fields of an instantiated method
3267/// declaration (New) from the corresponding fields of its template
3268/// (Tmpl).
3269///
3270/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003271bool
3272TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003273 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003274 if (InitFunctionInstantiation(New, Tmpl))
3275 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003276
Douglas Gregor21342092009-03-24 00:38:23 +00003277 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003278 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003279 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003280
Douglas Gregor21342092009-03-24 00:38:23 +00003281 // FIXME: New needs a pointer to Tmpl
3282 return false;
3283}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003284
3285/// \brief Instantiate the definition of the given function from its
3286/// template.
3287///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003288/// \param PointOfInstantiation the point at which the instantiation was
3289/// required. Note that this is not precisely a "point of instantiation"
3290/// for the function, but it's close.
3291///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003292/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003293/// function template specialization or member function of a class template
3294/// specialization.
3295///
3296/// \param Recursive if true, recursively instantiates any functions that
3297/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003298///
3299/// \param DefinitionRequired if true, then we are performing an explicit
3300/// instantiation where the body of the function is required. Complain if
3301/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003302void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003303 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003304 bool Recursive,
3305 bool DefinitionRequired) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003306 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00003307 return;
3308
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003309 // Never instantiate an explicit specialization except if it is a class scope
3310 // explicit specialization.
3311 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3312 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003313 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003314
Douglas Gregor24c332b2009-05-14 21:06:31 +00003315 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003316 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003317 assert(PatternDecl && "instantiating a non-template");
3318
3319 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3320 assert(PatternDecl && "template definition is not a template");
3321 if (!Pattern) {
3322 // Try to find a defaulted definition
3323 PatternDecl->isDefined(PatternDecl);
Alexis Hunt92a0adf2011-05-25 22:02:25 +00003324 }
Alexis Hunt23f6b832011-05-27 20:00:14 +00003325 assert(PatternDecl && "template definition is not a template");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003326
Francois Pichet1c229c02011-04-22 22:18:13 +00003327 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003328 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003329 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00003330 PendingInstantiations.push_back(
3331 std::make_pair(Function, PointOfInstantiation));
3332 return;
3333 }
3334
David Majnemerf0a84f22013-08-16 08:29:13 +00003335 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003336 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003337 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003338 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003339 // FIXME: Optimize to allow individual templates to be deserialized.
3340 if (PatternDecl->isFromASTFile())
3341 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3342
3343 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3344 assert(LPT && "missing LateParsedTemplate");
3345 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet1c229c02011-04-22 22:18:13 +00003346 Pattern = PatternDecl->getBody(PatternDecl);
3347 }
3348
Alexis Hunt23f6b832011-05-27 20:00:14 +00003349 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003350 if (DefinitionRequired) {
3351 if (Function->getPrimaryTemplate())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003352 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003353 diag::err_explicit_instantiation_undefined_func_template)
3354 << Function->getPrimaryTemplate();
3355 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003356 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003357 diag::err_explicit_instantiation_undefined_member)
3358 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003359
Douglas Gregora8b89d22009-10-15 14:05:49 +00003360 if (PatternDecl)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003361 Diag(PatternDecl->getLocation(),
Douglas Gregora8b89d22009-10-15 14:05:49 +00003362 diag::note_explicit_instantiation_here);
Douglas Gregorfd7224f2010-05-17 17:57:54 +00003363 Function->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003364 } else if (Function->getTemplateSpecializationKind()
3365 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003366 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003367 std::make_pair(Function, PointOfInstantiation));
Douglas Gregora8b89d22009-10-15 14:05:49 +00003368 }
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003369
Douglas Gregor24c332b2009-05-14 21:06:31 +00003370 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00003371 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003372
Richard Smith2a7d4812013-05-04 07:00:32 +00003373 // C++1y [temp.explicit]p10:
3374 // Except for inline functions, declarations with types deduced from their
3375 // initializer or return value, and class template specializations, other
3376 // explicit instantiation declarations have the effect of suppressing the
3377 // implicit instantiation of the entity to which they refer.
Alp Toker314cc812014-01-25 16:55:45 +00003378 if (Function->getTemplateSpecializationKind() ==
3379 TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003380 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00003381 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003382 return;
Mike Stump11289f42009-09-09 15:08:12 +00003383
Richard Smithf3814ad2013-01-25 00:08:28 +00003384 if (PatternDecl->isInlined())
3385 Function->setImplicitlyInline();
3386
Douglas Gregor85673582009-05-18 17:01:57 +00003387 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003388 if (Inst.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003389 return;
3390
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00003391 // Copy the inner loc start from the pattern.
3392 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3393
Douglas Gregordda7ced2009-06-30 17:20:14 +00003394 // If we're performing recursive template instantiation, create our own
3395 // queue of pending implicit instantiations that we will instantiate later,
3396 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003397 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003398 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003399 SavePendingLocalImplicitInstantiationsRAII
3400 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003401 if (Recursive) {
3402 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003403 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003404 }
Mike Stump11289f42009-09-09 15:08:12 +00003405
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003406 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00003407 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00003408
Douglas Gregorb4850462009-05-14 23:26:13 +00003409 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003410 // recorded, unless we're actually a member function within a local
3411 // class, in which case we need to merge our results with the parent
3412 // scope (of the enclosing function).
3413 bool MergeWithParentScope = false;
3414 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3415 MergeWithParentScope = Rec->isLocalClass();
3416
3417 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00003418
Richard Smithbd305122012-12-11 01:14:52 +00003419 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003420 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00003421 else {
Craig Topperc3ec1492014-05-26 06:22:03 +00003422 ActOnStartOfFunctionDef(nullptr, Function);
Richard Smithbd305122012-12-11 01:14:52 +00003423
3424 // Enter the scope of this instantiation. We don't use
3425 // PushDeclContext because we don't have a scope.
3426 Sema::ContextRAII savedContext(*this, Function);
3427
3428 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003429 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
Richard Smithbd305122012-12-11 01:14:52 +00003430
3431 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3432 TemplateArgs);
3433
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003434 // If this is a constructor, instantiate the member initializers.
3435 if (const CXXConstructorDecl *Ctor =
3436 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3437 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3438 TemplateArgs);
3439 }
3440
3441 // Instantiate the function body.
3442 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3443
3444 if (Body.isInvalid())
3445 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003446
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003447 ActOnFinishFunctionBody(Function, Body.get(),
3448 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00003449
3450 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3451
Richard Smithd28ac5b2014-03-22 23:33:22 +00003452 if (auto *Listener = getASTMutationListener())
3453 Listener->FunctionDefinitionInstantiated(Function);
Richard Smith0ac1b8f2014-03-22 01:43:32 +00003454
Richard Smithbd305122012-12-11 01:14:52 +00003455 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00003456 }
3457
Douglas Gregor28ad4b52009-05-26 20:50:29 +00003458 DeclGroupRef DG(Function);
3459 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003460
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003461 // This class may have local implicit instantiations that need to be
3462 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003463 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003464 Scope.Exit();
3465
Douglas Gregordda7ced2009-06-30 17:20:14 +00003466 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003467 // Define any pending vtables.
3468 DefineUsedVTables();
3469
Douglas Gregordda7ced2009-06-30 17:20:14 +00003470 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003471 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003472 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003473
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003474 // Restore the set of pending vtables.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003475 assert(VTableUses.empty() &&
3476 "VTableUses should be empty before it is discarded.");
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003477 VTableUses.swap(SavedVTableUses);
3478
Douglas Gregordda7ced2009-06-30 17:20:14 +00003479 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003480 assert(PendingInstantiations.empty() &&
3481 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003482 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregordda7ced2009-06-30 17:20:14 +00003483 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003484}
3485
Larisse Voufo39a1e502013-08-06 01:03:05 +00003486VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3487 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3488 const TemplateArgumentList &TemplateArgList,
3489 const TemplateArgumentListInfo &TemplateArgsInfo,
3490 SmallVectorImpl<TemplateArgument> &Converted,
3491 SourceLocation PointOfInstantiation, void *InsertPos,
3492 LateInstantiatedAttrVec *LateAttrs,
3493 LocalInstantiationScope *StartingScope) {
3494 if (FromVar->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00003495 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003496
3497 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003498 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003499 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003500
3501 MultiLevelTemplateArgumentList TemplateArgLists;
3502 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3503
Richard Smith8809a0c2013-09-27 20:14:12 +00003504 // Instantiate the first declaration of the variable template: for a partial
3505 // specialization of a static data member template, the first declaration may
3506 // or may not be the declaration in the class; if it's in the class, we want
3507 // to instantiate a member in the class (a declaration), and if it's outside,
3508 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00003509 //
3510 // If we're instantiating an explicitly-specialized member template or member
3511 // partial specialization, don't do this. The member specialization completely
3512 // replaces the original declaration in this case.
3513 bool IsMemberSpec = false;
3514 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3515 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3516 IsMemberSpec = PartialSpec->isMemberSpecialization();
3517 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3518 IsMemberSpec = FromTemplate->isMemberSpecialization();
3519 if (!IsMemberSpec)
3520 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00003521
Manuel Klimek5843add2013-09-30 13:29:01 +00003522 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3523 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3524 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003525
3526 // TODO: Set LateAttrs and StartingScope ...
3527
3528 return cast_or_null<VarTemplateSpecializationDecl>(
3529 Instantiator.VisitVarTemplateSpecializationDecl(
3530 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3531}
3532
3533/// \brief Instantiates a variable template specialization by completing it
3534/// with appropriate type information and initializer.
3535VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3536 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3537 const MultiLevelTemplateArgumentList &TemplateArgs) {
3538
3539 // Do substitution on the type of the declaration
3540 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00003541 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003542 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3543 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003544 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003545
3546 // Update the type of this variable template specialization.
3547 VarSpec->setType(DI->getType());
3548
3549 // Instantiate the initializer.
3550 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3551
3552 return VarSpec;
3553}
3554
3555/// BuildVariableInstantiation - Used after a new variable has been created.
3556/// Sets basic variable data and decides whether to postpone the
3557/// variable instantiation.
3558void Sema::BuildVariableInstantiation(
3559 VarDecl *NewVar, VarDecl *OldVar,
3560 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003561 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3562 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003563 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003564
Richard Smith541b38b2013-09-20 01:15:31 +00003565 // If we are instantiating a local extern declaration, the
3566 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003567 // If we are instantiating a static data member defined
3568 // out-of-line, the instantiation will have the same lexical
3569 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00003570 if (OldVar->isLocalExternDecl()) {
3571 NewVar->setLocalExternDecl();
3572 NewVar->setLexicalDeclContext(Owner);
3573 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003574 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3575 NewVar->setTSCSpec(OldVar->getTSCSpec());
3576 NewVar->setInitStyle(OldVar->getInitStyle());
3577 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3578 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00003579 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00003580 NewVar->setPreviousDeclInSameBlockScope(
3581 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003582 NewVar->setAccess(OldVar->getAccess());
3583
Richard Smith0b551192013-09-23 23:12:22 +00003584 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00003585 if (OldVar->isUsed(false))
3586 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003587 NewVar->setReferenced(OldVar->isReferenced());
3588 }
3589
David Majnemer50ce8352013-09-17 23:57:10 +00003590 // See if the old variable had a type-specifier that defined an anonymous tag.
3591 // If it did, mark the new variable as being the declarator for the new
3592 // anonymous tag.
3593 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3594 TagDecl *OldTag = OldTagType->getDecl();
3595 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3596 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3597 assert(!NewTag->hasNameForLinkage() &&
3598 !NewTag->hasDeclaratorForAnonDecl());
3599 NewTag->setDeclaratorForAnonDecl(NewVar);
3600 }
3601 }
3602
Larisse Voufo39a1e502013-08-06 01:03:05 +00003603 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3604
Richard Smith541b38b2013-09-20 01:15:31 +00003605 LookupResult Previous(
3606 *this, NewVar->getDeclName(), NewVar->getLocation(),
3607 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3608 : Sema::LookupOrdinaryName,
3609 Sema::ForRedeclaration);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003610
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00003611 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3612 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3613 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00003614 // We have a previous declaration. Use that one, so we merge with the
3615 // right type.
3616 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3617 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3618 Previous.addDecl(NewPrev);
3619 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3620 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003621 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003622 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003623
Richard Smith541b38b2013-09-20 01:15:31 +00003624 if (!InstantiatingVarTemplate) {
3625 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3626 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003627 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00003628 }
3629
3630 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003631 if (NewVar->getDeclContext()->isFunctionOrMethod())
3632 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3633 }
3634
3635 // Link instantiations of static data members back to the template from
3636 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003637 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003638 NewVar->setInstantiationOfStaticDataMember(OldVar,
3639 TSK_ImplicitInstantiation);
3640
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003641 // Forward the mangling number from the template to the instantiated decl.
3642 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00003643 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003644
Richard Smith8809a0c2013-09-27 20:14:12 +00003645 // Delay instantiation of the initializer for variable templates until a
Richard Smithd292b242014-03-16 01:00:40 +00003646 // definition of the variable is needed. We need it right away if the type
3647 // contains 'auto'.
3648 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3649 !InstantiatingVarTemplate) ||
3650 NewVar->getType()->isUndeducedType())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003651 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3652
3653 // Diagnose unused local variables with dependent types, where the diagnostic
3654 // will have been deferred.
3655 if (!NewVar->isInvalidDecl() &&
3656 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3657 OldVar->getType()->isDependentType())
3658 DiagnoseUnusedDecl(NewVar);
3659}
3660
3661/// \brief Instantiate the initializer of a variable.
3662void Sema::InstantiateVariableInitializer(
3663 VarDecl *Var, VarDecl *OldVar,
3664 const MultiLevelTemplateArgumentList &TemplateArgs) {
3665
3666 if (Var->getAnyInitializer())
3667 // We already have an initializer in the class.
3668 return;
3669
3670 if (OldVar->getInit()) {
3671 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3672 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3673 else
3674 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3675
3676 // Instantiate the initializer.
3677 ExprResult Init =
3678 SubstInitializer(OldVar->getInit(), TemplateArgs,
3679 OldVar->getInitStyle() == VarDecl::CallInit);
3680 if (!Init.isInvalid()) {
3681 bool TypeMayContainAuto = true;
3682 if (Init.get()) {
3683 bool DirectInit = OldVar->isDirectInit();
3684 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3685 } else
3686 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3687 } else {
3688 // FIXME: Not too happy about invalidating the declaration
3689 // because of a bogus initializer.
3690 Var->setInvalidDecl();
3691 }
3692
3693 PopExpressionEvaluationContext();
3694 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3695 !Var->isCXXForRangeDecl())
3696 ActOnUninitializedDecl(Var, false);
3697}
3698
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003699/// \brief Instantiate the definition of the given variable from its
3700/// template.
3701///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003702/// \param PointOfInstantiation the point at which the instantiation was
3703/// required. Note that this is not precisely a "point of instantiation"
3704/// for the function, but it's close.
3705///
3706/// \param Var the already-instantiated declaration of a static member
3707/// variable of a class template specialization.
3708///
3709/// \param Recursive if true, recursively instantiates any functions that
3710/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003711///
3712/// \param DefinitionRequired if true, then we are performing an explicit
3713/// instantiation where an out-of-line definition of the member variable
3714/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003715void Sema::InstantiateStaticDataMemberDefinition(
3716 SourceLocation PointOfInstantiation,
3717 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003718 bool Recursive,
3719 bool DefinitionRequired) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003720 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3721 DefinitionRequired);
3722}
3723
3724void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3725 VarDecl *Var, bool Recursive,
3726 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003727 if (Var->isInvalidDecl())
3728 return;
Mike Stump11289f42009-09-09 15:08:12 +00003729
Larisse Voufo39a1e502013-08-06 01:03:05 +00003730 VarTemplateSpecializationDecl *VarSpec =
3731 dyn_cast<VarTemplateSpecializationDecl>(Var);
Craig Topperc3ec1492014-05-26 06:22:03 +00003732 VarDecl *PatternDecl = nullptr, *Def = nullptr;
Richard Smith8809a0c2013-09-27 20:14:12 +00003733 MultiLevelTemplateArgumentList TemplateArgs =
3734 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00003735
Larisse Voufo39a1e502013-08-06 01:03:05 +00003736 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003737 // If this is a variable template specialization, make sure that it is
3738 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003739 bool InstantiationDependent = false;
3740 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3741 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3742 "Only instantiate variable template specializations that are "
3743 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00003744 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003745
Richard Smith8809a0c2013-09-27 20:14:12 +00003746 // Find the variable initialization that we'll be substituting. If the
3747 // pattern was instantiated from a member template, look back further to
3748 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003749 assert(VarSpec->getSpecializedTemplate() &&
3750 "Specialization without specialized template?");
3751 llvm::PointerUnion<VarTemplateDecl *,
3752 VarTemplatePartialSpecializationDecl *> PatternPtr =
3753 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003754 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003755 VarTemplatePartialSpecializationDecl *Tmpl =
3756 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3757 while (VarTemplatePartialSpecializationDecl *From =
3758 Tmpl->getInstantiatedFromMember()) {
3759 if (Tmpl->isMemberSpecialization())
3760 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003761
Richard Smith8809a0c2013-09-27 20:14:12 +00003762 Tmpl = From;
3763 }
3764 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003765 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00003766 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3767 while (VarTemplateDecl *From =
3768 Tmpl->getInstantiatedFromMemberTemplate()) {
3769 if (Tmpl->isMemberSpecialization())
3770 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003771
Richard Smith8809a0c2013-09-27 20:14:12 +00003772 Tmpl = From;
3773 }
3774 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003775 }
Richard Smith8809a0c2013-09-27 20:14:12 +00003776
3777 // If this is a static data member template, there might be an
3778 // uninstantiated initializer on the declaration. If so, instantiate
3779 // it now.
3780 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00003781 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00003782 !Var->hasInit()) {
3783 // FIXME: Factor out the duplicated instantiation context setup/tear down
3784 // code here.
3785 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003786 if (Inst.isInvalid())
Richard Smith8809a0c2013-09-27 20:14:12 +00003787 return;
3788
3789 // If we're performing recursive template instantiation, create our own
3790 // queue of pending implicit instantiations that we will instantiate
3791 // later, while we're still within our own instantiation context.
3792 SmallVector<VTableUse, 16> SavedVTableUses;
3793 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3794 if (Recursive) {
3795 VTableUses.swap(SavedVTableUses);
3796 PendingInstantiations.swap(SavedPendingInstantiations);
3797 }
3798
3799 LocalInstantiationScope Local(*this);
3800
3801 // Enter the scope of this instantiation. We don't use
3802 // PushDeclContext because we don't have a scope.
3803 ContextRAII PreviousContext(*this, Var->getDeclContext());
3804 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3805 PreviousContext.pop();
3806
3807 // FIXME: Need to inform the ASTConsumer that we instantiated the
3808 // initializer?
3809
3810 // This variable may have local implicit instantiations that need to be
3811 // instantiated within this scope.
3812 PerformPendingInstantiations(/*LocalOnly=*/true);
3813
3814 Local.Exit();
3815
3816 if (Recursive) {
3817 // Define any newly required vtables.
3818 DefineUsedVTables();
3819
3820 // Instantiate any pending implicit instantiations found during the
3821 // instantiation of this template.
3822 PerformPendingInstantiations();
3823
3824 // Restore the set of pending vtables.
3825 assert(VTableUses.empty() &&
3826 "VTableUses should be empty before it is discarded.");
3827 VTableUses.swap(SavedVTableUses);
3828
3829 // Restore the set of pending implicit instantiations.
3830 assert(PendingInstantiations.empty() &&
3831 "PendingInstantiations should be empty before it is discarded.");
3832 PendingInstantiations.swap(SavedPendingInstantiations);
3833 }
3834 }
3835
3836 // Find actual definition
3837 Def = PatternDecl->getDefinition(getASTContext());
3838 } else {
3839 // If this is a static data member, find its out-of-line definition.
3840 assert(Var->isStaticDataMember() && "not a static data member?");
3841 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3842
3843 assert(PatternDecl && "data member was not instantiated from a template?");
3844 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3845 Def = PatternDecl->getOutOfLineDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003846 }
3847
Richard Smith8809a0c2013-09-27 20:14:12 +00003848 // If we don't have a definition of the variable template, we won't perform
3849 // any instantiation. Rather, we rely on the user to instantiate this
3850 // definition (or provide a specialization for it) in another translation
3851 // unit.
3852 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003853 if (DefinitionRequired) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003854 if (VarSpec)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003855 Diag(PointOfInstantiation,
Richard Smith8809a0c2013-09-27 20:14:12 +00003856 diag::err_explicit_instantiation_undefined_var_template) << Var;
3857 else
Larisse Voufo39a1e502013-08-06 01:03:05 +00003858 Diag(PointOfInstantiation,
3859 diag::err_explicit_instantiation_undefined_member)
Richard Smith8809a0c2013-09-27 20:14:12 +00003860 << 2 << Var->getDeclName() << Var->getDeclContext();
3861 Diag(PatternDecl->getLocation(),
3862 diag::note_explicit_instantiation_here);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003863 if (VarSpec)
3864 Var->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003865 } else if (Var->getTemplateSpecializationKind()
3866 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003867 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003868 std::make_pair(Var, PointOfInstantiation));
3869 }
3870
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003871 return;
3872 }
3873
Rafael Espindola189fa742012-03-05 10:54:55 +00003874 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3875
Douglas Gregor86d142a2009-10-08 07:24:58 +00003876 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00003877 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003878 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003879
Larisse Voufo39a1e502013-08-06 01:03:05 +00003880 // C++11 [temp.explicit]p10:
3881 // Except for inline functions, [...] explicit instantiation declarations
3882 // have the effect of suppressing the implicit instantiation of the entity
3883 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00003884 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003885 return;
Mike Stump11289f42009-09-09 15:08:12 +00003886
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003887 // Make sure to pass the instantiated variable to the consumer at the end.
3888 struct PassToConsumerRAII {
3889 ASTConsumer &Consumer;
3890 VarDecl *Var;
3891
3892 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3893 : Consumer(Consumer), Var(Var) { }
3894
3895 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00003896 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003897 }
3898 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003899
Richard Smith8809a0c2013-09-27 20:14:12 +00003900 // If we already have a definition, we're done.
3901 if (VarDecl *Def = Var->getDefinition()) {
3902 // We may be explicitly instantiating something we've already implicitly
3903 // instantiated.
3904 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3905 PointOfInstantiation);
3906 return;
Nick Lewyckya995a472012-04-04 02:38:36 +00003907 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00003908
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003909 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003910 if (Inst.isInvalid())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003911 return;
Mike Stump11289f42009-09-09 15:08:12 +00003912
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003913 // If we're performing recursive template instantiation, create our own
3914 // queue of pending implicit instantiations that we will instantiate later,
3915 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003916 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003917 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003918 SavePendingLocalImplicitInstantiationsRAII
3919 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003920 if (Recursive) {
3921 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003922 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003923 }
Mike Stump11289f42009-09-09 15:08:12 +00003924
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003925 // Enter the scope of this instantiation. We don't use
3926 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003927 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00003928 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00003929
Larisse Voufo39a1e502013-08-06 01:03:05 +00003930 VarDecl *OldVar = Var;
3931 if (!VarSpec)
3932 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00003933 TemplateArgs));
3934 else if (Var->isStaticDataMember() &&
3935 Var->getLexicalDeclContext()->isRecord()) {
3936 // We need to instantiate the definition of a static data member template,
3937 // and all we have is the in-class declaration of it. Instantiate a separate
3938 // declaration of the definition.
3939 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3940 TemplateArgs);
3941 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
Craig Topperc3ec1492014-05-26 06:22:03 +00003942 VarSpec->getSpecializedTemplate(), Def, nullptr,
Richard Smith8809a0c2013-09-27 20:14:12 +00003943 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3944 if (Var) {
3945 llvm::PointerUnion<VarTemplateDecl *,
3946 VarTemplatePartialSpecializationDecl *> PatternPtr =
3947 VarSpec->getSpecializedTemplateOrPartial();
3948 if (VarTemplatePartialSpecializationDecl *Partial =
3949 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3950 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3951 Partial, &VarSpec->getTemplateInstantiationArgs());
3952
3953 // Merge the definition with the declaration.
3954 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3955 LookupOrdinaryName, ForRedeclaration);
3956 R.addDecl(OldVar);
3957 MergeVarDecl(Var, R);
3958
3959 // Attach the initializer.
3960 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3961 }
3962 } else
3963 // Complete the existing variable's definition with an appropriately
3964 // substituted type and initializer.
3965 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003966
3967 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003968
3969 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003970 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00003971 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3972 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003973 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003974
3975 // This variable may have local implicit instantiations that need to be
3976 // instantiated within this scope.
3977 PerformPendingInstantiations(/*LocalOnly=*/true);
3978
Douglas Gregora86bc002012-02-16 21:36:18 +00003979 Local.Exit();
3980
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003981 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003982 // Define any newly required vtables.
3983 DefineUsedVTables();
3984
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003985 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003986 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003987 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003988
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003989 // Restore the set of pending vtables.
3990 assert(VTableUses.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003991 "VTableUses should be empty before it is discarded.");
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003992 VTableUses.swap(SavedVTableUses);
3993
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003994 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003995 assert(PendingInstantiations.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003996 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003997 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00003998 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003999}
Douglas Gregor51783312009-05-27 05:35:12 +00004000
Anders Carlsson70553942009-08-29 05:16:22 +00004001void
4002Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4003 const CXXConstructorDecl *Tmpl,
4004 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00004005
Richard Trieu9becef62011-09-09 03:18:59 +00004006 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00004007 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004008
Anders Carlsson70553942009-08-29 05:16:22 +00004009 // Instantiate all the initializers.
Aaron Ballman0ad78302014-03-13 17:34:31 +00004010 for (const auto *Init : Tmpl->inits()) {
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004011 // Only instantiate written initializers, let Sema re-construct implicit
4012 // ones.
4013 if (!Init->isWritten())
4014 continue;
4015
Douglas Gregor44e7df62011-01-04 00:32:56 +00004016 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004017
Douglas Gregor44e7df62011-01-04 00:32:56 +00004018 if (Init->isPackExpansion()) {
4019 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004020 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004021 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004022 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004023 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004024 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004025 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004026 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004027 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004028 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004029 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004030 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004031 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004032 NumExpansions)) {
4033 AnyErrors = true;
4034 New->setInvalidDecl();
4035 continue;
4036 }
4037 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004038
4039 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004040 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004041 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4042
4043 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004044 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4045 /*CXXDirectInit=*/true);
4046 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004047 AnyErrors = true;
4048 break;
4049 }
4050
4051 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004052 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004053 TemplateArgs,
4054 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004055 New->getDeclName());
4056 if (!BaseTInfo) {
4057 AnyErrors = true;
4058 break;
4059 }
4060
4061 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004062 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redla9351792012-02-11 23:51:47 +00004063 BaseTInfo, TempInit.take(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004064 New->getParent(),
4065 SourceLocation());
4066 if (NewInit.isInvalid()) {
4067 AnyErrors = true;
4068 break;
4069 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004070
Douglas Gregor44e7df62011-01-04 00:32:56 +00004071 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004072 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004073
Douglas Gregor44e7df62011-01-04 00:32:56 +00004074 continue;
4075 }
4076
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004077 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004078 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4079 /*CXXDirectInit=*/true);
4080 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004081 AnyErrors = true;
4082 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004083 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004084
Anders Carlsson70553942009-08-29 05:16:22 +00004085 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004086 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4087 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4088 TemplateArgs,
4089 Init->getSourceLocation(),
4090 New->getDeclName());
4091 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004092 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004093 New->setInvalidDecl();
4094 continue;
4095 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004096
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004097 if (Init->isBaseInitializer())
Sebastian Redla9351792012-02-11 23:51:47 +00004098 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004099 New->getParent(), EllipsisLoc);
4100 else
Sebastian Redla9351792012-02-11 23:51:47 +00004101 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004102 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004103 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004104 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004105 Init->getMemberLocation(),
4106 Init->getMember(),
4107 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004108 if (!Member) {
4109 AnyErrors = true;
4110 New->setInvalidDecl();
4111 continue;
4112 }
Mike Stump11289f42009-09-09 15:08:12 +00004113
Sebastian Redla9351792012-02-11 23:51:47 +00004114 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004115 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004116 } else if (Init->isIndirectMemberInitializer()) {
4117 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004118 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004119 Init->getMemberLocation(),
4120 Init->getIndirectMember(), TemplateArgs));
4121
Douglas Gregor55e6b312011-03-04 19:46:35 +00004122 if (!IndirectMember) {
4123 AnyErrors = true;
4124 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004125 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004126 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004127
Sebastian Redla9351792012-02-11 23:51:47 +00004128 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004129 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004130 }
4131
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004132 if (NewInit.isInvalid()) {
4133 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004134 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004135 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004136 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004137 }
4138 }
Mike Stump11289f42009-09-09 15:08:12 +00004139
Anders Carlsson70553942009-08-29 05:16:22 +00004140 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004141 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004142 /*FIXME: ColonLoc */
4143 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004144 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004145 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004146}
4147
John McCall59660882009-08-29 08:11:13 +00004148// TODO: this could be templated if the various decl types used the
4149// same method name.
4150static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4151 ClassTemplateDecl *Instance) {
4152 Pattern = Pattern->getCanonicalDecl();
4153
4154 do {
4155 Instance = Instance->getCanonicalDecl();
4156 if (Pattern == Instance) return true;
4157 Instance = Instance->getInstantiatedFromMemberTemplate();
4158 } while (Instance);
4159
4160 return false;
4161}
4162
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004163static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4164 FunctionTemplateDecl *Instance) {
4165 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004166
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004167 do {
4168 Instance = Instance->getCanonicalDecl();
4169 if (Pattern == Instance) return true;
4170 Instance = Instance->getInstantiatedFromMemberTemplate();
4171 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004172
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004173 return false;
4174}
4175
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004176static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004177isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4178 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004179 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004180 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4181 do {
4182 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4183 Instance->getCanonicalDecl());
4184 if (Pattern == Instance)
4185 return true;
4186 Instance = Instance->getInstantiatedFromMember();
4187 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004188
Douglas Gregor21610382009-10-29 00:04:11 +00004189 return false;
4190}
4191
John McCall59660882009-08-29 08:11:13 +00004192static bool isInstantiationOf(CXXRecordDecl *Pattern,
4193 CXXRecordDecl *Instance) {
4194 Pattern = Pattern->getCanonicalDecl();
4195
4196 do {
4197 Instance = Instance->getCanonicalDecl();
4198 if (Pattern == Instance) return true;
4199 Instance = Instance->getInstantiatedFromMemberClass();
4200 } while (Instance);
4201
4202 return false;
4203}
4204
4205static bool isInstantiationOf(FunctionDecl *Pattern,
4206 FunctionDecl *Instance) {
4207 Pattern = Pattern->getCanonicalDecl();
4208
4209 do {
4210 Instance = Instance->getCanonicalDecl();
4211 if (Pattern == Instance) return true;
4212 Instance = Instance->getInstantiatedFromMemberFunction();
4213 } while (Instance);
4214
4215 return false;
4216}
4217
4218static bool isInstantiationOf(EnumDecl *Pattern,
4219 EnumDecl *Instance) {
4220 Pattern = Pattern->getCanonicalDecl();
4221
4222 do {
4223 Instance = Instance->getCanonicalDecl();
4224 if (Pattern == Instance) return true;
4225 Instance = Instance->getInstantiatedFromMemberEnum();
4226 } while (Instance);
4227
4228 return false;
4229}
4230
John McCallb96ec562009-12-04 22:46:56 +00004231static bool isInstantiationOf(UsingShadowDecl *Pattern,
4232 UsingShadowDecl *Instance,
4233 ASTContext &C) {
4234 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4235}
4236
4237static bool isInstantiationOf(UsingDecl *Pattern,
4238 UsingDecl *Instance,
4239 ASTContext &C) {
4240 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4241}
4242
John McCalle61f2ba2009-11-18 02:36:19 +00004243static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4244 UsingDecl *Instance,
4245 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004246 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCalle61f2ba2009-11-18 02:36:19 +00004247}
4248
4249static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004250 UsingDecl *Instance,
4251 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004252 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004253}
4254
John McCall59660882009-08-29 08:11:13 +00004255static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4256 VarDecl *Instance) {
4257 assert(Instance->isStaticDataMember());
4258
4259 Pattern = Pattern->getCanonicalDecl();
4260
4261 do {
4262 Instance = Instance->getCanonicalDecl();
4263 if (Pattern == Instance) return true;
4264 Instance = Instance->getInstantiatedFromStaticDataMember();
4265 } while (Instance);
4266
4267 return false;
4268}
4269
John McCallb96ec562009-12-04 22:46:56 +00004270// Other is the prospective instantiation
4271// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004272static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004273 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004274 if (UnresolvedUsingTypenameDecl *UUD
4275 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4276 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4277 return isInstantiationOf(UUD, UD, Ctx);
4278 }
4279 }
4280
4281 if (UnresolvedUsingValueDecl *UUD
4282 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004283 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4284 return isInstantiationOf(UUD, UD, Ctx);
4285 }
4286 }
Douglas Gregor51783312009-05-27 05:35:12 +00004287
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004288 return false;
4289 }
Mike Stump11289f42009-09-09 15:08:12 +00004290
John McCall59660882009-08-29 08:11:13 +00004291 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4292 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004293
John McCall59660882009-08-29 08:11:13 +00004294 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4295 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004296
John McCall59660882009-08-29 08:11:13 +00004297 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4298 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004299
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004300 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004301 if (Var->isStaticDataMember())
4302 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4303
4304 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4305 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004306
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004307 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4308 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4309
Douglas Gregor21610382009-10-29 00:04:11 +00004310 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4311 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4312 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4313 PartialSpec);
4314
Anders Carlsson5da84842009-09-01 04:26:58 +00004315 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4316 if (!Field->getDeclName()) {
4317 // This is an unnamed field.
Mike Stump11289f42009-09-09 15:08:12 +00004318 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlsson5da84842009-09-01 04:26:58 +00004319 cast<FieldDecl>(D);
4320 }
4321 }
Mike Stump11289f42009-09-09 15:08:12 +00004322
John McCallb96ec562009-12-04 22:46:56 +00004323 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4324 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4325
4326 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4327 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4328
Douglas Gregor51783312009-05-27 05:35:12 +00004329 return D->getDeclName() && isa<NamedDecl>(Other) &&
4330 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4331}
4332
4333template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004334static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004335 NamedDecl *D,
4336 ForwardIterator first,
4337 ForwardIterator last) {
4338 for (; first != last; ++first)
4339 if (isInstantiationOf(Ctx, D, *first))
4340 return cast<NamedDecl>(*first);
4341
Craig Topperc3ec1492014-05-26 06:22:03 +00004342 return nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00004343}
4344
John McCallaa74a0c2009-08-28 07:59:38 +00004345/// \brief Finds the instantiation of the given declaration context
4346/// within the current instantiation.
4347///
4348/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004349DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004350 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004351 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004352 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00004353 return cast_or_null<DeclContext>(ID);
4354 } else return DC;
4355}
4356
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004357/// \brief Find the instantiation of the given declaration within the
4358/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004359///
4360/// This routine is intended to be used when \p D is a declaration
4361/// referenced from within a template, that needs to mapped into the
4362/// corresponding declaration within an instantiation. For example,
4363/// given:
4364///
4365/// \code
4366/// template<typename T>
4367/// struct X {
4368/// enum Kind {
4369/// KnownValue = sizeof(T)
4370/// };
4371///
4372/// bool getKind() const { return KnownValue; }
4373/// };
4374///
4375/// template struct X<int>;
4376/// \endcode
4377///
Serge Pavloved5fe902013-07-10 04:59:14 +00004378/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4379/// \p EnumConstantDecl for \p KnownValue (which refers to
4380/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4381/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4382/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004383NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00004384 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00004385 DeclContext *ParentDC = D->getDeclContext();
Faisal Vali2cba1332013-10-23 06:44:28 +00004386 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4387 // parameters (p below) can have their ParentDC set to the translation-unit
4388 // - thus we can not consistently check if the ParentDC of such a parameter
4389 // is Dependent or/and a FunctionOrMethod.
4390 // For e.g. this code, during Template argument deduction tries to
4391 // find an instantiated decl for (T y) when the ParentDC for y is
4392 // the translation unit.
4393 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00004394 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00004395 // Foo(baz);
4396 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4397 // it gets here, always has a FunctionOrMethod as its ParentDC??
4398 // For now:
4399 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4400 // whose type is not instantiation dependent, do nothing to the decl
4401 // - otherwise find its instantiated decl.
4402 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4403 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4404 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00004405 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00004406 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00004407 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4408 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004409 // D is a local of some kind. Look into the map of local
4410 // declarations to their instantiations.
Chris Lattner50c3c132011-02-17 19:47:42 +00004411 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4412 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4413 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004414
Chris Lattnercab02a62011-02-17 20:34:02 +00004415 if (Found) {
4416 if (Decl *FD = Found->dyn_cast<Decl *>())
4417 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004418
Richard Smithb15fe3a2012-09-12 00:56:43 +00004419 int PackIdx = ArgumentPackSubstitutionIndex;
4420 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattnercab02a62011-02-17 20:34:02 +00004421 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4422 }
4423
Serge Pavlov7cd8f602013-07-15 06:14:07 +00004424 // If we're performing a partial substitution during template argument
4425 // deduction, we may not have values for template parameters yet. They
4426 // just map to themselves.
4427 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4428 isa<TemplateTemplateParmDecl>(D))
4429 return D;
4430
Serge Pavlov074a5182013-08-10 12:00:21 +00004431 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00004432 return nullptr;
Serge Pavlov074a5182013-08-10 12:00:21 +00004433
Chris Lattnercab02a62011-02-17 20:34:02 +00004434 // If we didn't find the decl, then we must have a label decl that hasn't
4435 // been found yet. Lazily instantiate it and return it now.
4436 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004437
Chris Lattnercab02a62011-02-17 20:34:02 +00004438 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4439 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004440
Chris Lattnercab02a62011-02-17 20:34:02 +00004441 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4442 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004443 }
Douglas Gregor51783312009-05-27 05:35:12 +00004444
Larisse Voufo39a1e502013-08-06 01:03:05 +00004445 // For variable template specializations, update those that are still
4446 // type-dependent.
4447 if (VarTemplateSpecializationDecl *VarSpec =
4448 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4449 bool InstantiationDependent = false;
4450 const TemplateArgumentListInfo &VarTemplateArgs =
4451 VarSpec->getTemplateArgsInfo();
4452 if (TemplateSpecializationType::anyDependentTemplateArguments(
4453 VarTemplateArgs, InstantiationDependent))
4454 D = cast<NamedDecl>(
4455 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4456 return D;
4457 }
4458
Douglas Gregor64621e62009-09-16 18:34:49 +00004459 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4460 if (!Record->isDependentContext())
4461 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004462
Douglas Gregor4109afa2011-11-07 17:43:18 +00004463 // Determine whether this record is the "templated" declaration describing
4464 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00004465 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00004466 if (ClassTemplate)
4467 ClassTemplate = ClassTemplate->getCanonicalDecl();
4468 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4469 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4470 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004471
Douglas Gregor4109afa2011-11-07 17:43:18 +00004472 // Walk the current context to find either the record or an instantiation of
4473 // it.
4474 DeclContext *DC = CurContext;
4475 while (!DC->isFileContext()) {
4476 // If we're performing substitution while we're inside the template
4477 // definition, we'll find our own context. We're done.
4478 if (DC->Equals(Record))
4479 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004480
Douglas Gregor4109afa2011-11-07 17:43:18 +00004481 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4482 // Check whether we're in the process of instantiating a class template
4483 // specialization of the template we're mapping.
4484 if (ClassTemplateSpecializationDecl *InstSpec
4485 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4486 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4487 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4488 return InstRecord;
4489 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004490
Douglas Gregor4109afa2011-11-07 17:43:18 +00004491 // Check whether we're in the process of instantiating a member class.
4492 if (isInstantiationOf(Record, InstRecord))
4493 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00004494 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004495
Douglas Gregor4109afa2011-11-07 17:43:18 +00004496 // Move to the outer template scope.
4497 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4498 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4499 DC = FD->getLexicalDeclContext();
4500 continue;
4501 }
John McCall59660882009-08-29 08:11:13 +00004502 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004503
Douglas Gregor4109afa2011-11-07 17:43:18 +00004504 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00004505 }
Douglas Gregord225fa02010-02-05 22:40:03 +00004506
Douglas Gregor64621e62009-09-16 18:34:49 +00004507 // Fall through to deal with other dependent record types (e.g.,
4508 // anonymous unions in class templates).
4509 }
John McCall59660882009-08-29 08:11:13 +00004510
Douglas Gregor64621e62009-09-16 18:34:49 +00004511 if (!ParentDC->isDependentContext())
4512 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004513
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004514 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004515 if (!ParentDC)
Craig Topperc3ec1492014-05-26 06:22:03 +00004516 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004517
Douglas Gregor51783312009-05-27 05:35:12 +00004518 if (ParentDC != D->getDeclContext()) {
4519 // We performed some kind of instantiation in the parent context,
4520 // so now we need to look into the instantiated parent context to
4521 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004522
John McCalle78aac42010-03-10 03:28:59 +00004523 // If our context used to be dependent, we may need to instantiate
4524 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00004525 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00004526 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004527 if (!Spec->isDependentContext()) {
4528 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00004529 const RecordType *Tag = T->getAs<RecordType>();
4530 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00004531 if (Tag->isBeingDefined())
4532 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00004533 if (!Tag->isBeingDefined() &&
4534 RequireCompleteType(Loc, T, diag::err_incomplete_type))
Craig Topperc3ec1492014-05-26 06:22:03 +00004535 return nullptr;
Douglas Gregor25edf432010-11-05 23:22:45 +00004536
4537 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004538 }
4539 }
4540
Craig Topperc3ec1492014-05-26 06:22:03 +00004541 NamedDecl *Result = nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00004542 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004543 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00004544 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00004545 } else {
4546 // Since we don't have a name for the entity we're looking for,
4547 // our only option is to walk through all of the declarations to
4548 // find that name. This will occur in a few cases:
4549 //
4550 // - anonymous struct/union within a template
4551 // - unnamed class/struct/union/enum within a template
4552 //
4553 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00004554 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004555 ParentDC->decls_begin(),
4556 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00004557 }
Mike Stump11289f42009-09-09 15:08:12 +00004558
Douglas Gregor528ad932011-03-06 20:12:45 +00004559 if (!Result) {
4560 if (isa<UsingShadowDecl>(D)) {
4561 // UsingShadowDecls can instantiate to nothing because of using hiding.
4562 } else if (Diags.hasErrorOccurred()) {
4563 // We've already complained about something, so most likely this
4564 // declaration failed to instantiate. There's no point in complaining
4565 // further, since this is normal in invalid code.
4566 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004567 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00004568 // instantiated, and we haven't gotten around to instantiating this
4569 // member yet. This can happen when the code uses forward declarations
4570 // of member classes, and introduces ordering dependencies via
4571 // template instantiation.
4572 Diag(Loc, diag::err_member_not_yet_instantiated)
4573 << D->getDeclName()
4574 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4575 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00004576 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4577 // This enumeration constant was found when the template was defined,
4578 // but can't be found in the instantiation. This can happen if an
4579 // unscoped enumeration member is explicitly specialized.
4580 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4581 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4582 TemplateArgs));
4583 assert(Spec->getTemplateSpecializationKind() ==
4584 TSK_ExplicitSpecialization);
4585 Diag(Loc, diag::err_enumerator_does_not_exist)
4586 << D->getDeclName()
4587 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4588 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4589 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00004590 } else {
4591 // We should have found something, but didn't.
4592 llvm_unreachable("Unable to find instantiation of declaration!");
4593 }
4594 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004595
Douglas Gregor51783312009-05-27 05:35:12 +00004596 D = Result;
4597 }
4598
Douglas Gregor51783312009-05-27 05:35:12 +00004599 return D;
4600}
Douglas Gregor77b50e12009-06-22 23:06:13 +00004601
Mike Stump11289f42009-09-09 15:08:12 +00004602/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00004603/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00004604void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004605 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00004606 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004607 PendingImplicitInstantiation Inst;
4608
4609 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00004610 Inst = PendingInstantiations.front();
4611 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004612 } else {
4613 Inst = PendingLocalImplicitInstantiations.front();
4614 PendingLocalImplicitInstantiations.pop_front();
4615 }
Mike Stump11289f42009-09-09 15:08:12 +00004616
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004617 // Instantiate function definitions
4618 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallfaf5fb42010-08-26 23:41:50 +00004619 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4620 "instantiating function definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004621 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4622 TSK_ExplicitInstantiationDefinition;
4623 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4624 DefinitionRequired);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004625 continue;
4626 }
Mike Stump11289f42009-09-09 15:08:12 +00004627
Larisse Voufo39a1e502013-08-06 01:03:05 +00004628 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004629 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004630
4631 assert((Var->isStaticDataMember() ||
4632 isa<VarTemplateSpecializationDecl>(Var)) &&
4633 "Not a static data member, nor a variable template"
4634 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00004635
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004636 // Don't try to instantiate declarations if the most recent redeclaration
4637 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004638 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004639 continue;
4640
4641 // Check if the most recent declaration has changed the specialization kind
4642 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004643 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004644 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00004645 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004646 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004647 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004648 continue; // No longer need to instantiate this type.
4649 case TSK_ExplicitInstantiationDefinition:
4650 // We only need an instantiation if the pending instantiation *is* the
4651 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004652 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004653 case TSK_ImplicitInstantiation:
4654 break;
4655 }
4656
Larisse Voufo39a1e502013-08-06 01:03:05 +00004657 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4658 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004659 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4660 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004661
4662 // Instantiate static data member definitions or variable template
4663 // specializations.
4664 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4665 DefinitionRequired);
Douglas Gregor77b50e12009-06-22 23:06:13 +00004666 }
4667}
John McCallc62bb642010-03-24 05:22:00 +00004668
4669void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4670 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00004671 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00004672 switch (DD->getKind()) {
4673 case DependentDiagnostic::Access:
4674 HandleDependentAccessCheck(*DD, TemplateArgs);
4675 break;
4676 }
4677 }
4678}