blob: e9d95f2b2925ed0e1309b98c5ac1d5191beb609a [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())
Nikola Smiljanic01a75982014-05-29 10:55:11 +000082 S.AddAlignedAttr(Aligned->getLocation(), New, Result.getAs<Expr>(),
Richard Smith44c247f2013-02-22 08:32:16 +000083 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;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000141 Cond = Result.getAs<Expr>();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000142 }
143 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
144 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
145 if (Converted.isInvalid())
146 return;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000147 Cond = Converted.get();
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000148 }
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
Hans Wennborgc2b7f7a2014-08-24 00:12:36 +0000186 // Existing DLL attribute on the instantiation takes precedence.
187 if (TmplAttr->getKind() == attr::DLLExport ||
188 TmplAttr->getKind() == attr::DLLImport) {
189 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
190 continue;
191 }
192 }
193
Richard Smith44c247f2013-02-22 08:32:16 +0000194 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000195 if (TmplAttr->isLateParsed() && LateAttrs) {
196 // Late parsed attributes must be instantiated and attached after the
197 // enclosing class has been instantiated. See Sema::InstantiateClass.
Craig Topperc3ec1492014-05-26 06:22:03 +0000198 LocalInstantiationScope *Saved = nullptr;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000199 if (CurrentInstantiationScope)
200 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
201 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
202 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000203 // Allow 'this' within late-parsed attributes.
204 NamedDecl *ND = dyn_cast<NamedDecl>(New);
205 CXXRecordDecl *ThisContext =
206 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
207 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
208 ND && ND->isCXXInstanceMember());
209
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000210 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
211 *this, TemplateArgs);
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000212 if (NewAttr)
213 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000214 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000215 }
216}
217
Douglas Gregor8a655532009-03-25 15:45:12 +0000218Decl *
219TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000220 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000221}
222
223Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000224TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
225 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
226 D->getIdentifier());
227 Owner->addDecl(Inst);
228 return Inst;
229}
230
231Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000232TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000233 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000234}
235
John McCalld8d0d432010-02-16 06:53:13 +0000236Decl *
237TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
238 NamespaceAliasDecl *Inst
239 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
240 D->getNamespaceLoc(),
241 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000242 D->getIdentifier(),
243 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000244 D->getTargetNameLoc(),
245 D->getNamespace());
246 Owner->addDecl(Inst);
247 return Inst;
248}
249
Richard Smith3f1b5d02011-05-05 21:57:07 +0000250Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
251 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000252 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000253 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000254 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000255 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000256 DI = SemaRef.SubstType(DI, TemplateArgs,
257 D->getLocation(), D->getDeclName());
258 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000259 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000260 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000261 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000262 } else {
263 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000264 }
Mike Stump11289f42009-09-09 15:08:12 +0000265
Richard Smith2ddcbab2012-10-23 00:32:41 +0000266 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
267 // libstdc++ relies upon this bug in its implementation of common_type.
268 // If we happen to be processing that implementation, fake up the g++ ?:
269 // semantics. See LWG issue 2141 for more information on the bug.
270 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
271 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
272 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
273 DT->isReferenceType() &&
274 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
275 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
276 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
277 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
278 // Fold it to the (non-reference) type which g++ would have produced.
279 DI = SemaRef.Context.getTrivialTypeSourceInfo(
280 DI->getType().getNonReferenceType());
281
Douglas Gregord7e7a512009-03-17 21:15:40 +0000282 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000283 TypedefNameDecl *Typedef;
284 if (IsTypeAlias)
285 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
286 D->getLocation(), D->getIdentifier(), DI);
287 else
288 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
289 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000290 if (Invalid)
291 Typedef->setInvalidDecl();
292
John McCall04fcd0d2011-02-01 08:20:08 +0000293 // If the old typedef was the name for linkage purposes of an anonymous
294 // tag decl, re-establish that relationship for the new typedef.
295 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
296 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000297 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000298 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000299 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000300 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000301 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000302 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000303
Douglas Gregorec9fd132012-01-14 16:38:05 +0000304 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000305 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
306 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000307 if (!InstPrev)
Craig Topperc3ec1492014-05-26 06:22:03 +0000308 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000309
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000310 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
311
312 // If the typedef types are not identical, reject them.
313 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
314
Rafael Espindola8db352d2013-10-17 15:37:26 +0000315 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000316 }
317
John McCall6602bb12010-08-01 02:01:53 +0000318 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000319
John McCall401982f2010-01-20 21:53:11 +0000320 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000321
Douglas Gregord7e7a512009-03-17 21:15:40 +0000322 return Typedef;
323}
324
Richard Smithdda56e42011-04-15 14:24:37 +0000325Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000326 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
327 Owner->addDecl(Typedef);
328 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000329}
330
331Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000332 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
333 Owner->addDecl(Typedef);
334 return Typedef;
335}
336
337Decl *
338TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
339 // Create a local instantiation scope for this type alias template, which
340 // will contain the instantiations of the template parameters.
341 LocalInstantiationScope Scope(SemaRef);
342
343 TemplateParameterList *TempParams = D->getTemplateParameters();
344 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
345 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000346 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000347
348 TypeAliasDecl *Pattern = D->getTemplatedDecl();
349
Craig Topperc3ec1492014-05-26 06:22:03 +0000350 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000351 if (Pattern->getPreviousDecl()) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000352 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000353 if (!Found.empty()) {
354 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000355 }
356 }
357
358 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
359 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
360 if (!AliasInst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000361 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000362
363 TypeAliasTemplateDecl *Inst
364 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
365 D->getDeclName(), InstParams, AliasInst);
Richard Smith43ccec8e2014-08-26 03:52:16 +0000366 AliasInst->setDescribedAliasTemplate(Inst);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000367 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000368 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000369
370 Inst->setAccess(D->getAccess());
371
372 if (!PrevAliasTemplate)
373 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000374
Richard Smith3f1b5d02011-05-05 21:57:07 +0000375 Owner->addDecl(Inst);
376
377 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000378}
379
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000380Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000381 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000382}
383
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000384Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
385 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000386
Douglas Gregor04163182010-05-21 00:31:19 +0000387 // If this is the variable for an anonymous struct or union,
388 // instantiate the anonymous struct/union type first.
389 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
390 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
391 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +0000392 return nullptr;
Douglas Gregor04163182010-05-21 00:31:19 +0000393
John McCall76d824f2009-08-25 22:02:44 +0000394 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000395 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000396 TemplateArgs,
397 D->getTypeSpecStartLoc(),
398 D->getDeclName());
399 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +0000400 return nullptr;
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000401
Douglas Gregor61623342010-09-12 07:37:24 +0000402 if (DI->getType()->isFunctionType()) {
403 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
404 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000405 return nullptr;
Douglas Gregor61623342010-09-12 07:37:24 +0000406 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000407
Richard Smith541b38b2013-09-20 01:15:31 +0000408 DeclContext *DC = Owner;
409 if (D->isLocalExternDecl())
410 SemaRef.adjustContextForLocalExternDecl(DC);
411
Larisse Voufo39a1e502013-08-06 01:03:05 +0000412 // Build the instantiated declaration.
Richard Smith541b38b2013-09-20 01:15:31 +0000413 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000414 D->getLocation(), D->getIdentifier(),
Larisse Voufo39a1e502013-08-06 01:03:05 +0000415 DI->getType(), DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000416
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000417 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000418 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000419 SemaRef.inferObjCARCLifetime(Var))
420 Var->setInvalidDecl();
421
Larisse Voufo39a1e502013-08-06 01:03:05 +0000422 // Substitute the nested name specifier, if any.
423 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +0000424 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000425
Richard Smith541b38b2013-09-20 01:15:31 +0000426 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000427 StartingScope, InstantiatingVarTemplate);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000428
429 if (D->isNRVOVariable()) {
430 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
431 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
432 Var->setNRVOVariable(true);
433 }
434
Alexander Kornienko83a4e182014-05-27 21:29:22 +0000435 Var->setImplicit(D->isImplicit());
436
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000437 return Var;
438}
439
Abramo Bagnarad7340582010-06-05 05:09:32 +0000440Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
441 AccessSpecDecl* AD
442 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
443 D->getAccessSpecifierLoc(), D->getColonLoc());
444 Owner->addHiddenDecl(AD);
445 return AD;
446}
447
Douglas Gregord7e7a512009-03-17 21:15:40 +0000448Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
449 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000450 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000451 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000452 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000453 DI = SemaRef.SubstType(DI, TemplateArgs,
454 D->getLocation(), D->getDeclName());
455 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000456 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000457 Invalid = true;
458 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000459 // C++ [temp.arg.type]p3:
460 // If a declaration acquires a function type through a type
461 // dependent on a template-parameter and this causes a
462 // declaration that does not use the syntactic form of a
463 // function declarator to have function type, the program is
464 // ill-formed.
465 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000466 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000467 Invalid = true;
468 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000469 } else {
470 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000471 }
472
473 Expr *BitWidth = D->getBitWidth();
474 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +0000475 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000476 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000477 // The bit-width expression is a constant expression.
478 EnterExpressionEvaluationContext Unevaluated(SemaRef,
479 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000480
John McCalldadc5752010-08-24 06:29:42 +0000481 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000482 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000483 if (InstantiatedBitWidth.isInvalid()) {
484 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +0000485 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000486 } else
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000487 BitWidth = InstantiatedBitWidth.getAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000488 }
489
John McCall90459c52009-10-22 23:33:21 +0000490 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
491 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000492 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000493 D->getLocation(),
494 D->isMutable(),
495 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000496 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000497 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000498 D->getAccess(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000499 nullptr);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000500 if (!Field) {
501 cast<Decl>(Owner)->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +0000502 return nullptr;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000503 }
Mike Stump11289f42009-09-09 15:08:12 +0000504
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000505 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000506
Richard Smith848e1f12013-02-01 08:12:08 +0000507 if (Field->hasAttrs())
508 SemaRef.CheckAlignasUnderalignment(Field);
509
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000510 if (Invalid)
511 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000512
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000513 if (!Field->getDeclName()) {
514 // Keep track of where this decl came from.
515 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000516 }
Douglas Gregor04163182010-05-21 00:31:19 +0000517 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
518 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000519 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000520 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000521 }
Mike Stump11289f42009-09-09 15:08:12 +0000522
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000523 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000524 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000525 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000526
527 return Field;
528}
529
John McCall5e77d762013-04-16 07:28:30 +0000530Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
531 bool Invalid = false;
532 TypeSourceInfo *DI = D->getTypeSourceInfo();
533
534 if (DI->getType()->isVariablyModifiedType()) {
535 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +0000536 << D;
John McCall5e77d762013-04-16 07:28:30 +0000537 Invalid = true;
538 } else if (DI->getType()->isInstantiationDependentType()) {
539 DI = SemaRef.SubstType(DI, TemplateArgs,
540 D->getLocation(), D->getDeclName());
541 if (!DI) {
542 DI = D->getTypeSourceInfo();
543 Invalid = true;
544 } else if (DI->getType()->isFunctionType()) {
545 // C++ [temp.arg.type]p3:
546 // If a declaration acquires a function type through a type
547 // dependent on a template-parameter and this causes a
548 // declaration that does not use the syntactic form of a
549 // function declarator to have function type, the program is
550 // ill-formed.
551 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
552 << DI->getType();
553 Invalid = true;
554 }
555 } else {
556 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
557 }
558
Richard Smithf7981722013-11-22 09:01:48 +0000559 MSPropertyDecl *Property = MSPropertyDecl::Create(
560 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
561 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000562
563 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
564 StartingScope);
565
566 if (Invalid)
567 Property->setInvalidDecl();
568
569 Property->setAccess(D->getAccess());
570 Owner->addDecl(Property);
571
572 return Property;
573}
574
Francois Pichet783dd6e2010-11-21 06:08:52 +0000575Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
576 NamedDecl **NamedChain =
577 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
578
579 int i = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +0000580 for (auto *PI : D->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +0000581 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000582 TemplateArgs);
583 if (!Next)
Craig Topperc3ec1492014-05-26 06:22:03 +0000584 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000585
Douglas Gregor55e6b312011-03-04 19:46:35 +0000586 NamedChain[i++] = Next;
587 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000588
Francois Pichetdbafc192010-12-09 10:07:54 +0000589 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet783dd6e2010-11-21 06:08:52 +0000590 IndirectFieldDecl* IndirectField
591 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichetdbafc192010-12-09 10:07:54 +0000592 D->getIdentifier(), T,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000593 NamedChain, D->getChainingSize());
594
595
596 IndirectField->setImplicit(D->isImplicit());
597 IndirectField->setAccess(D->getAccess());
598 Owner->addDecl(IndirectField);
599 return IndirectField;
600}
601
John McCallaa74a0c2009-08-28 07:59:38 +0000602Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000603 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000604 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000605 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000606 TypeSourceInfo *InstTy;
607 // If this is an unsupported friend, don't bother substituting template
608 // arguments into it. The actual type referred to won't be used by any
609 // parts of Clang, and may not be valid for instantiating. Just use the
610 // same info for the instantiated friend.
611 if (D->isUnsupportedFriend()) {
612 InstTy = Ty;
613 } else {
614 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
615 D->getLocation(), DeclarationName());
616 }
617 if (!InstTy)
Craig Topperc3ec1492014-05-26 06:22:03 +0000618 return nullptr;
John McCallaa74a0c2009-08-28 07:59:38 +0000619
Richard Smitha31a89a2012-09-20 01:31:00 +0000620 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000621 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000622 if (!FD)
Craig Topperc3ec1492014-05-26 06:22:03 +0000623 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000624
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000625 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000626 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000627 Owner->addDecl(FD);
628 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000629 }
630
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000631 NamedDecl *ND = D->getFriendDecl();
632 assert(ND && "friend decl must be a decl or a type!");
633
John McCallb9c78482010-04-08 09:05:18 +0000634 // All of the Visit implementations for the various potential friend
635 // declarations have to be carefully written to work for friend
636 // objects, with the most important detail being that the target
637 // decl should almost certainly not be placed in Owner.
638 Decl *NewND = Visit(ND);
Craig Topperc3ec1492014-05-26 06:22:03 +0000639 if (!NewND) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000640
John McCallaa74a0c2009-08-28 07:59:38 +0000641 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000642 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000643 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000644 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000645 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000646 Owner->addDecl(FD);
647 return FD;
John McCall58de3582009-08-14 02:03:10 +0000648}
649
Douglas Gregord7e7a512009-03-17 21:15:40 +0000650Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
651 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000652
Richard Smith764d2fe2011-12-20 02:08:33 +0000653 // The expression in a static assertion is a constant expression.
654 EnterExpressionEvaluationContext Unevaluated(SemaRef,
655 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000656
John McCalldadc5752010-08-24 06:29:42 +0000657 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000658 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000659 if (InstantiatedAssertExpr.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +0000660 return nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000661
Richard Smithded9c2e2012-07-11 22:37:56 +0000662 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000663 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000664 D->getMessage(),
665 D->getRParenLoc(),
666 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000667}
668
669Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000670 EnumDecl *PrevDecl = nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +0000671 if (D->getPreviousDecl()) {
672 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
673 D->getPreviousDecl(),
674 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +0000675 if (!Prev) return nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +0000676 PrevDecl = cast<EnumDecl>(Prev);
677 }
678
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000679 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000680 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000681 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000682 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000683 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000684 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000685 // If we have type source information for the underlying type, it means it
686 // has been explicitly set by the user. Perform substitution on it before
687 // moving on.
688 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000689 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
690 DeclarationName());
691 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000692 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000693 else
694 Enum->setIntegerTypeSourceInfo(NewTI);
695 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000696 assert(!D->getIntegerType()->isDependentType()
697 && "Dependent type without type source info");
698 Enum->setIntegerType(D->getIntegerType());
699 }
700 }
701
John McCall811a0f52010-10-22 23:36:17 +0000702 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
703
Richard Smith4b38ded2012-03-14 23:13:10 +0000704 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000705 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +0000706 // Forward the mangling number from the template to the instantiated decl.
707 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
Craig Topperc3ec1492014-05-26 06:22:03 +0000708 if (SubstQualifier(D, Enum)) return nullptr;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000709 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +0000710
Richard Smith258a7442012-03-26 04:08:46 +0000711 EnumDecl *Def = D->getDefinition();
712 if (Def && Def != D) {
713 // If this is an out-of-line definition of an enum member template, check
714 // that the underlying types match in the instantiation of both
715 // declarations.
716 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
717 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
718 QualType DefnUnderlying =
719 SemaRef.SubstType(TI->getType(), TemplateArgs,
720 UnderlyingLoc, DeclarationName());
721 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
722 DefnUnderlying, Enum);
723 }
724 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000725
Richard Smith4b38ded2012-03-14 23:13:10 +0000726 // C++11 [temp.inst]p1: The implicit instantiation of a class template
727 // specialization causes the implicit instantiation of the declarations, but
728 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +0000729 //
730 // DR1484 clarifies that enumeration definitions inside of a template
731 // declaration aren't considered entities that can be separately instantiated
732 // from the rest of the entity they are declared inside of.
733 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
734 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +0000735 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +0000736 }
Richard Smith4b38ded2012-03-14 23:13:10 +0000737
738 return Enum;
739}
740
741void TemplateDeclInstantiator::InstantiateEnumDefinition(
742 EnumDecl *Enum, EnumDecl *Pattern) {
743 Enum->startDefinition();
744
Richard Smith7d137e32012-03-23 03:33:32 +0000745 // Update the location to refer to the definition.
746 Enum->setLocation(Pattern->getLocation());
747
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000748 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000749
Craig Topperc3ec1492014-05-26 06:22:03 +0000750 EnumConstantDecl *LastEnumConst = nullptr;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000751 for (auto *EC : Pattern->enumerators()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000752 // The specified value for the enumerator.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000753 ExprResult Value((Expr *)nullptr);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000754 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000755 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +0000756 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +0000757 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000758
John McCall76d824f2009-08-25 22:02:44 +0000759 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000760 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000761
762 // Drop the initial value and continue.
763 bool isInvalid = false;
764 if (Value.isInvalid()) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000765 Value = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000766 isInvalid = true;
767 }
768
Mike Stump11289f42009-09-09 15:08:12 +0000769 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +0000770 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
771 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +0000772 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000773
774 if (isInvalid) {
775 if (EnumConst)
776 EnumConst->setInvalidDecl();
777 Enum->setInvalidDecl();
778 }
779
780 if (EnumConst) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000781 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +0000782
John McCallf9b528c2010-01-23 22:37:59 +0000783 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000784 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +0000785 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000786 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000787
Richard Smith4b38ded2012-03-14 23:13:10 +0000788 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
789 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000790 // If the enumeration is within a function or method, record the enum
791 // constant as a local.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000792 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000793 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000794 }
795 }
Mike Stump11289f42009-09-09 15:08:12 +0000796
Richard Smith4b38ded2012-03-14 23:13:10 +0000797 // FIXME: Fixup LBraceLoc
798 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
799 Enum->getRBraceLoc(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +0000800 Enumerators,
Craig Topperc3ec1492014-05-26 06:22:03 +0000801 nullptr, nullptr);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000802}
803
Douglas Gregor9106b822009-03-25 15:04:13 +0000804Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000805 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +0000806}
807
John McCall87a44eb2009-08-20 01:44:21 +0000808Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000809 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
810
Douglas Gregor954de172009-10-31 17:21:17 +0000811 // Create a local instantiation scope for this class template, which
812 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +0000813 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +0000814 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000815 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000816 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000817 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +0000818
819 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +0000820
821 // Instantiate the qualifier. We have to do this first in case
822 // we're a friend declaration, because if we are then we need to put
823 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +0000824 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
825 if (QualifierLoc) {
826 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
827 TemplateArgs);
828 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +0000829 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000830 }
831
Craig Topperc3ec1492014-05-26 06:22:03 +0000832 CXXRecordDecl *PrevDecl = nullptr;
833 ClassTemplateDecl *PrevClassTemplate = nullptr;
John McCall598b4402010-03-25 06:39:04 +0000834
Douglas Gregorec9fd132012-01-14 16:38:05 +0000835 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky61478912010-11-08 23:29:42 +0000836 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000837 if (!Found.empty()) {
838 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +0000839 if (PrevClassTemplate)
840 PrevDecl = PrevClassTemplate->getTemplatedDecl();
841 }
842 }
843
John McCall598b4402010-03-25 06:39:04 +0000844 // If this isn't a friend, then it's a member template, in which
845 // case we just want to build the instantiation in the
846 // specialization. If it is a friend, we want to build it in
847 // the appropriate context.
848 DeclContext *DC = Owner;
849 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +0000850 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000851 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +0000852 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +0000853 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +0000854 if (!DC) return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000855 } else {
856 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
857 Pattern->getDeclContext(),
858 TemplateArgs);
859 }
860
861 // Look for a previous declaration of the template in the owning
862 // context.
863 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
864 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
865 SemaRef.LookupQualifiedName(R, DC);
866
867 if (R.isSingleResult()) {
868 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
869 if (PrevClassTemplate)
870 PrevDecl = PrevClassTemplate->getTemplatedDecl();
871 }
872
Douglas Gregor14454802011-02-25 02:25:35 +0000873 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000874 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +0000875 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +0000876 << QualifierLoc.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000877 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000878 }
879
Douglas Gregor01e09d92010-04-08 18:16:15 +0000880 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +0000881 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +0000882 bool Complain = true;
883
884 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
885 // template for struct std::tr1::__detail::_Map_base, where the
886 // template parameters of the friend declaration don't match the
887 // template parameters of the original declaration. In this one
888 // case, we don't complain about the ill-formed friend
889 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000890 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +0000891 Pattern->getIdentifier()->isStr("_Map_base") &&
892 DC->isNamespace() &&
893 cast<NamespaceDecl>(DC)->getIdentifier() &&
894 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
895 DeclContext *DCParent = DC->getParent();
896 if (DCParent->isNamespace() &&
897 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
898 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
Richard Trieuc771d5d2014-05-28 02:16:01 +0000899 if (cast<Decl>(DCParent)->isInStdNamespace())
Douglas Gregor01e09d92010-04-08 18:16:15 +0000900 Complain = false;
901 }
902 }
903
John McCall598b4402010-03-25 06:39:04 +0000904 TemplateParameterList *PrevParams
905 = PrevClassTemplate->getTemplateParameters();
906
907 // Make sure the parameter lists match.
908 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000909 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +0000910 Sema::TPL_TemplateMatch)) {
911 if (Complain)
Craig Topperc3ec1492014-05-26 06:22:03 +0000912 return nullptr;
Douglas Gregor01e09d92010-04-08 18:16:15 +0000913
914 AdoptedPreviousTemplateParams = true;
915 InstParams = PrevParams;
916 }
John McCall598b4402010-03-25 06:39:04 +0000917
918 // Do some additional validation, then merge default arguments
919 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +0000920 if (!AdoptedPreviousTemplateParams &&
921 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +0000922 Sema::TPC_ClassTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +0000923 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000924 }
925 }
926
John McCall87a44eb2009-08-20 01:44:21 +0000927 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +0000928 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000929 Pattern->getLocStart(), Pattern->getLocation(),
930 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000931 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +0000932
Douglas Gregor14454802011-02-25 02:25:35 +0000933 if (QualifierLoc)
934 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +0000935
John McCall87a44eb2009-08-20 01:44:21 +0000936 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +0000937 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
938 D->getIdentifier(), InstParams, RecordInst,
939 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +0000940 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +0000941
John McCall598b4402010-03-25 06:39:04 +0000942 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +0000943 if (PrevClassTemplate)
944 Inst->setAccess(PrevClassTemplate->getAccess());
945 else
946 Inst->setAccess(D->getAccess());
947
Richard Smith64017682013-07-17 23:53:16 +0000948 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +0000949 // TODO: do we want to track the instantiation progeny of this
950 // friend target decl?
951 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000952 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +0000953 if (!PrevClassTemplate)
954 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +0000955 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000956
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000957 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +0000958 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +0000959 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +0000960
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000961 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +0000962 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +0000963 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000964 Inst->setLexicalDeclContext(Owner);
965 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000966 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000967 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000968
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000969 if (D->isOutOfLine()) {
970 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
971 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
972 }
973
John McCall87a44eb2009-08-20 01:44:21 +0000974 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +0000975
976 if (!PrevClassTemplate) {
977 // Queue up any out-of-line partial specializations of this member
978 // class template; the client will force their instantiation once
979 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000980 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +0000981 D->getPartialSpecializations(PartialSpecs);
982 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000983 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +0000984 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
985 }
986
John McCall87a44eb2009-08-20 01:44:21 +0000987 return Inst;
988}
989
Douglas Gregore704c9d2009-08-27 16:57:43 +0000990Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +0000991TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
992 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +0000993 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000994
Douglas Gregor21610382009-10-29 00:04:11 +0000995 // Lookup the already-instantiated declaration in the instantiation
996 // of the class template and return that.
997 DeclContext::lookup_result Found
998 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000999 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00001000 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001001
Douglas Gregor21610382009-10-29 00:04:11 +00001002 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +00001003 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +00001004 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00001005 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001006
Douglas Gregor869853e2010-11-10 19:44:59 +00001007 if (ClassTemplatePartialSpecializationDecl *Result
1008 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1009 return Result;
1010
1011 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001012}
1013
Larisse Voufo39a1e502013-08-06 01:03:05 +00001014Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1015 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1016 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001017
1018 // Create a local instantiation scope for this variable template, which
1019 // will contain the instantiations of the template parameters.
1020 LocalInstantiationScope Scope(SemaRef);
1021 TemplateParameterList *TempParams = D->getTemplateParameters();
1022 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1023 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001024 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001025
1026 VarDecl *Pattern = D->getTemplatedDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001027 VarTemplateDecl *PrevVarTemplate = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001028
1029 if (Pattern->getPreviousDecl()) {
1030 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1031 if (!Found.empty())
1032 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1033 }
1034
Richard Smith1c34fb72013-08-13 18:18:50 +00001035 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001036 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1037 /*InstantiatingVarTemplate=*/true));
Larisse Voufo39a1e502013-08-06 01:03:05 +00001038
1039 DeclContext *DC = Owner;
1040
Larisse Voufo39a1e502013-08-06 01:03:05 +00001041 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1042 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001043 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001044 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001045 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001046
1047 Inst->setAccess(D->getAccess());
1048 if (!PrevVarTemplate)
1049 Inst->setInstantiatedFromMemberTemplate(D);
1050
1051 if (D->isOutOfLine()) {
1052 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1053 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1054 }
1055
1056 Owner->addDecl(Inst);
1057
1058 if (!PrevVarTemplate) {
1059 // Queue up any out-of-line partial specializations of this member
1060 // variable template; the client will force their instantiation once
1061 // the enclosing class has been instantiated.
1062 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1063 D->getPartialSpecializations(PartialSpecs);
1064 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001065 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001066 OutOfLineVarPartialSpecs.push_back(
1067 std::make_pair(Inst, PartialSpecs[I]));
1068 }
1069
1070 return Inst;
1071}
1072
1073Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1074 VarTemplatePartialSpecializationDecl *D) {
1075 assert(D->isStaticDataMember() &&
1076 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001077
1078 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1079
1080 // Lookup the already-instantiated declaration and return that.
1081 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1082 assert(!Found.empty() && "Instantiation found nothing?");
1083
1084 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1085 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1086
1087 if (VarTemplatePartialSpecializationDecl *Result =
1088 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1089 return Result;
1090
1091 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1092}
1093
Douglas Gregore4b05162009-10-07 17:21:34 +00001094Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001095TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001096 // Create a local instantiation scope for this function template, which
1097 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001098 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001099 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001100 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001101
Douglas Gregore704c9d2009-08-27 16:57:43 +00001102 TemplateParameterList *TempParams = D->getTemplateParameters();
1103 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001104 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001105 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001106
Craig Topperc3ec1492014-05-26 06:22:03 +00001107 FunctionDecl *Instantiated = nullptr;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001108 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001109 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001110 InstParams));
1111 else
1112 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001113 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001114 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001115
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001116 if (!Instantiated)
Craig Topperc3ec1492014-05-26 06:22:03 +00001117 return nullptr;
Douglas Gregore704c9d2009-08-27 16:57:43 +00001118
Mike Stump11289f42009-09-09 15:08:12 +00001119 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001120 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001121 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001122 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001123 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001124 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001125 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001126
John McCall30837102010-03-26 23:10:15 +00001127 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1128
John McCall2079d0b2009-12-14 23:19:40 +00001129 // Link the instantiation back to the pattern *unless* this is a
1130 // non-definition friend declaration.
1131 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001132 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001133 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001134
John McCall30837102010-03-26 23:10:15 +00001135 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001136 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001137 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001138 } else if (InstTemplate->getDeclContext()->isRecord() &&
1139 !D->getPreviousDecl()) {
1140 SemaRef.CheckFriendAccess(InstTemplate);
1141 }
John McCall30837102010-03-26 23:10:15 +00001142
Douglas Gregore704c9d2009-08-27 16:57:43 +00001143 return InstTemplate;
1144}
1145
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001146Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001147 CXXRecordDecl *PrevDecl = nullptr;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001148 if (D->isInjectedClassName())
1149 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001150 else if (D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001151 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregorec9fd132012-01-14 16:38:05 +00001152 D->getPreviousDecl(),
John McCalle9f92a02009-12-15 22:29:06 +00001153 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001154 if (!Prev) return nullptr;
John McCalle9f92a02009-12-15 22:29:06 +00001155 PrevDecl = cast<CXXRecordDecl>(Prev);
1156 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001157
1158 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001159 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001160 D->getLocStart(), D->getLocation(),
1161 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001162
1163 // Substitute the nested name specifier, if any.
1164 if (SubstQualifier(D, Record))
Craig Topperc3ec1492014-05-26 06:22:03 +00001165 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00001166
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001167 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001168 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1169 // the tag decls introduced by friend class declarations don't have an access
1170 // specifier. Remove once this area of the code gets sorted out.
1171 if (D->getAccess() != AS_none)
1172 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001173 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001174 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001175
John McCallaa74a0c2009-08-28 07:59:38 +00001176 // If the original function was part of a friend declaration,
1177 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001178 if (D->getFriendObjectKind())
1179 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001180
Douglas Gregor04163182010-05-21 00:31:19 +00001181 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001182 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001183 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001184
1185 if (D->isLocalClass())
1186 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001187
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001188 // Forward the mangling number from the template to the instantiated decl.
1189 SemaRef.Context.setManglingNumber(Record,
1190 SemaRef.Context.getManglingNumber(D));
1191
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001192 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001193
1194 // DR1484 clarifies that the members of a local class are instantiated as part
1195 // of the instantiation of their enclosing entity.
1196 if (D->isCompleteDefinition() && D->isLocalClass()) {
David Majnemera64cb5a2014-02-22 00:17:46 +00001197 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1198 TSK_ImplicitInstantiation,
1199 /*Complain=*/true);
1200 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1201 TSK_ImplicitInstantiation);
David Majnemer192d1792013-11-27 08:20:38 +00001202 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001203 return Record;
1204}
1205
Douglas Gregor89f593a2012-09-13 21:56:43 +00001206/// \brief Adjust the given function type for an instantiation of the
1207/// given declaration, to cope with modifications to the function's type that
1208/// aren't reflected in the type-source information.
1209///
1210/// \param D The declaration we're instantiating.
1211/// \param TInfo The already-instantiated type.
1212static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1213 FunctionDecl *D,
1214 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001215 const FunctionProtoType *OrigFunc
1216 = D->getType()->castAs<FunctionProtoType>();
1217 const FunctionProtoType *NewFunc
1218 = TInfo->getType()->castAs<FunctionProtoType>();
1219 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1220 return TInfo->getType();
1221
1222 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1223 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001224 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001225 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001226}
1227
John McCallaa74a0c2009-08-28 07:59:38 +00001228/// Normal class members are of more specific types and therefore
1229/// don't make it here. This function serves two purposes:
1230/// 1) instantiating function templates
1231/// 2) substituting friend declarations
Douglas Gregor33636e62009-12-24 20:56:24 +00001232Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001233 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001234 // Check whether there is already a function template specialization for
1235 // this declaration.
1236 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001237 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001238 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001239
Craig Topperc3ec1492014-05-26 06:22:03 +00001240 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001241 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00001242 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001243
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001244 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001245 if (SpecFunc)
1246 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001247 }
Mike Stump11289f42009-09-09 15:08:12 +00001248
John McCall2f88d7d2010-03-27 05:57:59 +00001249 bool isFriend;
1250 if (FunctionTemplate)
1251 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1252 else
1253 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1254
Craig Topperc3ec1492014-05-26 06:22:03 +00001255 bool MergeWithParentScope = (TemplateParams != nullptr) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001256 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001257 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001258 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001259 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001260
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001261 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001262 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001263 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001264 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001265 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001266
Douglas Gregor14454802011-02-25 02:25:35 +00001267 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1268 if (QualifierLoc) {
1269 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1270 TemplateArgs);
1271 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001272 return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001273 }
1274
John McCallce410662010-02-06 01:50:47 +00001275 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001276 // in the enclosing namespace; otherwise we need to find the instantiated
1277 // context.
John McCallce410662010-02-06 01:50:47 +00001278 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001279 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001280 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001281 SemaRef.adjustContextForLocalExternDecl(DC);
1282 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001283 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001284 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001285 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001286 if (!DC) return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001287 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001288 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001289 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001290 }
John McCallce410662010-02-06 01:50:47 +00001291
John McCallaa74a0c2009-08-28 07:59:38 +00001292 FunctionDecl *Function =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001293 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara0d4fce12012-10-04 21:40:42 +00001294 D->getNameInfo(), T, TInfo,
Rafael Espindola9dd86de2013-04-16 02:29:15 +00001295 D->getCanonicalDecl()->getStorageClass(),
Richard Smitha77a0a62011-08-15 21:04:07 +00001296 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001297 D->isConstexpr());
Enea Zaffanella25723ce2013-07-19 18:02:36 +00001298 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCall3e11ebe2010-03-15 10:12:16 +00001299
Richard Smithf3814ad2013-01-25 00:08:28 +00001300 if (D->isInlined())
1301 Function->setImplicitlyInline();
1302
Douglas Gregor14454802011-02-25 02:25:35 +00001303 if (QualifierLoc)
1304 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001305
Richard Smith541b38b2013-09-20 01:15:31 +00001306 if (D->isLocalExternDecl())
1307 Function->setLocalExternDecl();
1308
John McCall30837102010-03-26 23:10:15 +00001309 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001310 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001311 assert(D->getDeclContext()->isFileContext());
1312 LexicalDC = D->getDeclContext();
1313 }
1314
1315 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001316
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001317 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001318 for (unsigned P = 0; P < Params.size(); ++P)
1319 if (Params[P])
1320 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001321 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001322
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001323 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001324 if (TemplateParams) {
1325 // Our resulting instantiation is actually a function template, since we
1326 // are substituting only the outer template parameters. For example, given
1327 //
1328 // template<typename T>
1329 // struct X {
1330 // template<typename U> friend void f(T, U);
1331 // };
1332 //
1333 // X<int> x;
1334 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001335 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001336 // which means substituting int for T, but leaving "f" as a friend function
1337 // template.
1338 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001339 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001340 Function->getLocation(),
1341 Function->getDeclName(),
1342 TemplateParams, Function);
1343 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001344
1345 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001346
1347 if (isFriend && D->isThisDeclarationADefinition()) {
1348 // TODO: should we remember this connection regardless of whether
1349 // the friend declaration provided a body?
1350 FunctionTemplate->setInstantiatedFromMemberTemplate(
1351 D->getDescribedFunctionTemplate());
1352 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001353 } else if (FunctionTemplate) {
1354 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001355 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001356 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001357 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001358 Innermost.begin(),
1359 Innermost.size()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001360 /*InsertPos=*/nullptr);
Chandler Carruth48b28312011-08-18 09:09:59 +00001361 } else if (isFriend) {
1362 // Note, we need this connection even if the friend doesn't have a body.
1363 // Its body may exist but not have been attached yet due to deferred
1364 // parsing.
1365 // FIXME: It might be cleaner to set this when attaching the body to the
1366 // friend function declaration, however that would require finding all the
1367 // instantiations and modifying them.
John McCalle0b2ddb2010-03-26 04:53:08 +00001368 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001369 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001370
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001371 if (InitFunctionInstantiation(Function, D))
1372 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001373
John McCallb9c78482010-04-08 09:05:18 +00001374 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001375
Richard Smith541b38b2013-09-20 01:15:31 +00001376 LookupResult Previous(
1377 SemaRef, Function->getDeclName(), SourceLocation(),
1378 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1379 : Sema::LookupOrdinaryName,
1380 Sema::ForRedeclaration);
John McCall1f82f242009-11-18 22:49:29 +00001381
John McCallb9c78482010-04-08 09:05:18 +00001382 if (DependentFunctionTemplateSpecializationInfo *Info
1383 = D->getDependentSpecializationInfo()) {
1384 assert(isFriend && "non-friend has dependent specialization info?");
1385
1386 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001387 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001388
1389 // Instantiate the explicit template arguments.
1390 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1391 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001392 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1393 ExplicitArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00001394 return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001395
1396 // Map the candidate templates to their instantiations.
1397 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1398 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1399 Info->getTemplate(I),
1400 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001401 if (!Temp) return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001402
1403 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1404 }
1405
1406 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1407 &ExplicitArgs,
1408 Previous))
1409 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001410
John McCallb9c78482010-04-08 09:05:18 +00001411 isExplicitSpecialization = true;
1412
1413 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001414 // Look only into the namespace where the friend would be declared to
1415 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001416 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001417 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001418
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001419 // In C++, the previous declaration we find might be a tag type
1420 // (class or enum). In this case, the new declaration will hide the
1421 // tag type. Note that this does does not apply if we're declaring a
1422 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001423 if (Previous.isSingleTagDecl())
1424 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001425 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001426
Craig Topperc3ec1492014-05-26 06:22:03 +00001427 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001428 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001429
John McCallb9467b62010-04-24 01:30:58 +00001430 NamedDecl *PrincipalDecl = (TemplateParams
1431 ? cast<NamedDecl>(FunctionTemplate)
1432 : Function);
1433
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001434 // If the original function was part of a friend declaration,
1435 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001436 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001437 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001438 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001439
Richard Smith91dfaac2014-02-03 02:37:59 +00001440 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001441
Richard Smith91dfaac2014-02-03 02:37:59 +00001442 // C++11 [temp.friend]p4 (DR329):
1443 // When a function is defined in a friend function declaration in a class
1444 // template, the function is instantiated when the function is odr-used.
1445 // The same restrictions on multiple declarations and definitions that
1446 // apply to non-template function declarations and definitions also apply
1447 // to these implicit definitions.
1448 if (D->isThisDeclarationADefinition()) {
Douglas Gregorb92ea592010-05-18 05:45:02 +00001449 // Check for a function body.
Craig Topperc3ec1492014-05-26 06:22:03 +00001450 const FunctionDecl *Definition = nullptr;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001451 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001452 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001453 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1454 << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001455 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001456 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001457 // Check for redefinitions due to other instantiations of this or
1458 // a similar friend function.
Aaron Ballman86c93902014-03-06 23:45:36 +00001459 else for (auto R : Function->redecls()) {
1460 if (R == Function)
Gabor Greif122f1eb2010-08-28 15:42:30 +00001461 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00001462
1463 // If some prior declaration of this function has been used, we need
1464 // to instantiate its definition.
1465 if (!QueuedInstantiation && R->isUsed(false)) {
1466 if (MemberSpecializationInfo *MSInfo =
1467 Function->getMemberSpecializationInfo()) {
1468 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1469 SourceLocation Loc = R->getLocation(); // FIXME
1470 MSInfo->setPointOfInstantiation(Loc);
1471 SemaRef.PendingLocalImplicitInstantiations.push_back(
1472 std::make_pair(Function, Loc));
1473 QueuedInstantiation = true;
Gabor Greif718d5152010-08-30 21:10:05 +00001474 }
1475 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001476 }
1477
1478 // If some prior declaration of this function was a friend with an
1479 // uninstantiated definition, reject it.
1480 if (R->getFriendObjectKind()) {
1481 if (const FunctionDecl *RPattern =
1482 R->getTemplateInstantiationPattern()) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001483 if (RPattern->isDefined(RPattern)) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001484 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001485 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001486 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregorb92ea592010-05-18 05:45:02 +00001487 break;
1488 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001489 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001490 }
1491 }
1492 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001493 }
1494
Richard Smith541b38b2013-09-20 01:15:31 +00001495 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1496 DC->makeDeclVisibleInContext(PrincipalDecl);
1497
John McCallb9467b62010-04-24 01:30:58 +00001498 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1499 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1500 PrincipalDecl->setNonMemberOperator();
1501
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001502 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001503 return Function;
1504}
1505
Douglas Gregore704c9d2009-08-27 16:57:43 +00001506Decl *
1507TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001508 TemplateParameterList *TemplateParams,
1509 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001510 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001511 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001512 // We are creating a function template specialization from a function
1513 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001514 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001515 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001516
Craig Topperc3ec1492014-05-26 06:22:03 +00001517 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001518 FunctionDecl *SpecFunc
Craig Topper7e0daca2014-06-26 04:58:53 +00001519 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001520
Douglas Gregor97628d62009-08-21 00:16:32 +00001521 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001522 if (SpecFunc)
1523 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001524 }
1525
John McCall2f88d7d2010-03-27 05:57:59 +00001526 bool isFriend;
1527 if (FunctionTemplate)
1528 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1529 else
1530 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1531
Craig Topperc3ec1492014-05-26 06:22:03 +00001532 bool MergeWithParentScope = (TemplateParams != nullptr) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001533 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001534 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001535 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001536
John McCalld0e23ec2010-10-19 02:26:41 +00001537 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001538 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001539 unsigned NumTempParamLists = 0;
1540 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1541 TempParamLists.set_size(NumTempParamLists);
1542 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1543 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1544 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1545 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001546 return nullptr;
John McCalld0e23ec2010-10-19 02:26:41 +00001547 TempParamLists[I] = InstParams;
1548 }
1549 }
1550
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001551 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001552 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001553 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001554 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001555 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001556
Douglas Gregor14454802011-02-25 02:25:35 +00001557 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1558 if (QualifierLoc) {
1559 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001560 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001561 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001562 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001563 }
1564
1565 DeclContext *DC = Owner;
1566 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001567 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001568 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001569 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001570 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001571
1572 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00001573 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001574 } else {
1575 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1576 D->getDeclContext(),
1577 TemplateArgs);
1578 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001579 if (!DC) return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001580 }
1581
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001582 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001583 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Craig Topperc3ec1492014-05-26 06:22:03 +00001584 CXXMethodDecl *Method = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001585
Abramo Bagnaradff19302011-03-08 08:55:46 +00001586 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001587 DeclarationNameInfo NameInfo
1588 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001589 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001590 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001591 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001592 Constructor->isExplicit(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001593 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001594 false, Constructor->isConstexpr());
Richard Smith4c163a02013-05-17 02:19:35 +00001595
Richard Smith185be182013-04-10 05:48:59 +00001596 // Claim that the instantiation of a constructor or constructor template
1597 // inherits the same constructor that the template does.
Richard Smith4c163a02013-05-17 02:19:35 +00001598 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1599 Constructor->getInheritedConstructor())) {
1600 // If we're instantiating a specialization of a function template, our
1601 // "inherited constructor" will actually itself be a function template.
1602 // Instantiate a declaration of it, too.
1603 if (FunctionTemplate) {
1604 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1605 !Inh->getParent()->isDependentContext() &&
1606 "inheriting constructor template in dependent context?");
1607 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1608 Inh);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001609 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00001610 return nullptr;
Richard Smith4c163a02013-05-17 02:19:35 +00001611 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1612 LocalInstantiationScope LocalScope(SemaRef);
1613
1614 // Use the same template arguments that we deduced for the inheriting
1615 // constructor. There's no way they could be deduced differently.
1616 MultiLevelTemplateArgumentList InheritedArgs;
1617 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1618 Inh = cast_or_null<CXXConstructorDecl>(
1619 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1620 if (!Inh)
Craig Topperc3ec1492014-05-26 06:22:03 +00001621 return nullptr;
Richard Smith4c163a02013-05-17 02:19:35 +00001622 }
Richard Smith185be182013-04-10 05:48:59 +00001623 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smith4c163a02013-05-17 02:19:35 +00001624 }
Douglas Gregore8394862009-08-21 22:43:28 +00001625 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001626 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001627 StartLoc, NameInfo, T, TInfo,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001628 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001629 false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001630 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001631 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001632 StartLoc, NameInfo, T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001633 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001634 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001635 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001636 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001637 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001638 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001639 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001640 StartLoc, NameInfo, T, TInfo,
Rafael Espindola29cda592013-04-15 12:38:20 +00001641 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001642 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001643 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001644
Richard Smithf3814ad2013-01-25 00:08:28 +00001645 if (D->isInlined())
1646 Method->setImplicitlyInline();
1647
Douglas Gregor14454802011-02-25 02:25:35 +00001648 if (QualifierLoc)
1649 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001650
Douglas Gregore704c9d2009-08-27 16:57:43 +00001651 if (TemplateParams) {
1652 // Our resulting instantiation is actually a function template, since we
1653 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001654 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001655 // template<typename T>
1656 // struct X {
1657 // template<typename U> void f(T, U);
1658 // };
1659 //
1660 // X<int> x;
1661 //
1662 // We are instantiating the member template "f" within X<int>, which means
1663 // substituting int for T, but leaving "f" as a member function template.
1664 // Build the function template itself.
1665 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1666 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001667 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001668 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001669 if (isFriend) {
1670 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001671 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001672 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001673 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001674 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001675 } else if (FunctionTemplate) {
1676 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001677 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001678 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001679 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001680 Innermost.begin(),
1681 Innermost.size()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001682 /*InsertPos=*/nullptr);
John McCall2f88d7d2010-03-27 05:57:59 +00001683 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001684 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001685 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001686 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001687
Mike Stump11289f42009-09-09 15:08:12 +00001688 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001689 // out-of-line, the instantiation will have the same lexical
1690 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001691 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00001692 if (NumTempParamLists)
1693 Method->setTemplateParameterListsInfo(SemaRef.Context,
1694 NumTempParamLists,
1695 TempParamLists.data());
1696
John McCall2f88d7d2010-03-27 05:57:59 +00001697 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001698 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001699 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001700 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001701
Douglas Gregor21342092009-03-24 00:38:23 +00001702 // Attach the parameters
1703 for (unsigned P = 0; P < Params.size(); ++P)
1704 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00001705 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00001706
1707 if (InitMethodInstantiation(Method, D))
1708 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001709
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001710 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1711 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001712
John McCall2f88d7d2010-03-27 05:57:59 +00001713 if (!FunctionTemplate || TemplateParams || isFriend) {
1714 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001715
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001716 // In C++, the previous declaration we find might be a tag type
1717 // (class or enum). In this case, the new declaration will hide the
1718 // tag type. Note that this does does not apply if we're declaring a
1719 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001720 if (Previous.isSingleTagDecl())
1721 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001722 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001723
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001724 if (!IsClassScopeSpecialization)
Craig Topperc3ec1492014-05-26 06:22:03 +00001725 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001726
Douglas Gregor21920e372009-12-01 17:24:26 +00001727 if (D->isPure())
1728 SemaRef.CheckPureMethod(Method, SourceRange());
1729
John McCalla0a96892012-08-10 03:15:35 +00001730 // Propagate access. For a non-friend declaration, the access is
1731 // whatever we're propagating from. For a friend, it should be the
1732 // previous declaration we just found.
1733 if (isFriend && Method->getPreviousDecl())
1734 Method->setAccess(Method->getPreviousDecl()->getAccess());
1735 else
1736 Method->setAccess(D->getAccess());
1737 if (FunctionTemplate)
1738 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00001739
Anders Carlsson7c812f52011-01-20 06:52:44 +00001740 SemaRef.CheckOverrideControl(Method);
1741
Eli Friedman41340732011-11-15 22:39:08 +00001742 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00001743 if (D->isExplicitlyDefaulted())
1744 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001745 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00001746 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001747
John McCalla0a96892012-08-10 03:15:35 +00001748 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00001749 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00001750 // do nothing
1751
1752 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00001753 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00001754 // do nothing
1755
1756 // Otherwise, check access to friends and make them visible.
1757 } else if (isFriend) {
1758 // We only need to re-check access for methods which we didn't
1759 // manage to match during parsing.
1760 if (!D->getPreviousDecl())
1761 SemaRef.CheckFriendAccess(Method);
1762
1763 Record->makeDeclVisibleInContext(Method);
1764
1765 // Otherwise, add the declaration. We don't need to do this for
1766 // class-scope specializations because we'll have matched them with
1767 // the appropriate template.
1768 } else if (!IsClassScopeSpecialization) {
1769 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001770 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001771
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001772 return Method;
1773}
1774
Douglas Gregor4044d992009-03-24 16:43:20 +00001775Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001776 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001777}
1778
Douglas Gregor654b07e2009-03-24 00:15:49 +00001779Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001780 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001781}
1782
Douglas Gregor1880ba52009-03-25 00:34:44 +00001783Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001784 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001785}
1786
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00001787Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00001788 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1789 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001790}
1791
John McCall87a44eb2009-08-20 01:44:21 +00001792Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1793 TemplateTypeParmDecl *D) {
1794 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00001795 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00001796
John McCall87a44eb2009-08-20 01:44:21 +00001797 TemplateTypeParmDecl *Inst =
Abramo Bagnarab3185b02011-03-06 15:48:19 +00001798 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1799 D->getLocStart(), D->getLocation(),
Chandler Carruth08836322011-05-01 00:51:33 +00001800 D->getDepth() - TemplateArgs.getNumLevels(),
1801 D->getIndex(), D->getIdentifier(),
John McCall87a44eb2009-08-20 01:44:21 +00001802 D->wasDeclaredWithTypename(),
1803 D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001804 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00001805
David Majnemer89189202013-08-28 23:48:32 +00001806 if (D->hasDefaultArgument()) {
1807 TypeSourceInfo *InstantiatedDefaultArg =
1808 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1809 D->getDefaultArgumentLoc(), D->getDeclName());
1810 if (InstantiatedDefaultArg)
1811 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1812 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001813
1814 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001815 // scope.
1816 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001817
John McCall87a44eb2009-08-20 01:44:21 +00001818 return Inst;
1819}
1820
Douglas Gregor6b815c82009-10-23 23:25:44 +00001821Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1822 NonTypeTemplateParmDecl *D) {
1823 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001824 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001825 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1826 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001827 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001828 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001829 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001830 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001831
1832 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001833 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001834 // expansion of types. Substitute into each of the expanded types.
1835 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1836 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1837 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1838 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1839 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001840 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001841 D->getDeclName());
1842 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001843 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001844
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001845 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1846 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1847 D->getLocation());
1848 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001849 return nullptr;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001850 ExpandedParameterPackTypes.push_back(NewT);
1851 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001852
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001853 IsExpandedParameterPack = true;
1854 DI = D->getTypeSourceInfo();
1855 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00001856 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001857 // The non-type template parameter pack's type is a pack expansion of types.
1858 // Determine whether we need to expand this parameter pack into separate
1859 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00001860 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001861 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001862 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001863 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001864
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001865 // Determine whether the set of unexpanded parameter packs can and should
1866 // be expanded.
1867 bool Expand = true;
1868 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001869 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001870 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00001871 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001872 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1873 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001874 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001875 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001876 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001877 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00001878 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001879
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001880 if (Expand) {
1881 for (unsigned I = 0; I != *NumExpansions; ++I) {
1882 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1883 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001884 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001885 D->getDeclName());
1886 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001887 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001888
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001889 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1890 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1891 NewDI->getType(),
1892 D->getLocation());
1893 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001894 return nullptr;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001895 ExpandedParameterPackTypes.push_back(NewT);
1896 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001897
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001898 // Note that we have an expanded parameter pack. The "type" of this
1899 // expanded parameter pack is the original expansion type, but callers
1900 // will end up using the expanded parameter pack types for type-checking.
1901 IsExpandedParameterPack = true;
1902 DI = D->getTypeSourceInfo();
1903 T = DI->getType();
1904 } else {
1905 // We cannot fully expand the pack expansion now, so substitute into the
1906 // pattern and create a new pack expansion type.
1907 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1908 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001909 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001910 D->getDeclName());
1911 if (!NewPattern)
Craig Topperc3ec1492014-05-26 06:22:03 +00001912 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001913
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001914 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1915 NumExpansions);
1916 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001917 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001918
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001919 T = DI->getType();
1920 }
1921 } else {
1922 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001923 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001924 D->getLocation(), D->getDeclName());
1925 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001926 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001927
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001928 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001929 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001930 D->getLocation());
1931 if (T.isNull()) {
1932 T = SemaRef.Context.IntTy;
1933 Invalid = true;
1934 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00001935 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001936
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001937 NonTypeTemplateParmDecl *Param;
1938 if (IsExpandedParameterPack)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001939 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001940 D->getInnerLocStart(),
1941 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001942 D->getDepth() - TemplateArgs.getNumLevels(),
1943 D->getPosition(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001944 D->getIdentifier(), T,
1945 DI,
1946 ExpandedParameterPackTypes.data(),
1947 ExpandedParameterPackTypes.size(),
1948 ExpandedParameterPackTypesAsWritten.data());
1949 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001950 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001951 D->getInnerLocStart(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001952 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001953 D->getDepth() - TemplateArgs.getNumLevels(),
1954 D->getPosition(),
1955 D->getIdentifier(), T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001956 D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001957
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001958 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001959 if (Invalid)
1960 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001961
David Majnemer89189202013-08-28 23:48:32 +00001962 if (D->hasDefaultArgument()) {
1963 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1964 if (!Value.isInvalid())
1965 Param->setDefaultArgument(Value.get(), false);
1966 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001967
1968 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001969 // scope.
1970 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001971 return Param;
1972}
1973
Richard Smith1fde8ec2012-09-07 02:06:42 +00001974static void collectUnexpandedParameterPacks(
1975 Sema &S,
1976 TemplateParameterList *Params,
1977 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1978 for (TemplateParameterList::const_iterator I = Params->begin(),
1979 E = Params->end(); I != E; ++I) {
1980 if ((*I)->isTemplateParameterPack())
1981 continue;
1982 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1983 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1984 Unexpanded);
1985 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1986 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1987 Unexpanded);
1988 }
1989}
1990
Anders Carlsson4bd78752009-08-28 15:18:15 +00001991Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00001992TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1993 TemplateTemplateParmDecl *D) {
1994 // Instantiate the template parameter list of the template template parameter.
1995 TemplateParameterList *TempParams = D->getTemplateParameters();
1996 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001997 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1998
1999 bool IsExpandedParameterPack = false;
2000
2001 if (D->isExpandedParameterPack()) {
2002 // The template template parameter pack is an already-expanded pack
2003 // expansion of template parameters. Substitute into each of the expanded
2004 // parameters.
2005 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2006 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2007 I != N; ++I) {
2008 LocalInstantiationScope Scope(SemaRef);
2009 TemplateParameterList *Expansion =
2010 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2011 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002012 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002013 ExpandedParams.push_back(Expansion);
2014 }
2015
2016 IsExpandedParameterPack = true;
2017 InstParams = TempParams;
2018 } else if (D->isPackExpansion()) {
2019 // The template template parameter pack expands to a pack of template
2020 // template parameters. Determine whether we need to expand this parameter
2021 // pack into separate parameters.
2022 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2023 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2024 Unexpanded);
2025
2026 // Determine whether the set of unexpanded parameter packs can and should
2027 // be expanded.
2028 bool Expand = true;
2029 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002030 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002031 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2032 TempParams->getSourceRange(),
2033 Unexpanded,
2034 TemplateArgs,
2035 Expand, RetainExpansion,
2036 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002037 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002038
2039 if (Expand) {
2040 for (unsigned I = 0; I != *NumExpansions; ++I) {
2041 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2042 LocalInstantiationScope Scope(SemaRef);
2043 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2044 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002045 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002046 ExpandedParams.push_back(Expansion);
2047 }
2048
2049 // Note that we have an expanded parameter pack. The "type" of this
2050 // expanded parameter pack is the original expansion type, but callers
2051 // will end up using the expanded parameter pack types for type-checking.
2052 IsExpandedParameterPack = true;
2053 InstParams = TempParams;
2054 } else {
2055 // We cannot fully expand the pack expansion now, so just substitute
2056 // into the pattern.
2057 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2058
2059 LocalInstantiationScope Scope(SemaRef);
2060 InstParams = SubstTemplateParams(TempParams);
2061 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002062 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002063 }
2064 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002065 // Perform the actual substitution of template parameters within a new,
2066 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002067 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002068 InstParams = SubstTemplateParams(TempParams);
2069 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002070 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002071 }
2072
Douglas Gregor38fee962009-11-11 16:58:32 +00002073 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002074 TemplateTemplateParmDecl *Param;
2075 if (IsExpandedParameterPack)
2076 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2077 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002078 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00002079 D->getPosition(),
2080 D->getIdentifier(), InstParams,
2081 ExpandedParams);
2082 else
2083 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2084 D->getLocation(),
2085 D->getDepth() - TemplateArgs.getNumLevels(),
2086 D->getPosition(),
2087 D->isParameterPack(),
2088 D->getIdentifier(), InstParams);
David Majnemer89189202013-08-28 23:48:32 +00002089 if (D->hasDefaultArgument()) {
2090 NestedNameSpecifierLoc QualifierLoc =
2091 D->getDefaultArgument().getTemplateQualifierLoc();
2092 QualifierLoc =
2093 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2094 TemplateName TName = SemaRef.SubstTemplateName(
2095 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2096 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2097 if (!TName.isNull())
2098 Param->setDefaultArgument(
2099 TemplateArgumentLoc(TemplateArgument(TName),
2100 D->getDefaultArgument().getTemplateQualifierLoc(),
2101 D->getDefaultArgument().getTemplateNameLoc()),
2102 false);
2103 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002104 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002105
2106 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002107 // scope.
2108 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002109
Douglas Gregor38fee962009-11-11 16:58:32 +00002110 return Param;
2111}
2112
Douglas Gregore0b28662009-11-17 06:07:40 +00002113Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002114 // Using directives are never dependent (and never contain any types or
2115 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002116
Douglas Gregore0b28662009-11-17 06:07:40 +00002117 UsingDirectiveDecl *Inst
2118 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002119 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002120 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002121 D->getIdentLocation(),
2122 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002123 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002124
2125 // Add the using directive to its declaration context
2126 // only if this is not a function or method.
2127 if (!Owner->isFunctionOrMethod())
2128 Owner->addDecl(Inst);
2129
Douglas Gregore0b28662009-11-17 06:07:40 +00002130 return Inst;
2131}
2132
John McCallb96ec562009-12-04 22:46:56 +00002133Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002134
2135 // The nested name specifier may be dependent, for example
2136 // template <typename T> struct t {
2137 // struct s1 { T f1(); };
2138 // struct s2 : s1 { using s1::f1; };
2139 // };
2140 // template struct t<int>;
2141 // Here, in using s1::f1, s1 refers to t<T>::s1;
2142 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002143 NestedNameSpecifierLoc QualifierLoc
2144 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2145 TemplateArgs);
2146 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002147 return nullptr;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002148
2149 // The name info is non-dependent, so no transformation
2150 // is required.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002151 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCallb96ec562009-12-04 22:46:56 +00002152
John McCall84d87672009-12-10 09:41:52 +00002153 // We only need to do redeclaration lookups if we're in a class
2154 // scope (in fact, it's not really even possible in non-class
2155 // scopes).
2156 bool CheckRedeclaration = Owner->isRecord();
2157
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002158 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2159 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002160
John McCallb96ec562009-12-04 22:46:56 +00002161 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002162 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002163 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002164 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002165 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002166
Douglas Gregor0499ab62011-02-25 15:54:31 +00002167 CXXScopeSpec SS;
2168 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002169 if (CheckRedeclaration) {
2170 Prev.setHideTags(false);
2171 SemaRef.LookupQualifiedName(Prev, Owner);
2172
2173 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002174 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2175 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002176 D->getLocation(), Prev))
2177 NewUD->setInvalidDecl();
2178
2179 }
2180
2181 if (!NewUD->isInvalidDecl() &&
Richard Smith7ad0b882014-04-02 21:44:35 +00002182 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00002183 D->getLocation()))
2184 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002185
John McCallb96ec562009-12-04 22:46:56 +00002186 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2187 NewUD->setAccess(D->getAccess());
2188 Owner->addDecl(NewUD);
2189
John McCall84d87672009-12-10 09:41:52 +00002190 // Don't process the shadow decls for an invalid decl.
2191 if (NewUD->isInvalidDecl())
2192 return NewUD;
2193
Richard Smith23d55872012-04-02 01:30:27 +00002194 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00002195 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
Richard Smith23d55872012-04-02 01:30:27 +00002196 return NewUD;
2197 }
2198
John McCalla1d85502009-12-22 22:26:37 +00002199 bool isFunctionScope = Owner->isFunctionOrMethod();
2200
John McCall84d87672009-12-10 09:41:52 +00002201 // Process the shadow decls.
Aaron Ballman91cdc282014-03-13 18:07:29 +00002202 for (auto *Shadow : D->shadows()) {
John McCall84d87672009-12-10 09:41:52 +00002203 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002204 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2205 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002206 if (!InstTarget)
Craig Topperc3ec1492014-05-26 06:22:03 +00002207 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00002208
Craig Topperc3ec1492014-05-26 06:22:03 +00002209 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00002210 if (CheckRedeclaration) {
2211 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2212 continue;
2213 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2214 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2215 Shadow->getLocation(), OldPrev, TemplateArgs));
2216 }
John McCall84d87672009-12-10 09:41:52 +00002217
Richard Smithfd8634a2013-10-23 02:17:46 +00002218 UsingShadowDecl *InstShadow =
Craig Topperc3ec1492014-05-26 06:22:03 +00002219 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2220 PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002221 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002222
2223 if (isFunctionScope)
2224 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002225 }
John McCallb96ec562009-12-04 22:46:56 +00002226
2227 return NewUD;
2228}
2229
2230Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002231 // Ignore these; we handle them in bulk when processing the UsingDecl.
Craig Topperc3ec1492014-05-26 06:22:03 +00002232 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00002233}
2234
John McCalle61f2ba2009-11-18 02:36:19 +00002235Decl * TemplateDeclInstantiator
2236 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002237 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002238 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002239 TemplateArgs);
2240 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002241 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002242
Anders Carlsson4bd78752009-08-28 15:18:15 +00002243 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002244 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002245
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002246 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Kramerd81108f2012-11-14 15:08:31 +00002247 // Hence, no transformation is required for it.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002248 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002249 NamedDecl *UD =
Craig Topperc3ec1492014-05-26 06:22:03 +00002250 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2251 D->getUsingLoc(), SS, NameInfo, nullptr,
John McCalle61f2ba2009-11-18 02:36:19 +00002252 /*instantiation*/ true,
2253 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor6044d692010-05-19 17:02:24 +00002254 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002255 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2256
John McCalle61f2ba2009-11-18 02:36:19 +00002257 return UD;
2258}
2259
2260Decl * TemplateDeclInstantiator
2261 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002262 NestedNameSpecifierLoc QualifierLoc
2263 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2264 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002265 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002266
John McCalle61f2ba2009-11-18 02:36:19 +00002267 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002268 SS.Adopt(QualifierLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00002269
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002270 DeclarationNameInfo NameInfo
2271 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2272
John McCalle61f2ba2009-11-18 02:36:19 +00002273 NamedDecl *UD =
Craig Topperc3ec1492014-05-26 06:22:03 +00002274 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2275 D->getUsingLoc(), SS, NameInfo, nullptr,
John McCalle61f2ba2009-11-18 02:36:19 +00002276 /*instantiation*/ true,
2277 /*typename*/ false, SourceLocation());
Douglas Gregor6044d692010-05-19 17:02:24 +00002278 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002279 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2280
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002281 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00002282}
2283
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002284
2285Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2286 ClassScopeFunctionSpecializationDecl *Decl) {
2287 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber7b5a7162012-06-25 17:21:05 +00002288 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
Craig Topperc3ec1492014-05-26 06:22:03 +00002289 nullptr, true));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002290
2291 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2292 Sema::ForRedeclaration);
2293
Nico Weber7b5a7162012-06-25 17:21:05 +00002294 TemplateArgumentListInfo TemplateArgs;
Craig Topperc3ec1492014-05-26 06:22:03 +00002295 TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
Nico Weber7b5a7162012-06-25 17:21:05 +00002296 if (Decl->hasExplicitTemplateArgs()) {
2297 TemplateArgs = Decl->templateArgs();
2298 TemplateArgsPtr = &TemplateArgs;
2299 }
2300
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002301 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002302 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2303 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002304 NewFD->setInvalidDecl();
2305 return NewFD;
2306 }
2307
2308 // Associate the specialization with the pattern.
2309 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2310 assert(Specialization && "Class scope Specialization is null");
2311 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2312
2313 return NewFD;
2314}
2315
Alexey Bataeva769e072013-03-22 06:34:35 +00002316Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2317 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002318 SmallVector<Expr *, 5> Vars;
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002319 for (auto *I : D->varlists()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002320 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
Alexey Bataeva769e072013-03-22 06:34:35 +00002321 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002322 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002323 }
2324
2325 OMPThreadPrivateDecl *TD =
2326 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2327
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002328 TD->setAccess(AS_public);
2329 Owner->addDecl(TD);
2330
Alexey Bataeva769e072013-03-22 06:34:35 +00002331 return TD;
2332}
2333
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002334Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002335 return VisitFunctionDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002336}
2337
2338Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002339 return VisitCXXMethodDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002340}
2341
2342Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2343 llvm_unreachable("There are only CXXRecordDecls in C++");
2344}
2345
2346Decl *
2347TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2348 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00002349 // As a MS extension, we permit class-scope explicit specialization
2350 // of member class templates.
2351 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2352 assert(ClassTemplate->getDeclContext()->isRecord() &&
2353 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2354 "can only instantiate an explicit specialization "
2355 "for a member class template");
2356
2357 // Lookup the already-instantiated declaration in the instantiation
2358 // of the class template. FIXME: Diagnose or assert if this fails?
2359 DeclContext::lookup_result Found
2360 = Owner->lookup(ClassTemplate->getDeclName());
2361 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00002362 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002363 ClassTemplateDecl *InstClassTemplate
2364 = dyn_cast<ClassTemplateDecl>(Found.front());
2365 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00002366 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002367
2368 // Substitute into the template arguments of the class template explicit
2369 // specialization.
2370 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2371 castAs<TemplateSpecializationTypeLoc>();
2372 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2373 Loc.getRAngleLoc());
2374 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2375 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2376 ArgLocs.push_back(Loc.getArgLoc(I));
2377 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2378 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002379 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002380
2381 // Check that the template argument list is well-formed for this
2382 // class template.
2383 SmallVector<TemplateArgument, 4> Converted;
2384 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2385 D->getLocation(),
2386 InstTemplateArgs,
2387 false,
2388 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002389 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002390
2391 // Figure out where to insert this class template explicit specialization
2392 // in the member template's set of class template explicit specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002393 void *InsertPos = nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002394 ClassTemplateSpecializationDecl *PrevDecl =
Craig Topper7e0daca2014-06-26 04:58:53 +00002395 InstClassTemplate->findSpecialization(Converted, InsertPos);
Richard Smith8a0dde72013-12-14 01:04:22 +00002396
2397 // Check whether we've already seen a conflicting instantiation of this
2398 // declaration (for instance, if there was a prior implicit instantiation).
2399 bool Ignored;
2400 if (PrevDecl &&
2401 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2402 D->getSpecializationKind(),
2403 PrevDecl,
2404 PrevDecl->getSpecializationKind(),
2405 PrevDecl->getPointOfInstantiation(),
2406 Ignored))
Craig Topperc3ec1492014-05-26 06:22:03 +00002407 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002408
2409 // If PrevDecl was a definition and D is also a definition, diagnose.
2410 // This happens in cases like:
2411 //
2412 // template<typename T, typename U>
2413 // struct Outer {
2414 // template<typename X> struct Inner;
2415 // template<> struct Inner<T> {};
2416 // template<> struct Inner<U> {};
2417 // };
2418 //
2419 // Outer<int, int> outer; // error: the explicit specializations of Inner
2420 // // have the same signature.
2421 if (PrevDecl && PrevDecl->getDefinition() &&
2422 D->isThisDeclarationADefinition()) {
2423 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2424 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2425 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00002426 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002427 }
2428
2429 // Create the class template partial specialization declaration.
2430 ClassTemplateSpecializationDecl *InstD
2431 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2432 D->getTagKind(),
2433 Owner,
2434 D->getLocStart(),
2435 D->getLocation(),
2436 InstClassTemplate,
2437 Converted.data(),
2438 Converted.size(),
2439 PrevDecl);
2440
2441 // Add this partial specialization to the set of class template partial
2442 // specializations.
2443 if (!PrevDecl)
2444 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2445
2446 // Substitute the nested name specifier, if any.
2447 if (SubstQualifier(D, InstD))
Craig Topperc3ec1492014-05-26 06:22:03 +00002448 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002449
2450 // Build the canonical type that describes the converted template
2451 // arguments of the class template explicit specialization.
2452 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2453 TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2454 SemaRef.Context.getRecordType(InstD));
2455
2456 // Build the fully-sugared type for this class template
2457 // specialization as the user wrote in the specialization
2458 // itself. This means that we'll pretty-print the type retrieved
2459 // from the specialization's declaration the way that the user
2460 // actually wrote the specialization, rather than formatting the
2461 // name based on the "canonical" representation used to store the
2462 // template arguments in the specialization.
2463 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2464 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2465 CanonType);
2466
2467 InstD->setAccess(D->getAccess());
2468 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2469 InstD->setSpecializationKind(D->getSpecializationKind());
2470 InstD->setTypeAsWritten(WrittenTy);
2471 InstD->setExternLoc(D->getExternLoc());
2472 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2473
2474 Owner->addDecl(InstD);
2475
2476 // Instantiate the members of the class-scope explicit specialization eagerly.
2477 // We don't have support for lazy instantiation of an explicit specialization
2478 // yet, and MSVC eagerly instantiates in this case.
2479 if (D->isThisDeclarationADefinition() &&
2480 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2481 TSK_ImplicitInstantiation,
2482 /*Complain=*/true))
Craig Topperc3ec1492014-05-26 06:22:03 +00002483 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002484
2485 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002486}
2487
Larisse Voufo39a1e502013-08-06 01:03:05 +00002488Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2489 VarTemplateSpecializationDecl *D) {
2490
2491 TemplateArgumentListInfo VarTemplateArgsInfo;
2492 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2493 assert(VarTemplate &&
2494 "A template specialization without specialized template?");
2495
2496 // Substitute the current template arguments.
2497 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2498 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2499 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2500
2501 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2502 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002503 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002504
2505 // Check that the template argument list is well-formed for this template.
2506 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002507 if (SemaRef.CheckTemplateArgumentList(
2508 VarTemplate, VarTemplate->getLocStart(),
2509 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002510 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002511 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002512
2513 // Find the variable template specialization declaration that
2514 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002515 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002516 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
Craig Topper7e0daca2014-06-26 04:58:53 +00002517 Converted, InsertPos))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002518 // If we already have a variable template specialization, return it.
2519 return VarSpec;
2520
2521 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2522 VarTemplateArgsInfo, Converted);
2523}
2524
2525Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2526 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2527 const TemplateArgumentListInfo &TemplateArgsInfo,
Craig Topper00bbdcf2014-06-28 23:22:23 +00002528 ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002529
2530 // If this is the variable for an anonymous struct or union,
2531 // instantiate the anonymous struct/union type first.
2532 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2533 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2534 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +00002535 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002536
2537 // Do substitution on the type of the declaration
2538 TypeSourceInfo *DI =
2539 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2540 D->getTypeSpecStartLoc(), D->getDeclName());
2541 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002542 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002543
2544 if (DI->getType()->isFunctionType()) {
2545 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2546 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00002547 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002548 }
2549
2550 // Build the instantiated declaration
2551 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2552 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2553 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2554 Converted.size());
2555 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00002556 if (InsertPos)
2557 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002558
2559 // Substitute the nested name specifier, if any.
2560 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +00002561 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002562
2563 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00002564 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002565
2566 return Var;
2567}
2568
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002569Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2570 llvm_unreachable("@defs is not supported in Objective-C++");
2571}
2572
2573Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2574 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2575 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2576 DiagnosticsEngine::Error,
2577 "cannot instantiate %0 yet");
2578 SemaRef.Diag(D->getLocation(), DiagID)
2579 << D->getDeclKindName();
2580
Craig Topperc3ec1492014-05-26 06:22:03 +00002581 return nullptr;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002582}
2583
2584Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2585 llvm_unreachable("Unexpected decl");
2586}
2587
John McCall76d824f2009-08-25 22:02:44 +00002588Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002589 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00002590 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00002591 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00002592 return nullptr;
Douglas Gregor71ad4772010-02-16 19:28:15 +00002593
Douglas Gregord7e7a512009-03-17 21:15:40 +00002594 return Instantiator.Visit(D);
2595}
2596
John McCall87a44eb2009-08-20 01:44:21 +00002597/// \brief Instantiates a nested template parameter list in the current
2598/// instantiation context.
2599///
2600/// \param L The parameter list to instantiate
2601///
2602/// \returns NULL if there was an error
2603TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00002604TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00002605 // Get errors for all the parameters before bailing out.
2606 bool Invalid = false;
2607
2608 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002609 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00002610 ParamVector Params;
2611 Params.reserve(N);
2612 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2613 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002614 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00002615 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00002616 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00002617 }
2618
2619 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00002620 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +00002621 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00002622
2623 TemplateParameterList *InstL
2624 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2625 L->getLAngleLoc(), &Params.front(), N,
2626 L->getRAngleLoc());
2627 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00002628}
John McCall87a44eb2009-08-20 01:44:21 +00002629
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002630/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002631/// specialization.
2632///
2633/// \param ClassTemplate the (instantiated) class template that is partially
2634// specialized by the instantiation of \p PartialSpec.
2635///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002636/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002637/// specialization that we are instantiating.
2638///
Douglas Gregor869853e2010-11-10 19:44:59 +00002639/// \returns The instantiated partial specialization, if successful; otherwise,
2640/// NULL to indicate an error.
2641ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00002642TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2643 ClassTemplateDecl *ClassTemplate,
2644 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00002645 // Create a local instantiation scope for this class template partial
2646 // specialization, which will contain the instantiations of the template
2647 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00002648 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002649
Douglas Gregor21610382009-10-29 00:04:11 +00002650 // Substitute into the template parameters of the class template partial
2651 // specialization.
2652 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2653 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2654 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002655 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002656
Douglas Gregor21610382009-10-29 00:04:11 +00002657 // Substitute into the template arguments of the class template partial
2658 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002659 const ASTTemplateArgumentListInfo *TemplArgInfo
2660 = PartialSpec->getTemplateArgsAsWritten();
2661 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2662 TemplArgInfo->RAngleLoc);
2663 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2664 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002665 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002666 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002667
Douglas Gregor21610382009-10-29 00:04:11 +00002668 // Check that the template argument list is well-formed for this
2669 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002670 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002671 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00002672 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002673 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002674 false,
2675 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002676 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002677
2678 // Figure out where to insert this class template partial specialization
2679 // in the member template's set of class template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002680 void *InsertPos = nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002681 ClassTemplateSpecializationDecl *PrevDecl
Craig Topper7e0daca2014-06-26 04:58:53 +00002682 = ClassTemplate->findPartialSpecialization(Converted, 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 =
Craig Topper7e0daca2014-06-26 04:58:53 +00002806 VarTemplate->findPartialSpecialization(Converted, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002807
2808 // Build the canonical type that describes the converted template
2809 // arguments of the variable template partial specialization.
2810 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2811 TemplateName(VarTemplate), Converted.data(), Converted.size());
2812
2813 // Build the fully-sugared type for this variable template
2814 // specialization as the user wrote in the specialization
2815 // itself. This means that we'll pretty-print the type retrieved
2816 // from the specialization's declaration the way that the user
2817 // actually wrote the specialization, rather than formatting the
2818 // name based on the "canonical" representation used to store the
2819 // template arguments in the specialization.
2820 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2821 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2822 CanonType);
2823
2824 if (PrevDecl) {
2825 // We've already seen a partial specialization with the same template
2826 // parameters and template arguments. This can happen, for example, when
2827 // substituting the outer template arguments ends up causing two
2828 // variable template partial specializations of a member variable template
2829 // to have identical forms, e.g.,
2830 //
2831 // template<typename T, typename U>
2832 // struct Outer {
2833 // template<typename X, typename Y> pair<X,Y> p;
2834 // template<typename Y> pair<T, Y> p;
2835 // template<typename Y> pair<U, Y> p;
2836 // };
2837 //
2838 // Outer<int, int> outer; // error: the partial specializations of Inner
2839 // // have the same signature.
2840 SemaRef.Diag(PartialSpec->getLocation(),
2841 diag::err_var_partial_spec_redeclared)
2842 << WrittenTy->getType();
2843 SemaRef.Diag(PrevDecl->getLocation(),
2844 diag::note_var_prev_partial_spec_here);
Craig Topperc3ec1492014-05-26 06:22:03 +00002845 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002846 }
2847
2848 // Do substitution on the type of the declaration
2849 TypeSourceInfo *DI = SemaRef.SubstType(
2850 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2851 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2852 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002853 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002854
2855 if (DI->getType()->isFunctionType()) {
2856 SemaRef.Diag(PartialSpec->getLocation(),
2857 diag::err_variable_instantiates_to_function)
2858 << PartialSpec->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00002859 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002860 }
2861
2862 // Create the variable template partial specialization declaration.
2863 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2864 VarTemplatePartialSpecializationDecl::Create(
2865 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2866 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2867 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smithb2f61b42013-08-22 23:27:37 +00002868 Converted.size(), InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002869
2870 // Substitute the nested name specifier, if any.
2871 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00002872 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002873
2874 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2875 InstPartialSpec->setTypeAsWritten(WrittenTy);
2876
Larisse Voufo39a1e502013-08-06 01:03:05 +00002877 // Add this partial specialization to the set of variable template partial
2878 // specializations. The instantiation of the initializer is not necessary.
Craig Topperc3ec1492014-05-26 06:22:03 +00002879 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002880
Larisse Voufo4cda4612013-08-22 00:28:27 +00002881 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00002882 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002883
Larisse Voufo39a1e502013-08-06 01:03:05 +00002884 return InstPartialSpec;
2885}
2886
John McCall58f10c32010-03-11 09:03:00 +00002887TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00002888TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002889 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00002890 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2891 assert(OldTInfo && "substituting function without type source info");
2892 assert(Params.empty() && "parameter vector is non-empty at start");
Craig Topperc3ec1492014-05-26 06:22:03 +00002893
2894 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002895 unsigned ThisTypeQuals = 0;
2896 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002897 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00002898 ThisTypeQuals = Method->getTypeQualifiers();
2899 }
2900
John McCallb29f78f2010-04-09 17:38:44 +00002901 TypeSourceInfo *NewTInfo
2902 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2903 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002904 D->getDeclName(),
2905 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00002906 if (!NewTInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00002907 return nullptr;
Douglas Gregor21342092009-03-24 00:38:23 +00002908
Reid Klecknera09e44c2013-07-31 21:00:18 +00002909 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2910 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2911 if (NewTInfo != OldTInfo) {
2912 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00002913 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00002914 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00002915 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002916 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00002917 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002918 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00002919 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2920
David Blaikie05785d12013-02-20 22:23:23 +00002921 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00002922 if (OldParam->isParameterPack())
2923 NumArgumentsInExpansion =
2924 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2925 TemplateArgs);
2926 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002927 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00002928 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002929 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00002930 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00002931 Scope->InstantiatedLocal(OldParam, NewParam);
2932 } else {
2933 // Parameter pack expansion: make the instantiation an argument pack.
2934 Scope->MakeInstantiatedLocalArgPack(OldParam);
2935 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002936 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00002937 Params.push_back(NewParam);
2938 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2939 }
Douglas Gregorf3010112011-01-07 16:43:16 +00002940 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002941 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002942 } else {
2943 // The function type itself was not dependent and therefore no
2944 // substitution occurred. However, we still need to instantiate
2945 // the function parameters themselves.
2946 const FunctionProtoType *OldProto =
2947 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002948 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
2949 ++i) {
2950 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00002951 if (!OldParam) {
2952 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00002953 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00002954 continue;
2955 }
2956
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002957 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00002958 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002959 if (!Parm)
Craig Topperc3ec1492014-05-26 06:22:03 +00002960 return nullptr;
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002961 Params.push_back(Parm);
2962 }
Douglas Gregor940bca72010-04-12 07:48:19 +00002963 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002964 } else {
2965 // If the type of this function, after ignoring parentheses, is not
2966 // *directly* a function type, then we're instantiating a function that
2967 // was declared via a typedef or with attributes, e.g.,
2968 //
2969 // typedef int functype(int, int);
2970 // functype func;
2971 // int __cdecl meth(int, int);
2972 //
2973 // In this case, we'll just go instantiate the ParmVarDecls that we
2974 // synthesized in the method declaration.
2975 SmallVector<QualType, 4> ParamTypes;
2976 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2977 D->getNumParams(), TemplateArgs, ParamTypes,
2978 &Params))
Craig Topperc3ec1492014-05-26 06:22:03 +00002979 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00002980 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002981
John McCall58f10c32010-03-11 09:03:00 +00002982 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00002983}
2984
Richard Smithf623c962012-04-17 00:58:00 +00002985/// Introduce the instantiated function parameters into the local
2986/// instantiation scope, and set the parameter names to those used
2987/// in the template.
2988static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2989 const FunctionDecl *PatternDecl,
2990 LocalInstantiationScope &Scope,
2991 const MultiLevelTemplateArgumentList &TemplateArgs) {
2992 unsigned FParamIdx = 0;
2993 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2994 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2995 if (!PatternParam->isParameterPack()) {
2996 // Simple case: not a parameter pack.
2997 assert(FParamIdx < Function->getNumParams());
2998 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smithaae40582014-03-13 00:28:45 +00002999 // If the parameter's type is not dependent, update it to match the type
3000 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3001 // the pattern's type here. If the type is dependent, they can't differ,
3002 // per core issue 1668.
3003 // FIXME: Updating the type to work around this is at best fragile.
3004 if (!PatternDecl->getType()->isDependentType())
3005 FunctionParam->setType(PatternParam->getType());
3006
Richard Smithf623c962012-04-17 00:58:00 +00003007 FunctionParam->setDeclName(PatternParam->getDeclName());
3008 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3009 ++FParamIdx;
3010 continue;
3011 }
3012
3013 // Expand the parameter pack.
3014 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003015 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003016 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00003017 assert(NumArgumentsInExpansion &&
3018 "should only be called when all template arguments are known");
3019 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00003020 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smithaae40582014-03-13 00:28:45 +00003021 if (!PatternDecl->getType()->isDependentType())
3022 FunctionParam->setType(PatternParam->getType());
3023
Richard Smithf623c962012-04-17 00:58:00 +00003024 FunctionParam->setDeclName(PatternParam->getDeclName());
3025 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3026 ++FParamIdx;
3027 }
3028 }
3029}
3030
3031static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
3032 const FunctionProtoType *Proto,
3033 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smithd3729422012-04-19 00:08:28 +00003034 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
3035
Richard Smithf623c962012-04-17 00:58:00 +00003036 // C++11 [expr.prim.general]p3:
3037 // If a declaration declares a member function or member function
3038 // template of a class X, the expression this is a prvalue of type
3039 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3040 // and the end of the function-definition, member-declarator, or
3041 // declarator.
Craig Topperc3ec1492014-05-26 06:22:03 +00003042 CXXRecordDecl *ThisContext = nullptr;
Richard Smithf623c962012-04-17 00:58:00 +00003043 unsigned ThisTypeQuals = 0;
3044 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
3045 ThisContext = Method->getParent();
3046 ThisTypeQuals = Method->getTypeQualifiers();
3047 }
3048 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003049 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithf623c962012-04-17 00:58:00 +00003050
3051 // The function has an exception specification or a "noreturn"
3052 // attribute. Substitute into each of the exception types.
3053 SmallVector<QualType, 4> Exceptions;
3054 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
3055 // FIXME: Poor location information!
3056 if (const PackExpansionType *PackExpansion
3057 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
3058 // We have a pack expansion. Instantiate it.
3059 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3060 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
3061 Unexpanded);
3062 assert(!Unexpanded.empty() &&
3063 "Pack expansion without parameter packs?");
3064
3065 bool Expand = false;
3066 bool RetainExpansion = false;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003067 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithf623c962012-04-17 00:58:00 +00003068 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
3069 SourceRange(),
3070 Unexpanded,
3071 TemplateArgs,
3072 Expand,
3073 RetainExpansion,
3074 NumExpansions))
3075 break;
3076
3077 if (!Expand) {
3078 // We can't expand this pack expansion into separate arguments yet;
3079 // just substitute into the pattern and create a new pack expansion
3080 // type.
3081 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3082 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3083 TemplateArgs,
3084 New->getLocation(), New->getDeclName());
3085 if (T.isNull())
3086 break;
3087
3088 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
3089 Exceptions.push_back(T);
3090 continue;
3091 }
3092
3093 // Substitute into the pack expansion pattern for each template
3094 bool Invalid = false;
3095 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
3096 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
3097
3098 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3099 TemplateArgs,
3100 New->getLocation(), New->getDeclName());
3101 if (T.isNull()) {
3102 Invalid = true;
3103 break;
3104 }
3105
3106 Exceptions.push_back(T);
3107 }
3108
3109 if (Invalid)
3110 break;
3111
3112 continue;
3113 }
3114
3115 QualType T
3116 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
3117 New->getLocation(), New->getDeclName());
3118 if (T.isNull() ||
3119 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
3120 continue;
3121
3122 Exceptions.push_back(T);
3123 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003124 Expr *NoexceptExpr = nullptr;
Richard Smithf623c962012-04-17 00:58:00 +00003125 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
3126 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3127 Sema::ConstantEvaluated);
3128 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
3129 if (E.isUsable())
3130 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
3131
3132 if (E.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003133 NoexceptExpr = E.get();
Richard Smithf623c962012-04-17 00:58:00 +00003134 if (!NoexceptExpr->isTypeDependent() &&
3135 !NoexceptExpr->isValueDependent())
Douglas Gregore2b37442012-05-04 22:38:52 +00003136 NoexceptExpr
3137 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003138 nullptr, diag::err_noexcept_needs_constant_expression,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003139 /*AllowFold*/ false).get();
Richard Smithf623c962012-04-17 00:58:00 +00003140 }
3141 }
3142
Richard Smith8acb4282014-07-31 21:57:55 +00003143 FunctionProtoType::ExceptionSpecInfo ESI;
3144 ESI.Type = Proto->getExceptionSpecType();
3145 ESI.Exceptions = Exceptions;
3146 ESI.NoexceptExpr = NoexceptExpr;
Richard Smithf623c962012-04-17 00:58:00 +00003147
Richard Smith8acb4282014-07-31 21:57:55 +00003148 SemaRef.UpdateExceptionSpec(New, ESI);
Richard Smithf623c962012-04-17 00:58:00 +00003149}
3150
3151void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3152 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003153 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3154 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003155 return;
3156
3157 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3158 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003159 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003160 // We hit the instantiation depth limit. Clear the exception specification
3161 // so that our callers don't have to cope with EST_Uninstantiated.
Richard Smith8acb4282014-07-31 21:57:55 +00003162 UpdateExceptionSpec(Decl, EST_None);
Richard Smithf623c962012-04-17 00:58:00 +00003163 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003164 }
Richard Smithf623c962012-04-17 00:58:00 +00003165
3166 // Enter the scope of this instantiation. We don't use
3167 // PushDeclContext because we don't have a scope.
3168 Sema::ContextRAII savedContext(*this, Decl);
3169 LocalInstantiationScope Scope(*this);
3170
3171 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003172 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
Richard Smithf623c962012-04-17 00:58:00 +00003173
Richard Smithd3729422012-04-19 00:08:28 +00003174 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3175 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003176
Richard Smithd3729422012-04-19 00:08:28 +00003177 ::InstantiateExceptionSpec(*this, Decl,
3178 Template->getType()->castAs<FunctionProtoType>(),
3179 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003180}
3181
Mike Stump11289f42009-09-09 15:08:12 +00003182/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003183/// declaration (New) from the corresponding fields of its template (Tmpl).
3184///
3185/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003186bool
3187TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003188 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003189 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003190 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003191
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003192 // Forward the mangling number from the template to the instantiated decl.
3193 SemaRef.Context.setManglingNumber(New,
3194 SemaRef.Context.getManglingNumber(Tmpl));
3195
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003196 // If we are performing substituting explicitly-specified template arguments
3197 // or deduced template arguments into a function template and we reach this
3198 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003199 // to keeping the new function template specialization. We therefore
3200 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003201 // into a template instantiation for this specific function template
3202 // specialization, which is not a SFINAE context, so that we diagnose any
3203 // further errors in the declaration itself.
3204 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3205 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3206 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3207 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003208 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003209 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003210 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003211 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003212 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003213 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003214 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003215 }
3216 }
Mike Stump11289f42009-09-09 15:08:12 +00003217
Douglas Gregor049bdca2009-12-08 17:45:32 +00003218 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3219 assert(Proto && "Function template without prototype?");
3220
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003221 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003222 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003223
Richard Smithf623c962012-04-17 00:58:00 +00003224 // DR1330: In C++11, defer instantiation of a non-trivial
3225 // exception specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003226 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith8acb4282014-07-31 21:57:55 +00003227 EPI.ExceptionSpec.Type != EST_None &&
3228 EPI.ExceptionSpec.Type != EST_DynamicNone &&
3229 EPI.ExceptionSpec.Type != EST_BasicNoexcept) {
Richard Smithd3729422012-04-19 00:08:28 +00003230 FunctionDecl *ExceptionSpecTemplate = Tmpl;
Richard Smith8acb4282014-07-31 21:57:55 +00003231 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3232 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003233 ExceptionSpecificationType NewEST = EST_Uninstantiated;
Richard Smith8acb4282014-07-31 21:57:55 +00003234 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
Richard Smith185be182013-04-10 05:48:59 +00003235 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003236
Richard Smithf623c962012-04-17 00:58:00 +00003237 // Mark the function has having an uninstantiated exception specification.
3238 const FunctionProtoType *NewProto
3239 = New->getType()->getAs<FunctionProtoType>();
3240 assert(NewProto && "Template instantiation without function prototype?");
3241 EPI = NewProto->getExtProtoInfo();
Richard Smith8acb4282014-07-31 21:57:55 +00003242 EPI.ExceptionSpec.Type = NewEST;
3243 EPI.ExceptionSpec.SourceDecl = New;
3244 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003245 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003246 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003247 } else {
3248 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3249 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003250 }
3251
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003252 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003253 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003254 Tmpl->isDefined(Definition);
3255
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003256 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3257 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003258
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003259 return false;
3260}
3261
Douglas Gregor21342092009-03-24 00:38:23 +00003262/// \brief Initializes common fields of an instantiated method
3263/// declaration (New) from the corresponding fields of its template
3264/// (Tmpl).
3265///
3266/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003267bool
3268TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003269 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003270 if (InitFunctionInstantiation(New, Tmpl))
3271 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003272
Douglas Gregor21342092009-03-24 00:38:23 +00003273 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003274 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003275 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003276
Douglas Gregor21342092009-03-24 00:38:23 +00003277 // FIXME: New needs a pointer to Tmpl
3278 return false;
3279}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003280
3281/// \brief Instantiate the definition of the given function from its
3282/// template.
3283///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003284/// \param PointOfInstantiation the point at which the instantiation was
3285/// required. Note that this is not precisely a "point of instantiation"
3286/// for the function, but it's close.
3287///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003288/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003289/// function template specialization or member function of a class template
3290/// specialization.
3291///
3292/// \param Recursive if true, recursively instantiates any functions that
3293/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003294///
3295/// \param DefinitionRequired if true, then we are performing an explicit
3296/// instantiation where the body of the function is required. Complain if
3297/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003298void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003299 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003300 bool Recursive,
3301 bool DefinitionRequired) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003302 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00003303 return;
3304
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003305 // Never instantiate an explicit specialization except if it is a class scope
3306 // explicit specialization.
3307 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3308 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003309 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003310
Douglas Gregor24c332b2009-05-14 21:06:31 +00003311 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003312 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003313 assert(PatternDecl && "instantiating a non-template");
3314
3315 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3316 assert(PatternDecl && "template definition is not a template");
3317 if (!Pattern) {
3318 // Try to find a defaulted definition
3319 PatternDecl->isDefined(PatternDecl);
Alexis Hunt92a0adf2011-05-25 22:02:25 +00003320 }
Alexis Hunt23f6b832011-05-27 20:00:14 +00003321 assert(PatternDecl && "template definition is not a template");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003322
Francois Pichet1c229c02011-04-22 22:18:13 +00003323 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003324 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003325 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00003326 PendingInstantiations.push_back(
3327 std::make_pair(Function, PointOfInstantiation));
3328 return;
3329 }
3330
Nico Weberae4bb8c2014-08-15 23:21:41 +00003331 // If we're performing recursive template instantiation, create our own
3332 // queue of pending implicit instantiations that we will instantiate later,
3333 // while we're still within our own instantiation context.
3334 // This has to happen before LateTemplateParser below is called, so that
3335 // it marks vtables used in late parsed templates as used.
3336 SavePendingLocalImplicitInstantiationsRAII
3337 SavedPendingLocalImplicitInstantiations(*this);
3338 std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII>
3339 SavePendingInstantiationsAndVTableUses;
3340 if (Recursive) {
3341 SavePendingInstantiationsAndVTableUses.reset(
3342 new SavePendingInstantiationsAndVTableUsesRAII(*this));
3343 }
3344
David Majnemerf0a84f22013-08-16 08:29:13 +00003345 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003346 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003347 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003348 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003349 // FIXME: Optimize to allow individual templates to be deserialized.
3350 if (PatternDecl->isFromASTFile())
3351 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3352
3353 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3354 assert(LPT && "missing LateParsedTemplate");
3355 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet1c229c02011-04-22 22:18:13 +00003356 Pattern = PatternDecl->getBody(PatternDecl);
3357 }
3358
Alexis Hunt23f6b832011-05-27 20:00:14 +00003359 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003360 if (DefinitionRequired) {
3361 if (Function->getPrimaryTemplate())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003362 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003363 diag::err_explicit_instantiation_undefined_func_template)
3364 << Function->getPrimaryTemplate();
3365 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003366 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003367 diag::err_explicit_instantiation_undefined_member)
3368 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003369
Douglas Gregora8b89d22009-10-15 14:05:49 +00003370 if (PatternDecl)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003371 Diag(PatternDecl->getLocation(),
Douglas Gregora8b89d22009-10-15 14:05:49 +00003372 diag::note_explicit_instantiation_here);
Douglas Gregorfd7224f2010-05-17 17:57:54 +00003373 Function->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003374 } else if (Function->getTemplateSpecializationKind()
3375 == TSK_ExplicitInstantiationDefinition) {
Nico Weberae4bb8c2014-08-15 23:21:41 +00003376 assert(!Recursive);
Chandler Carruth54080172010-08-25 08:44:16 +00003377 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003378 std::make_pair(Function, PointOfInstantiation));
Douglas Gregora8b89d22009-10-15 14:05:49 +00003379 }
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003380
Douglas Gregor24c332b2009-05-14 21:06:31 +00003381 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00003382 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003383
Richard Smith2a7d4812013-05-04 07:00:32 +00003384 // C++1y [temp.explicit]p10:
3385 // Except for inline functions, declarations with types deduced from their
3386 // initializer or return value, and class template specializations, other
3387 // explicit instantiation declarations have the effect of suppressing the
3388 // implicit instantiation of the entity to which they refer.
Alp Toker314cc812014-01-25 16:55:45 +00003389 if (Function->getTemplateSpecializationKind() ==
3390 TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003391 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00003392 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003393 return;
Mike Stump11289f42009-09-09 15:08:12 +00003394
Richard Smith195d8ef2014-05-29 03:15:31 +00003395 if (PatternDecl->isInlined()) {
3396 // Function, and all later redeclarations of it (from imported modules,
3397 // for instance), are now implicitly inline.
3398 for (auto *D = Function->getMostRecentDecl(); /**/;
3399 D = D->getPreviousDecl()) {
3400 D->setImplicitlyInline();
3401 if (D == Function)
3402 break;
3403 }
3404 }
Richard Smithf3814ad2013-01-25 00:08:28 +00003405
Douglas Gregor85673582009-05-18 17:01:57 +00003406 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003407 if (Inst.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003408 return;
3409
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00003410 // Copy the inner loc start from the pattern.
3411 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3412
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003413 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00003414 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00003415
Douglas Gregorb4850462009-05-14 23:26:13 +00003416 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003417 // recorded, unless we're actually a member function within a local
3418 // class, in which case we need to merge our results with the parent
3419 // scope (of the enclosing function).
3420 bool MergeWithParentScope = false;
3421 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3422 MergeWithParentScope = Rec->isLocalClass();
3423
3424 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00003425
Richard Smithbd305122012-12-11 01:14:52 +00003426 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003427 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00003428 else {
Craig Topperc3ec1492014-05-26 06:22:03 +00003429 ActOnStartOfFunctionDef(nullptr, Function);
Richard Smithbd305122012-12-11 01:14:52 +00003430
3431 // Enter the scope of this instantiation. We don't use
3432 // PushDeclContext because we don't have a scope.
3433 Sema::ContextRAII savedContext(*this, Function);
3434
3435 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003436 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
Richard Smithbd305122012-12-11 01:14:52 +00003437
3438 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3439 TemplateArgs);
3440
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003441 // If this is a constructor, instantiate the member initializers.
3442 if (const CXXConstructorDecl *Ctor =
3443 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3444 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3445 TemplateArgs);
3446 }
3447
3448 // Instantiate the function body.
3449 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3450
3451 if (Body.isInvalid())
3452 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003453
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003454 ActOnFinishFunctionBody(Function, Body.get(),
3455 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00003456
3457 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3458
Richard Smithd28ac5b2014-03-22 23:33:22 +00003459 if (auto *Listener = getASTMutationListener())
3460 Listener->FunctionDefinitionInstantiated(Function);
Richard Smith0ac1b8f2014-03-22 01:43:32 +00003461
Richard Smithbd305122012-12-11 01:14:52 +00003462 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00003463 }
3464
Douglas Gregor28ad4b52009-05-26 20:50:29 +00003465 DeclGroupRef DG(Function);
3466 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003467
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003468 // This class may have local implicit instantiations that need to be
3469 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003470 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003471 Scope.Exit();
3472
Douglas Gregordda7ced2009-06-30 17:20:14 +00003473 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003474 // Define any pending vtables.
3475 DefineUsedVTables();
3476
Douglas Gregordda7ced2009-06-30 17:20:14 +00003477 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003478 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003479 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003480
Nico Weberccec9d82014-08-15 22:29:14 +00003481 // Restore PendingInstantiations and VTableUses.
3482 SavePendingInstantiationsAndVTableUses.reset();
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;
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00003682 Expr *InitExpr = Init.get();
3683
Richard Smith95b83e92014-07-10 20:53:43 +00003684 if (Var->hasAttr<DLLImportAttr>() &&
3685 (!InitExpr ||
3686 !InitExpr->isConstantInitializer(getASTContext(), false))) {
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00003687 // Do not dynamically initialize dllimport variables.
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00003688 } else if (InitExpr) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003689 bool DirectInit = OldVar->isDirectInit();
Hans Wennborg91ebe6e2014-06-10 00:55:51 +00003690 AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003691 } else
3692 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3693 } else {
3694 // FIXME: Not too happy about invalidating the declaration
3695 // because of a bogus initializer.
3696 Var->setInvalidDecl();
3697 }
3698
3699 PopExpressionEvaluationContext();
3700 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3701 !Var->isCXXForRangeDecl())
3702 ActOnUninitializedDecl(Var, false);
3703}
3704
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003705/// \brief Instantiate the definition of the given variable from its
3706/// template.
3707///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003708/// \param PointOfInstantiation the point at which the instantiation was
3709/// required. Note that this is not precisely a "point of instantiation"
3710/// for the function, but it's close.
3711///
3712/// \param Var the already-instantiated declaration of a static member
3713/// variable of a class template specialization.
3714///
3715/// \param Recursive if true, recursively instantiates any functions that
3716/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003717///
3718/// \param DefinitionRequired if true, then we are performing an explicit
3719/// instantiation where an out-of-line definition of the member variable
3720/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003721void Sema::InstantiateStaticDataMemberDefinition(
3722 SourceLocation PointOfInstantiation,
3723 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003724 bool Recursive,
3725 bool DefinitionRequired) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003726 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3727 DefinitionRequired);
3728}
3729
3730void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3731 VarDecl *Var, bool Recursive,
3732 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003733 if (Var->isInvalidDecl())
3734 return;
Mike Stump11289f42009-09-09 15:08:12 +00003735
Larisse Voufo39a1e502013-08-06 01:03:05 +00003736 VarTemplateSpecializationDecl *VarSpec =
3737 dyn_cast<VarTemplateSpecializationDecl>(Var);
Craig Topperc3ec1492014-05-26 06:22:03 +00003738 VarDecl *PatternDecl = nullptr, *Def = nullptr;
Richard Smith8809a0c2013-09-27 20:14:12 +00003739 MultiLevelTemplateArgumentList TemplateArgs =
3740 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00003741
Larisse Voufo39a1e502013-08-06 01:03:05 +00003742 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003743 // If this is a variable template specialization, make sure that it is
3744 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003745 bool InstantiationDependent = false;
3746 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3747 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3748 "Only instantiate variable template specializations that are "
3749 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00003750 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003751
Richard Smith8809a0c2013-09-27 20:14:12 +00003752 // Find the variable initialization that we'll be substituting. If the
3753 // pattern was instantiated from a member template, look back further to
3754 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003755 assert(VarSpec->getSpecializedTemplate() &&
3756 "Specialization without specialized template?");
3757 llvm::PointerUnion<VarTemplateDecl *,
3758 VarTemplatePartialSpecializationDecl *> PatternPtr =
3759 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003760 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003761 VarTemplatePartialSpecializationDecl *Tmpl =
3762 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3763 while (VarTemplatePartialSpecializationDecl *From =
3764 Tmpl->getInstantiatedFromMember()) {
3765 if (Tmpl->isMemberSpecialization())
3766 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003767
Richard Smith8809a0c2013-09-27 20:14:12 +00003768 Tmpl = From;
3769 }
3770 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003771 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00003772 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3773 while (VarTemplateDecl *From =
3774 Tmpl->getInstantiatedFromMemberTemplate()) {
3775 if (Tmpl->isMemberSpecialization())
3776 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003777
Richard Smith8809a0c2013-09-27 20:14:12 +00003778 Tmpl = From;
3779 }
3780 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003781 }
Richard Smith8809a0c2013-09-27 20:14:12 +00003782
3783 // If this is a static data member template, there might be an
3784 // uninstantiated initializer on the declaration. If so, instantiate
3785 // it now.
3786 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00003787 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00003788 !Var->hasInit()) {
3789 // FIXME: Factor out the duplicated instantiation context setup/tear down
3790 // code here.
3791 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003792 if (Inst.isInvalid())
Richard Smith8809a0c2013-09-27 20:14:12 +00003793 return;
3794
3795 // If we're performing recursive template instantiation, create our own
3796 // queue of pending implicit instantiations that we will instantiate
3797 // later, while we're still within our own instantiation context.
Nico Weberccec9d82014-08-15 22:29:14 +00003798 std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII>
3799 SavePendingInstantiationsAndVTableUses;
Richard Smith8809a0c2013-09-27 20:14:12 +00003800 if (Recursive) {
Nico Weberccec9d82014-08-15 22:29:14 +00003801 SavePendingInstantiationsAndVTableUses.reset(
3802 new SavePendingInstantiationsAndVTableUsesRAII(*this));
Richard Smith8809a0c2013-09-27 20:14:12 +00003803 }
3804
3805 LocalInstantiationScope Local(*this);
3806
3807 // Enter the scope of this instantiation. We don't use
3808 // PushDeclContext because we don't have a scope.
3809 ContextRAII PreviousContext(*this, Var->getDeclContext());
3810 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3811 PreviousContext.pop();
3812
3813 // FIXME: Need to inform the ASTConsumer that we instantiated the
3814 // initializer?
3815
3816 // This variable may have local implicit instantiations that need to be
3817 // instantiated within this scope.
3818 PerformPendingInstantiations(/*LocalOnly=*/true);
3819
3820 Local.Exit();
3821
3822 if (Recursive) {
3823 // Define any newly required vtables.
3824 DefineUsedVTables();
3825
3826 // Instantiate any pending implicit instantiations found during the
3827 // instantiation of this template.
3828 PerformPendingInstantiations();
3829
Nico Weberccec9d82014-08-15 22:29:14 +00003830 // Restore PendingInstantiations and VTableUses.
3831 SavePendingInstantiationsAndVTableUses.reset();
Richard Smith8809a0c2013-09-27 20:14:12 +00003832 }
3833 }
3834
3835 // Find actual definition
3836 Def = PatternDecl->getDefinition(getASTContext());
3837 } else {
3838 // If this is a static data member, find its out-of-line definition.
3839 assert(Var->isStaticDataMember() && "not a static data member?");
3840 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3841
3842 assert(PatternDecl && "data member was not instantiated from a template?");
3843 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3844 Def = PatternDecl->getOutOfLineDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003845 }
3846
Richard Smith8809a0c2013-09-27 20:14:12 +00003847 // If we don't have a definition of the variable template, we won't perform
3848 // any instantiation. Rather, we rely on the user to instantiate this
3849 // definition (or provide a specialization for it) in another translation
3850 // unit.
3851 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003852 if (DefinitionRequired) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003853 if (VarSpec)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003854 Diag(PointOfInstantiation,
Richard Smith8809a0c2013-09-27 20:14:12 +00003855 diag::err_explicit_instantiation_undefined_var_template) << Var;
3856 else
Larisse Voufo39a1e502013-08-06 01:03:05 +00003857 Diag(PointOfInstantiation,
3858 diag::err_explicit_instantiation_undefined_member)
Richard Smith8809a0c2013-09-27 20:14:12 +00003859 << 2 << Var->getDeclName() << Var->getDeclContext();
3860 Diag(PatternDecl->getLocation(),
3861 diag::note_explicit_instantiation_here);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003862 if (VarSpec)
3863 Var->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003864 } else if (Var->getTemplateSpecializationKind()
3865 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003866 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003867 std::make_pair(Var, PointOfInstantiation));
3868 }
3869
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003870 return;
3871 }
3872
Rafael Espindola189fa742012-03-05 10:54:55 +00003873 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3874
Douglas Gregor86d142a2009-10-08 07:24:58 +00003875 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00003876 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003877 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003878
Larisse Voufo39a1e502013-08-06 01:03:05 +00003879 // C++11 [temp.explicit]p10:
3880 // Except for inline functions, [...] explicit instantiation declarations
3881 // have the effect of suppressing the implicit instantiation of the entity
3882 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00003883 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003884 return;
Mike Stump11289f42009-09-09 15:08:12 +00003885
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003886 // Make sure to pass the instantiated variable to the consumer at the end.
3887 struct PassToConsumerRAII {
3888 ASTConsumer &Consumer;
3889 VarDecl *Var;
3890
3891 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3892 : Consumer(Consumer), Var(Var) { }
3893
3894 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00003895 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003896 }
3897 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003898
Richard Smith8809a0c2013-09-27 20:14:12 +00003899 // If we already have a definition, we're done.
3900 if (VarDecl *Def = Var->getDefinition()) {
3901 // We may be explicitly instantiating something we've already implicitly
3902 // instantiated.
3903 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3904 PointOfInstantiation);
3905 return;
Nick Lewyckya995a472012-04-04 02:38:36 +00003906 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00003907
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003908 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003909 if (Inst.isInvalid())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003910 return;
Mike Stump11289f42009-09-09 15:08:12 +00003911
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003912 // If we're performing recursive template instantiation, create our own
3913 // queue of pending implicit instantiations that we will instantiate later,
3914 // while we're still within our own instantiation context.
David Majnemerfd6c685f2013-11-27 22:57:44 +00003915 SavePendingLocalImplicitInstantiationsRAII
3916 SavedPendingLocalImplicitInstantiations(*this);
Nico Weberccec9d82014-08-15 22:29:14 +00003917 std::unique_ptr<SavePendingInstantiationsAndVTableUsesRAII>
3918 SavePendingInstantiationsAndVTableUses;
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003919 if (Recursive) {
Nico Weberccec9d82014-08-15 22:29:14 +00003920 SavePendingInstantiationsAndVTableUses.reset(
3921 new SavePendingInstantiationsAndVTableUsesRAII(*this));
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003922 }
Mike Stump11289f42009-09-09 15:08:12 +00003923
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003924 // Enter the scope of this instantiation. We don't use
3925 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003926 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00003927 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00003928
Larisse Voufo39a1e502013-08-06 01:03:05 +00003929 VarDecl *OldVar = Var;
3930 if (!VarSpec)
3931 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00003932 TemplateArgs));
3933 else if (Var->isStaticDataMember() &&
3934 Var->getLexicalDeclContext()->isRecord()) {
3935 // We need to instantiate the definition of a static data member template,
3936 // and all we have is the in-class declaration of it. Instantiate a separate
3937 // declaration of the definition.
3938 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3939 TemplateArgs);
3940 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
Craig Topperc3ec1492014-05-26 06:22:03 +00003941 VarSpec->getSpecializedTemplate(), Def, nullptr,
Richard Smith8809a0c2013-09-27 20:14:12 +00003942 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3943 if (Var) {
3944 llvm::PointerUnion<VarTemplateDecl *,
3945 VarTemplatePartialSpecializationDecl *> PatternPtr =
3946 VarSpec->getSpecializedTemplateOrPartial();
3947 if (VarTemplatePartialSpecializationDecl *Partial =
3948 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3949 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3950 Partial, &VarSpec->getTemplateInstantiationArgs());
3951
3952 // Merge the definition with the declaration.
3953 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3954 LookupOrdinaryName, ForRedeclaration);
3955 R.addDecl(OldVar);
3956 MergeVarDecl(Var, R);
3957
3958 // Attach the initializer.
3959 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3960 }
3961 } else
3962 // Complete the existing variable's definition with an appropriately
3963 // substituted type and initializer.
3964 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003965
3966 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003967
3968 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003969 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00003970 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3971 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003972 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003973
3974 // This variable may have local implicit instantiations that need to be
3975 // instantiated within this scope.
3976 PerformPendingInstantiations(/*LocalOnly=*/true);
3977
Douglas Gregora86bc002012-02-16 21:36:18 +00003978 Local.Exit();
3979
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003980 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003981 // Define any newly required vtables.
3982 DefineUsedVTables();
3983
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003984 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003985 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003986 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003987
Nico Weberccec9d82014-08-15 22:29:14 +00003988 // Restore PendingInstantiations and VTableUses.
3989 SavePendingInstantiationsAndVTableUses.reset();
Mike Stump11289f42009-09-09 15:08:12 +00003990 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003991}
Douglas Gregor51783312009-05-27 05:35:12 +00003992
Anders Carlsson70553942009-08-29 05:16:22 +00003993void
3994Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3995 const CXXConstructorDecl *Tmpl,
3996 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003997
Richard Trieu9becef62011-09-09 03:18:59 +00003998 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00003999 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004000
Anders Carlsson70553942009-08-29 05:16:22 +00004001 // Instantiate all the initializers.
Aaron Ballman0ad78302014-03-13 17:34:31 +00004002 for (const auto *Init : Tmpl->inits()) {
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004003 // Only instantiate written initializers, let Sema re-construct implicit
4004 // ones.
4005 if (!Init->isWritten())
4006 continue;
4007
Douglas Gregor44e7df62011-01-04 00:32:56 +00004008 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004009
Douglas Gregor44e7df62011-01-04 00:32:56 +00004010 if (Init->isPackExpansion()) {
4011 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004012 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004013 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004014 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004015 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004016 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004017 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004018 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004019 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004020 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004021 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004022 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004023 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004024 NumExpansions)) {
4025 AnyErrors = true;
4026 New->setInvalidDecl();
4027 continue;
4028 }
4029 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004030
4031 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004032 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004033 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4034
4035 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004036 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4037 /*CXXDirectInit=*/true);
4038 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004039 AnyErrors = true;
4040 break;
4041 }
4042
4043 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004044 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004045 TemplateArgs,
4046 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004047 New->getDeclName());
4048 if (!BaseTInfo) {
4049 AnyErrors = true;
4050 break;
4051 }
4052
4053 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004054 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004055 BaseTInfo, TempInit.get(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004056 New->getParent(),
4057 SourceLocation());
4058 if (NewInit.isInvalid()) {
4059 AnyErrors = true;
4060 break;
4061 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004062
Douglas Gregor44e7df62011-01-04 00:32:56 +00004063 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004064 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004065
Douglas Gregor44e7df62011-01-04 00:32:56 +00004066 continue;
4067 }
4068
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004069 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004070 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4071 /*CXXDirectInit=*/true);
4072 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004073 AnyErrors = true;
4074 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004075 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004076
Anders Carlsson70553942009-08-29 05:16:22 +00004077 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004078 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4079 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4080 TemplateArgs,
4081 Init->getSourceLocation(),
4082 New->getDeclName());
4083 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004084 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004085 New->setInvalidDecl();
4086 continue;
4087 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004088
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004089 if (Init->isBaseInitializer())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004090 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004091 New->getParent(), EllipsisLoc);
4092 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004093 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004094 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004095 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004096 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004097 Init->getMemberLocation(),
4098 Init->getMember(),
4099 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004100 if (!Member) {
4101 AnyErrors = true;
4102 New->setInvalidDecl();
4103 continue;
4104 }
Mike Stump11289f42009-09-09 15:08:12 +00004105
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004106 NewInit = BuildMemberInitializer(Member, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004107 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004108 } else if (Init->isIndirectMemberInitializer()) {
4109 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004110 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004111 Init->getMemberLocation(),
4112 Init->getIndirectMember(), TemplateArgs));
4113
Douglas Gregor55e6b312011-03-04 19:46:35 +00004114 if (!IndirectMember) {
4115 AnyErrors = true;
4116 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004117 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004118 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004119
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004120 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004121 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004122 }
4123
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004124 if (NewInit.isInvalid()) {
4125 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004126 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004127 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004128 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004129 }
4130 }
Mike Stump11289f42009-09-09 15:08:12 +00004131
Anders Carlsson70553942009-08-29 05:16:22 +00004132 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004133 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004134 /*FIXME: ColonLoc */
4135 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004136 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004137 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004138}
4139
John McCall59660882009-08-29 08:11:13 +00004140// TODO: this could be templated if the various decl types used the
4141// same method name.
4142static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4143 ClassTemplateDecl *Instance) {
4144 Pattern = Pattern->getCanonicalDecl();
4145
4146 do {
4147 Instance = Instance->getCanonicalDecl();
4148 if (Pattern == Instance) return true;
4149 Instance = Instance->getInstantiatedFromMemberTemplate();
4150 } while (Instance);
4151
4152 return false;
4153}
4154
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004155static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4156 FunctionTemplateDecl *Instance) {
4157 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004158
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004159 do {
4160 Instance = Instance->getCanonicalDecl();
4161 if (Pattern == Instance) return true;
4162 Instance = Instance->getInstantiatedFromMemberTemplate();
4163 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004164
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004165 return false;
4166}
4167
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004168static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004169isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4170 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004171 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004172 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4173 do {
4174 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4175 Instance->getCanonicalDecl());
4176 if (Pattern == Instance)
4177 return true;
4178 Instance = Instance->getInstantiatedFromMember();
4179 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004180
Douglas Gregor21610382009-10-29 00:04:11 +00004181 return false;
4182}
4183
John McCall59660882009-08-29 08:11:13 +00004184static bool isInstantiationOf(CXXRecordDecl *Pattern,
4185 CXXRecordDecl *Instance) {
4186 Pattern = Pattern->getCanonicalDecl();
4187
4188 do {
4189 Instance = Instance->getCanonicalDecl();
4190 if (Pattern == Instance) return true;
4191 Instance = Instance->getInstantiatedFromMemberClass();
4192 } while (Instance);
4193
4194 return false;
4195}
4196
4197static bool isInstantiationOf(FunctionDecl *Pattern,
4198 FunctionDecl *Instance) {
4199 Pattern = Pattern->getCanonicalDecl();
4200
4201 do {
4202 Instance = Instance->getCanonicalDecl();
4203 if (Pattern == Instance) return true;
4204 Instance = Instance->getInstantiatedFromMemberFunction();
4205 } while (Instance);
4206
4207 return false;
4208}
4209
4210static bool isInstantiationOf(EnumDecl *Pattern,
4211 EnumDecl *Instance) {
4212 Pattern = Pattern->getCanonicalDecl();
4213
4214 do {
4215 Instance = Instance->getCanonicalDecl();
4216 if (Pattern == Instance) return true;
4217 Instance = Instance->getInstantiatedFromMemberEnum();
4218 } while (Instance);
4219
4220 return false;
4221}
4222
John McCallb96ec562009-12-04 22:46:56 +00004223static bool isInstantiationOf(UsingShadowDecl *Pattern,
4224 UsingShadowDecl *Instance,
4225 ASTContext &C) {
4226 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4227}
4228
4229static bool isInstantiationOf(UsingDecl *Pattern,
4230 UsingDecl *Instance,
4231 ASTContext &C) {
4232 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4233}
4234
John McCalle61f2ba2009-11-18 02:36:19 +00004235static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4236 UsingDecl *Instance,
4237 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004238 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCalle61f2ba2009-11-18 02:36:19 +00004239}
4240
4241static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004242 UsingDecl *Instance,
4243 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004244 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004245}
4246
John McCall59660882009-08-29 08:11:13 +00004247static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4248 VarDecl *Instance) {
4249 assert(Instance->isStaticDataMember());
4250
4251 Pattern = Pattern->getCanonicalDecl();
4252
4253 do {
4254 Instance = Instance->getCanonicalDecl();
4255 if (Pattern == Instance) return true;
4256 Instance = Instance->getInstantiatedFromStaticDataMember();
4257 } while (Instance);
4258
4259 return false;
4260}
4261
John McCallb96ec562009-12-04 22:46:56 +00004262// Other is the prospective instantiation
4263// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004264static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004265 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004266 if (UnresolvedUsingTypenameDecl *UUD
4267 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4268 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4269 return isInstantiationOf(UUD, UD, Ctx);
4270 }
4271 }
4272
4273 if (UnresolvedUsingValueDecl *UUD
4274 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004275 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4276 return isInstantiationOf(UUD, UD, Ctx);
4277 }
4278 }
Douglas Gregor51783312009-05-27 05:35:12 +00004279
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004280 return false;
4281 }
Mike Stump11289f42009-09-09 15:08:12 +00004282
John McCall59660882009-08-29 08:11:13 +00004283 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4284 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004285
John McCall59660882009-08-29 08:11:13 +00004286 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4287 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004288
John McCall59660882009-08-29 08:11:13 +00004289 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4290 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004291
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004292 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004293 if (Var->isStaticDataMember())
4294 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4295
4296 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4297 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004298
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004299 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4300 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4301
Douglas Gregor21610382009-10-29 00:04:11 +00004302 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4303 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4304 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4305 PartialSpec);
4306
Anders Carlsson5da84842009-09-01 04:26:58 +00004307 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4308 if (!Field->getDeclName()) {
4309 // This is an unnamed field.
Mike Stump11289f42009-09-09 15:08:12 +00004310 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlsson5da84842009-09-01 04:26:58 +00004311 cast<FieldDecl>(D);
4312 }
4313 }
Mike Stump11289f42009-09-09 15:08:12 +00004314
John McCallb96ec562009-12-04 22:46:56 +00004315 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4316 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4317
4318 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4319 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4320
Douglas Gregor51783312009-05-27 05:35:12 +00004321 return D->getDeclName() && isa<NamedDecl>(Other) &&
4322 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4323}
4324
4325template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004326static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004327 NamedDecl *D,
4328 ForwardIterator first,
4329 ForwardIterator last) {
4330 for (; first != last; ++first)
4331 if (isInstantiationOf(Ctx, D, *first))
4332 return cast<NamedDecl>(*first);
4333
Craig Topperc3ec1492014-05-26 06:22:03 +00004334 return nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00004335}
4336
John McCallaa74a0c2009-08-28 07:59:38 +00004337/// \brief Finds the instantiation of the given declaration context
4338/// within the current instantiation.
4339///
4340/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004341DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004342 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004343 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004344 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00004345 return cast_or_null<DeclContext>(ID);
4346 } else return DC;
4347}
4348
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004349/// \brief Find the instantiation of the given declaration within the
4350/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004351///
4352/// This routine is intended to be used when \p D is a declaration
4353/// referenced from within a template, that needs to mapped into the
4354/// corresponding declaration within an instantiation. For example,
4355/// given:
4356///
4357/// \code
4358/// template<typename T>
4359/// struct X {
4360/// enum Kind {
4361/// KnownValue = sizeof(T)
4362/// };
4363///
4364/// bool getKind() const { return KnownValue; }
4365/// };
4366///
4367/// template struct X<int>;
4368/// \endcode
4369///
Serge Pavloved5fe902013-07-10 04:59:14 +00004370/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4371/// \p EnumConstantDecl for \p KnownValue (which refers to
4372/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4373/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4374/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004375NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00004376 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00004377 DeclContext *ParentDC = D->getDeclContext();
Faisal Vali2cba1332013-10-23 06:44:28 +00004378 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4379 // parameters (p below) can have their ParentDC set to the translation-unit
4380 // - thus we can not consistently check if the ParentDC of such a parameter
4381 // is Dependent or/and a FunctionOrMethod.
4382 // For e.g. this code, during Template argument deduction tries to
4383 // find an instantiated decl for (T y) when the ParentDC for y is
4384 // the translation unit.
4385 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00004386 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00004387 // Foo(baz);
4388 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4389 // it gets here, always has a FunctionOrMethod as its ParentDC??
4390 // For now:
4391 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4392 // whose type is not instantiation dependent, do nothing to the decl
4393 // - otherwise find its instantiated decl.
4394 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4395 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4396 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00004397 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00004398 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00004399 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4400 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004401 // D is a local of some kind. Look into the map of local
4402 // declarations to their instantiations.
Chris Lattner50c3c132011-02-17 19:47:42 +00004403 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4404 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4405 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004406
Chris Lattnercab02a62011-02-17 20:34:02 +00004407 if (Found) {
4408 if (Decl *FD = Found->dyn_cast<Decl *>())
4409 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004410
Richard Smithb15fe3a2012-09-12 00:56:43 +00004411 int PackIdx = ArgumentPackSubstitutionIndex;
4412 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattnercab02a62011-02-17 20:34:02 +00004413 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4414 }
4415
Serge Pavlov7cd8f602013-07-15 06:14:07 +00004416 // If we're performing a partial substitution during template argument
4417 // deduction, we may not have values for template parameters yet. They
4418 // just map to themselves.
4419 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4420 isa<TemplateTemplateParmDecl>(D))
4421 return D;
4422
Serge Pavlov074a5182013-08-10 12:00:21 +00004423 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00004424 return nullptr;
Serge Pavlov074a5182013-08-10 12:00:21 +00004425
Chris Lattnercab02a62011-02-17 20:34:02 +00004426 // If we didn't find the decl, then we must have a label decl that hasn't
4427 // been found yet. Lazily instantiate it and return it now.
4428 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004429
Chris Lattnercab02a62011-02-17 20:34:02 +00004430 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4431 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004432
Chris Lattnercab02a62011-02-17 20:34:02 +00004433 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4434 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004435 }
Douglas Gregor51783312009-05-27 05:35:12 +00004436
Larisse Voufo39a1e502013-08-06 01:03:05 +00004437 // For variable template specializations, update those that are still
4438 // type-dependent.
4439 if (VarTemplateSpecializationDecl *VarSpec =
4440 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4441 bool InstantiationDependent = false;
4442 const TemplateArgumentListInfo &VarTemplateArgs =
4443 VarSpec->getTemplateArgsInfo();
4444 if (TemplateSpecializationType::anyDependentTemplateArguments(
4445 VarTemplateArgs, InstantiationDependent))
4446 D = cast<NamedDecl>(
4447 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4448 return D;
4449 }
4450
Douglas Gregor64621e62009-09-16 18:34:49 +00004451 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4452 if (!Record->isDependentContext())
4453 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004454
Douglas Gregor4109afa2011-11-07 17:43:18 +00004455 // Determine whether this record is the "templated" declaration describing
4456 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00004457 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00004458 if (ClassTemplate)
4459 ClassTemplate = ClassTemplate->getCanonicalDecl();
4460 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4461 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4462 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004463
Douglas Gregor4109afa2011-11-07 17:43:18 +00004464 // Walk the current context to find either the record or an instantiation of
4465 // it.
4466 DeclContext *DC = CurContext;
4467 while (!DC->isFileContext()) {
4468 // If we're performing substitution while we're inside the template
4469 // definition, we'll find our own context. We're done.
4470 if (DC->Equals(Record))
4471 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004472
Douglas Gregor4109afa2011-11-07 17:43:18 +00004473 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4474 // Check whether we're in the process of instantiating a class template
4475 // specialization of the template we're mapping.
4476 if (ClassTemplateSpecializationDecl *InstSpec
4477 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4478 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4479 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4480 return InstRecord;
4481 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004482
Douglas Gregor4109afa2011-11-07 17:43:18 +00004483 // Check whether we're in the process of instantiating a member class.
4484 if (isInstantiationOf(Record, InstRecord))
4485 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00004486 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004487
Douglas Gregor4109afa2011-11-07 17:43:18 +00004488 // Move to the outer template scope.
4489 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4490 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4491 DC = FD->getLexicalDeclContext();
4492 continue;
4493 }
John McCall59660882009-08-29 08:11:13 +00004494 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004495
Douglas Gregor4109afa2011-11-07 17:43:18 +00004496 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00004497 }
Douglas Gregord225fa02010-02-05 22:40:03 +00004498
Douglas Gregor64621e62009-09-16 18:34:49 +00004499 // Fall through to deal with other dependent record types (e.g.,
4500 // anonymous unions in class templates).
4501 }
John McCall59660882009-08-29 08:11:13 +00004502
Douglas Gregor64621e62009-09-16 18:34:49 +00004503 if (!ParentDC->isDependentContext())
4504 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004505
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004506 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004507 if (!ParentDC)
Craig Topperc3ec1492014-05-26 06:22:03 +00004508 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004509
Douglas Gregor51783312009-05-27 05:35:12 +00004510 if (ParentDC != D->getDeclContext()) {
4511 // We performed some kind of instantiation in the parent context,
4512 // so now we need to look into the instantiated parent context to
4513 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004514
John McCalle78aac42010-03-10 03:28:59 +00004515 // If our context used to be dependent, we may need to instantiate
4516 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00004517 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00004518 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004519 if (!Spec->isDependentContext()) {
4520 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00004521 const RecordType *Tag = T->getAs<RecordType>();
4522 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00004523 if (Tag->isBeingDefined())
4524 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00004525 if (!Tag->isBeingDefined() &&
4526 RequireCompleteType(Loc, T, diag::err_incomplete_type))
Craig Topperc3ec1492014-05-26 06:22:03 +00004527 return nullptr;
Douglas Gregor25edf432010-11-05 23:22:45 +00004528
4529 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004530 }
4531 }
4532
Craig Topperc3ec1492014-05-26 06:22:03 +00004533 NamedDecl *Result = nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00004534 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004535 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00004536 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00004537 } else {
4538 // Since we don't have a name for the entity we're looking for,
4539 // our only option is to walk through all of the declarations to
4540 // find that name. This will occur in a few cases:
4541 //
4542 // - anonymous struct/union within a template
4543 // - unnamed class/struct/union/enum within a template
4544 //
4545 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00004546 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004547 ParentDC->decls_begin(),
4548 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00004549 }
Mike Stump11289f42009-09-09 15:08:12 +00004550
Douglas Gregor528ad932011-03-06 20:12:45 +00004551 if (!Result) {
4552 if (isa<UsingShadowDecl>(D)) {
4553 // UsingShadowDecls can instantiate to nothing because of using hiding.
4554 } else if (Diags.hasErrorOccurred()) {
4555 // We've already complained about something, so most likely this
4556 // declaration failed to instantiate. There's no point in complaining
4557 // further, since this is normal in invalid code.
4558 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004559 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00004560 // instantiated, and we haven't gotten around to instantiating this
4561 // member yet. This can happen when the code uses forward declarations
4562 // of member classes, and introduces ordering dependencies via
4563 // template instantiation.
4564 Diag(Loc, diag::err_member_not_yet_instantiated)
4565 << D->getDeclName()
4566 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4567 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00004568 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4569 // This enumeration constant was found when the template was defined,
4570 // but can't be found in the instantiation. This can happen if an
4571 // unscoped enumeration member is explicitly specialized.
4572 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4573 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4574 TemplateArgs));
4575 assert(Spec->getTemplateSpecializationKind() ==
4576 TSK_ExplicitSpecialization);
4577 Diag(Loc, diag::err_enumerator_does_not_exist)
4578 << D->getDeclName()
4579 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4580 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4581 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00004582 } else {
4583 // We should have found something, but didn't.
4584 llvm_unreachable("Unable to find instantiation of declaration!");
4585 }
4586 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004587
Douglas Gregor51783312009-05-27 05:35:12 +00004588 D = Result;
4589 }
4590
Douglas Gregor51783312009-05-27 05:35:12 +00004591 return D;
4592}
Douglas Gregor77b50e12009-06-22 23:06:13 +00004593
Mike Stump11289f42009-09-09 15:08:12 +00004594/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00004595/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00004596void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004597 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00004598 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004599 PendingImplicitInstantiation Inst;
4600
4601 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00004602 Inst = PendingInstantiations.front();
4603 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004604 } else {
4605 Inst = PendingLocalImplicitInstantiations.front();
4606 PendingLocalImplicitInstantiations.pop_front();
4607 }
Mike Stump11289f42009-09-09 15:08:12 +00004608
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004609 // Instantiate function definitions
4610 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallfaf5fb42010-08-26 23:41:50 +00004611 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4612 "instantiating function definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004613 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4614 TSK_ExplicitInstantiationDefinition;
4615 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4616 DefinitionRequired);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004617 continue;
4618 }
Mike Stump11289f42009-09-09 15:08:12 +00004619
Larisse Voufo39a1e502013-08-06 01:03:05 +00004620 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004621 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004622
4623 assert((Var->isStaticDataMember() ||
4624 isa<VarTemplateSpecializationDecl>(Var)) &&
4625 "Not a static data member, nor a variable template"
4626 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00004627
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004628 // Don't try to instantiate declarations if the most recent redeclaration
4629 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004630 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004631 continue;
4632
4633 // Check if the most recent declaration has changed the specialization kind
4634 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004635 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004636 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00004637 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004638 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004639 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004640 continue; // No longer need to instantiate this type.
4641 case TSK_ExplicitInstantiationDefinition:
4642 // We only need an instantiation if the pending instantiation *is* the
4643 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004644 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004645 case TSK_ImplicitInstantiation:
4646 break;
4647 }
4648
Larisse Voufo39a1e502013-08-06 01:03:05 +00004649 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4650 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004651 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4652 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004653
4654 // Instantiate static data member definitions or variable template
4655 // specializations.
4656 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4657 DefinitionRequired);
Douglas Gregor77b50e12009-06-22 23:06:13 +00004658 }
4659}
John McCallc62bb642010-03-24 05:22:00 +00004660
4661void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4662 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00004663 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00004664 switch (DD->getKind()) {
4665 case DependentDiagnostic::Access:
4666 HandleDependentAccessCheck(*DD, TemplateArgs);
4667 break;
4668 }
4669 }
4670}