blob: 0219b6fc761bee2a0f04c71e7d9f27f3a171a32c [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"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
John McCallc62bb642010-03-24 05:22:00 +000017#include "clang/AST/DependentDiagnostic.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000018#include "clang/AST/Expr.h"
Douglas Gregor6131b442009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
John McCall58f10c32010-03-11 09:03:00 +000020#include "clang/AST/TypeLoc.h"
Douglas Gregor402250f2009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Template.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000025
26using namespace clang;
27
David Majnemer192d1792013-11-27 08:20:38 +000028static bool isDeclWithinFunction(const Decl *D) {
29 const DeclContext *DC = D->getDeclContext();
30 if (DC->isFunctionOrMethod())
31 return true;
32
33 if (DC->isRecord())
34 return cast<CXXRecordDecl>(DC)->isLocalClass();
35
36 return false;
37}
38
John McCall3e11ebe2010-03-15 10:12:16 +000039bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
40 DeclaratorDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000041 if (!OldDecl->getQualifierLoc())
42 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000043
Douglas Gregor14454802011-02-25 02:25:35 +000044 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000045 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000046 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000047
Douglas Gregor14454802011-02-25 02:25:35 +000048 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000049 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000050
Douglas Gregor14454802011-02-25 02:25:35 +000051 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000052 return false;
53}
54
55bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
56 TagDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000057 if (!OldDecl->getQualifierLoc())
58 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000059
Douglas Gregor14454802011-02-25 02:25:35 +000060 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000061 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000062 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000063
Douglas Gregor14454802011-02-25 02:25:35 +000064 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000065 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000066
Douglas Gregor14454802011-02-25 02:25:35 +000067 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000068 return false;
69}
70
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000071// Include attribute instantiation code.
72#include "clang/Sema/AttrTemplateInstantiate.inc"
73
Richard Smith44c247f2013-02-22 08:32:16 +000074static void instantiateDependentAlignedAttr(
75 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
76 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
77 if (Aligned->isAlignmentExpr()) {
78 // The alignment expression is a constant expression.
79 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
80 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
81 if (!Result.isInvalid())
82 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
83 Aligned->getSpellingListIndex(), IsPackExpansion);
84 } else {
85 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
86 TemplateArgs, Aligned->getLocation(),
87 DeclarationName());
88 if (Result)
89 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
90 Aligned->getSpellingListIndex(), IsPackExpansion);
91 }
92}
93
94static void instantiateDependentAlignedAttr(
95 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
96 const AlignedAttr *Aligned, Decl *New) {
97 if (!Aligned->isPackExpansion()) {
98 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
99 return;
100 }
101
102 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
103 if (Aligned->isAlignmentExpr())
104 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
105 Unexpanded);
106 else
107 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
108 Unexpanded);
109 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
110
111 // Determine whether we can expand this attribute pack yet.
112 bool Expand = true, RetainExpansion = false;
113 Optional<unsigned> NumExpansions;
114 // FIXME: Use the actual location of the ellipsis.
115 SourceLocation EllipsisLoc = Aligned->getLocation();
116 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
117 Unexpanded, TemplateArgs, Expand,
118 RetainExpansion, NumExpansions))
119 return;
120
121 if (!Expand) {
122 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
123 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
124 } else {
125 for (unsigned I = 0; I != *NumExpansions; ++I) {
126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
128 }
129 }
130}
131
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000132static void instantiateDependentEnableIfAttr(
133 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
134 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
135 Expr *Cond = 0;
136 {
137 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
138 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
139 if (Result.isInvalid())
140 return;
141 Cond = Result.takeAs<Expr>();
142 }
143 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
144 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
145 if (Converted.isInvalid())
146 return;
147 Cond = Converted.take();
148 }
149
150 SmallVector<PartialDiagnosticAt, 8> Diags;
151 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
152 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
153 Diags)) {
154 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
155 for (int I = 0, N = Diags.size(); I != N; ++I)
156 S.Diag(Diags[I].first, Diags[I].second);
157 return;
158 }
159
Aaron Ballman36a53502014-01-16 13:03:14 +0000160 EnableIfAttr *EIA = new (S.getASTContext())
161 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
162 A->getMessage(),
163 A->getSpellingListIndex());
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000164 New->addAttr(EIA);
165}
166
John McCall6602bb12010-08-01 02:01:53 +0000167void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000168 const Decl *Tmpl, Decl *New,
169 LateInstantiatedAttrVec *LateAttrs,
170 LocalInstantiationScope *OuterMostScope) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000171 for (const auto *TmplAttr : Tmpl->attrs()) {
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000172 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000173 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
174 if (Aligned && Aligned->isAlignmentDependent()) {
175 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
176 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000177 }
178
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000179 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
180 if (EnableIf && EnableIf->getCond()->isValueDependent()) {
181 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
182 New);
183 continue;
184 }
185
Richard Smith44c247f2013-02-22 08:32:16 +0000186 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000187 if (TmplAttr->isLateParsed() && LateAttrs) {
188 // Late parsed attributes must be instantiated and attached after the
189 // enclosing class has been instantiated. See Sema::InstantiateClass.
190 LocalInstantiationScope *Saved = 0;
191 if (CurrentInstantiationScope)
192 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
193 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
194 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000195 // Allow 'this' within late-parsed attributes.
196 NamedDecl *ND = dyn_cast<NamedDecl>(New);
197 CXXRecordDecl *ThisContext =
198 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
199 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
200 ND && ND->isCXXInstanceMember());
201
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000202 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
203 *this, TemplateArgs);
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000204 if (NewAttr)
205 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000206 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000207 }
208}
209
Douglas Gregor8a655532009-03-25 15:45:12 +0000210Decl *
211TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000212 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000213}
214
215Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000216TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
217 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
218 D->getIdentifier());
219 Owner->addDecl(Inst);
220 return Inst;
221}
222
223Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000224TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000225 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000226}
227
John McCalld8d0d432010-02-16 06:53:13 +0000228Decl *
229TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
230 NamespaceAliasDecl *Inst
231 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
232 D->getNamespaceLoc(),
233 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000234 D->getIdentifier(),
235 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000236 D->getTargetNameLoc(),
237 D->getNamespace());
238 Owner->addDecl(Inst);
239 return Inst;
240}
241
Richard Smith3f1b5d02011-05-05 21:57:07 +0000242Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
243 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000244 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000245 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000246 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000247 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000248 DI = SemaRef.SubstType(DI, TemplateArgs,
249 D->getLocation(), D->getDeclName());
250 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000251 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000252 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000253 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000254 } else {
255 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000256 }
Mike Stump11289f42009-09-09 15:08:12 +0000257
Richard Smith2ddcbab2012-10-23 00:32:41 +0000258 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
259 // libstdc++ relies upon this bug in its implementation of common_type.
260 // If we happen to be processing that implementation, fake up the g++ ?:
261 // semantics. See LWG issue 2141 for more information on the bug.
262 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
263 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
264 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
265 DT->isReferenceType() &&
266 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
267 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
268 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
269 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
270 // Fold it to the (non-reference) type which g++ would have produced.
271 DI = SemaRef.Context.getTrivialTypeSourceInfo(
272 DI->getType().getNonReferenceType());
273
Douglas Gregord7e7a512009-03-17 21:15:40 +0000274 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000275 TypedefNameDecl *Typedef;
276 if (IsTypeAlias)
277 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
278 D->getLocation(), D->getIdentifier(), DI);
279 else
280 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
281 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000282 if (Invalid)
283 Typedef->setInvalidDecl();
284
John McCall04fcd0d2011-02-01 08:20:08 +0000285 // If the old typedef was the name for linkage purposes of an anonymous
286 // tag decl, re-establish that relationship for the new typedef.
287 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
288 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000289 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000290 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000291 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000292 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000293 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000294 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000295
Douglas Gregorec9fd132012-01-14 16:38:05 +0000296 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000297 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
298 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000299 if (!InstPrev)
300 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000301
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000302 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
303
304 // If the typedef types are not identical, reject them.
305 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
306
Rafael Espindola8db352d2013-10-17 15:37:26 +0000307 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000308 }
309
John McCall6602bb12010-08-01 02:01:53 +0000310 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000311
John McCall401982f2010-01-20 21:53:11 +0000312 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000313
Douglas Gregord7e7a512009-03-17 21:15:40 +0000314 return Typedef;
315}
316
Richard Smithdda56e42011-04-15 14:24:37 +0000317Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000318 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
319 Owner->addDecl(Typedef);
320 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000321}
322
323Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000324 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
325 Owner->addDecl(Typedef);
326 return Typedef;
327}
328
329Decl *
330TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
331 // Create a local instantiation scope for this type alias template, which
332 // will contain the instantiations of the template parameters.
333 LocalInstantiationScope Scope(SemaRef);
334
335 TemplateParameterList *TempParams = D->getTemplateParameters();
336 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
337 if (!InstParams)
338 return 0;
339
340 TypeAliasDecl *Pattern = D->getTemplatedDecl();
341
342 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000343 if (Pattern->getPreviousDecl()) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000344 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000345 if (!Found.empty()) {
346 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000347 }
348 }
349
350 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
351 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
352 if (!AliasInst)
353 return 0;
354
355 TypeAliasTemplateDecl *Inst
356 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
357 D->getDeclName(), InstParams, AliasInst);
358 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000359 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000360
361 Inst->setAccess(D->getAccess());
362
363 if (!PrevAliasTemplate)
364 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000365
Richard Smith3f1b5d02011-05-05 21:57:07 +0000366 Owner->addDecl(Inst);
367
368 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000369}
370
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000371Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000372 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000373}
374
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000375Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
376 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000377
Douglas Gregor04163182010-05-21 00:31:19 +0000378 // If this is the variable for an anonymous struct or union,
379 // instantiate the anonymous struct/union type first.
380 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
381 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
382 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
383 return 0;
384
John McCall76d824f2009-08-25 22:02:44 +0000385 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000386 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000387 TemplateArgs,
388 D->getTypeSpecStartLoc(),
389 D->getDeclName());
390 if (!DI)
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000391 return 0;
392
Douglas Gregor61623342010-09-12 07:37:24 +0000393 if (DI->getType()->isFunctionType()) {
394 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
395 << D->isStaticDataMember() << DI->getType();
396 return 0;
397 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000398
Richard Smith541b38b2013-09-20 01:15:31 +0000399 DeclContext *DC = Owner;
400 if (D->isLocalExternDecl())
401 SemaRef.adjustContextForLocalExternDecl(DC);
402
Larisse Voufo39a1e502013-08-06 01:03:05 +0000403 // Build the instantiated declaration.
Richard Smith541b38b2013-09-20 01:15:31 +0000404 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000405 D->getLocation(), D->getIdentifier(),
Larisse Voufo39a1e502013-08-06 01:03:05 +0000406 DI->getType(), DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000407
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000408 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000409 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000410 SemaRef.inferObjCARCLifetime(Var))
411 Var->setInvalidDecl();
412
Larisse Voufo39a1e502013-08-06 01:03:05 +0000413 // Substitute the nested name specifier, if any.
414 if (SubstQualifier(D, Var))
415 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000416
Richard Smith541b38b2013-09-20 01:15:31 +0000417 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000418 StartingScope, InstantiatingVarTemplate);
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000419 return Var;
420}
421
Abramo Bagnarad7340582010-06-05 05:09:32 +0000422Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
423 AccessSpecDecl* AD
424 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
425 D->getAccessSpecifierLoc(), D->getColonLoc());
426 Owner->addHiddenDecl(AD);
427 return AD;
428}
429
Douglas Gregord7e7a512009-03-17 21:15:40 +0000430Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
431 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000432 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000433 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000434 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000435 DI = SemaRef.SubstType(DI, TemplateArgs,
436 D->getLocation(), D->getDeclName());
437 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000438 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000439 Invalid = true;
440 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000441 // C++ [temp.arg.type]p3:
442 // If a declaration acquires a function type through a type
443 // dependent on a template-parameter and this causes a
444 // declaration that does not use the syntactic form of a
445 // function declarator to have function type, the program is
446 // ill-formed.
447 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000448 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000449 Invalid = true;
450 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000451 } else {
452 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000453 }
454
455 Expr *BitWidth = D->getBitWidth();
456 if (Invalid)
457 BitWidth = 0;
458 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000459 // The bit-width expression is a constant expression.
460 EnterExpressionEvaluationContext Unevaluated(SemaRef,
461 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000462
John McCalldadc5752010-08-24 06:29:42 +0000463 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000464 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000465 if (InstantiatedBitWidth.isInvalid()) {
466 Invalid = true;
467 BitWidth = 0;
468 } else
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000469 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000470 }
471
John McCall90459c52009-10-22 23:33:21 +0000472 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
473 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000474 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000475 D->getLocation(),
476 D->isMutable(),
477 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000478 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000479 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000480 D->getAccess(),
481 0);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000482 if (!Field) {
483 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000484 return 0;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000485 }
Mike Stump11289f42009-09-09 15:08:12 +0000486
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000487 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000488
Richard Smith848e1f12013-02-01 08:12:08 +0000489 if (Field->hasAttrs())
490 SemaRef.CheckAlignasUnderalignment(Field);
491
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000492 if (Invalid)
493 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000494
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000495 if (!Field->getDeclName()) {
496 // Keep track of where this decl came from.
497 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000498 }
Douglas Gregor04163182010-05-21 00:31:19 +0000499 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
500 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000501 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000502 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000503 }
Mike Stump11289f42009-09-09 15:08:12 +0000504
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000505 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000506 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000507 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000508
509 return Field;
510}
511
John McCall5e77d762013-04-16 07:28:30 +0000512Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
513 bool Invalid = false;
514 TypeSourceInfo *DI = D->getTypeSourceInfo();
515
516 if (DI->getType()->isVariablyModifiedType()) {
517 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +0000518 << D;
John McCall5e77d762013-04-16 07:28:30 +0000519 Invalid = true;
520 } else if (DI->getType()->isInstantiationDependentType()) {
521 DI = SemaRef.SubstType(DI, TemplateArgs,
522 D->getLocation(), D->getDeclName());
523 if (!DI) {
524 DI = D->getTypeSourceInfo();
525 Invalid = true;
526 } else if (DI->getType()->isFunctionType()) {
527 // C++ [temp.arg.type]p3:
528 // If a declaration acquires a function type through a type
529 // dependent on a template-parameter and this causes a
530 // declaration that does not use the syntactic form of a
531 // function declarator to have function type, the program is
532 // ill-formed.
533 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
534 << DI->getType();
535 Invalid = true;
536 }
537 } else {
538 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
539 }
540
Richard Smithf7981722013-11-22 09:01:48 +0000541 MSPropertyDecl *Property = MSPropertyDecl::Create(
542 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
543 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000544
545 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
546 StartingScope);
547
548 if (Invalid)
549 Property->setInvalidDecl();
550
551 Property->setAccess(D->getAccess());
552 Owner->addDecl(Property);
553
554 return Property;
555}
556
Francois Pichet783dd6e2010-11-21 06:08:52 +0000557Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
558 NamedDecl **NamedChain =
559 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
560
561 int i = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +0000562 for (auto *PI : D->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +0000563 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000564 TemplateArgs);
565 if (!Next)
566 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000567
Douglas Gregor55e6b312011-03-04 19:46:35 +0000568 NamedChain[i++] = Next;
569 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000570
Francois Pichetdbafc192010-12-09 10:07:54 +0000571 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet783dd6e2010-11-21 06:08:52 +0000572 IndirectFieldDecl* IndirectField
573 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichetdbafc192010-12-09 10:07:54 +0000574 D->getIdentifier(), T,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000575 NamedChain, D->getChainingSize());
576
577
578 IndirectField->setImplicit(D->isImplicit());
579 IndirectField->setAccess(D->getAccess());
580 Owner->addDecl(IndirectField);
581 return IndirectField;
582}
583
John McCallaa74a0c2009-08-28 07:59:38 +0000584Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000585 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000586 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000587 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000588 TypeSourceInfo *InstTy;
589 // If this is an unsupported friend, don't bother substituting template
590 // arguments into it. The actual type referred to won't be used by any
591 // parts of Clang, and may not be valid for instantiating. Just use the
592 // same info for the instantiated friend.
593 if (D->isUnsupportedFriend()) {
594 InstTy = Ty;
595 } else {
596 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
597 D->getLocation(), DeclarationName());
598 }
599 if (!InstTy)
Douglas Gregor33636e62009-12-24 20:56:24 +0000600 return 0;
John McCallaa74a0c2009-08-28 07:59:38 +0000601
Richard Smitha31a89a2012-09-20 01:31:00 +0000602 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000603 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000604 if (!FD)
605 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000606
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000607 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000608 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000609 Owner->addDecl(FD);
610 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000611 }
612
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000613 NamedDecl *ND = D->getFriendDecl();
614 assert(ND && "friend decl must be a decl or a type!");
615
John McCallb9c78482010-04-08 09:05:18 +0000616 // All of the Visit implementations for the various potential friend
617 // declarations have to be carefully written to work for friend
618 // objects, with the most important detail being that the target
619 // decl should almost certainly not be placed in Owner.
620 Decl *NewND = Visit(ND);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000621 if (!NewND) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000622
John McCallaa74a0c2009-08-28 07:59:38 +0000623 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000624 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000625 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000626 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000627 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000628 Owner->addDecl(FD);
629 return FD;
John McCall58de3582009-08-14 02:03:10 +0000630}
631
Douglas Gregord7e7a512009-03-17 21:15:40 +0000632Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
633 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000634
Richard Smith764d2fe2011-12-20 02:08:33 +0000635 // The expression in a static assertion is a constant expression.
636 EnterExpressionEvaluationContext Unevaluated(SemaRef,
637 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000638
John McCalldadc5752010-08-24 06:29:42 +0000639 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000640 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000641 if (InstantiatedAssertExpr.isInvalid())
642 return 0;
643
Richard Smithded9c2e2012-07-11 22:37:56 +0000644 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000645 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000646 D->getMessage(),
647 D->getRParenLoc(),
648 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000649}
650
651Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith2e6610a2012-03-26 04:58:10 +0000652 EnumDecl *PrevDecl = 0;
653 if (D->getPreviousDecl()) {
654 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
655 D->getPreviousDecl(),
656 TemplateArgs);
657 if (!Prev) return 0;
658 PrevDecl = cast<EnumDecl>(Prev);
659 }
660
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000661 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000662 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000663 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000664 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000665 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000666 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000667 // If we have type source information for the underlying type, it means it
668 // has been explicitly set by the user. Perform substitution on it before
669 // moving on.
670 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000671 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
672 DeclarationName());
673 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000674 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000675 else
676 Enum->setIntegerTypeSourceInfo(NewTI);
677 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000678 assert(!D->getIntegerType()->isDependentType()
679 && "Dependent type without type source info");
680 Enum->setIntegerType(D->getIntegerType());
681 }
682 }
683
John McCall811a0f52010-10-22 23:36:17 +0000684 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
685
Richard Smith4b38ded2012-03-14 23:13:10 +0000686 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000687 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +0000688 // Forward the mangling number from the template to the instantiated decl.
689 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
John McCall3e11ebe2010-03-15 10:12:16 +0000690 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000691 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +0000692
Richard Smith258a7442012-03-26 04:08:46 +0000693 EnumDecl *Def = D->getDefinition();
694 if (Def && Def != D) {
695 // If this is an out-of-line definition of an enum member template, check
696 // that the underlying types match in the instantiation of both
697 // declarations.
698 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
699 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
700 QualType DefnUnderlying =
701 SemaRef.SubstType(TI->getType(), TemplateArgs,
702 UnderlyingLoc, DeclarationName());
703 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
704 DefnUnderlying, Enum);
705 }
706 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000707
Richard Smith4b38ded2012-03-14 23:13:10 +0000708 // C++11 [temp.inst]p1: The implicit instantiation of a class template
709 // specialization causes the implicit instantiation of the declarations, but
710 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +0000711 //
712 // DR1484 clarifies that enumeration definitions inside of a template
713 // declaration aren't considered entities that can be separately instantiated
714 // from the rest of the entity they are declared inside of.
715 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
716 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +0000717 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +0000718 }
Richard Smith4b38ded2012-03-14 23:13:10 +0000719
720 return Enum;
721}
722
723void TemplateDeclInstantiator::InstantiateEnumDefinition(
724 EnumDecl *Enum, EnumDecl *Pattern) {
725 Enum->startDefinition();
726
Richard Smith7d137e32012-03-23 03:33:32 +0000727 // Update the location to refer to the definition.
728 Enum->setLocation(Pattern->getLocation());
729
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000730 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000731
732 EnumConstantDecl *LastEnumConst = 0;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000733 for (auto *EC : Pattern->enumerators()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000734 // The specified value for the enumerator.
John McCalldadc5752010-08-24 06:29:42 +0000735 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000736 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000737 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +0000738 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +0000739 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000740
John McCall76d824f2009-08-25 22:02:44 +0000741 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000742 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000743
744 // Drop the initial value and continue.
745 bool isInvalid = false;
746 if (Value.isInvalid()) {
747 Value = SemaRef.Owned((Expr *)0);
748 isInvalid = true;
749 }
750
Mike Stump11289f42009-09-09 15:08:12 +0000751 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +0000752 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
753 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +0000754 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000755
756 if (isInvalid) {
757 if (EnumConst)
758 EnumConst->setInvalidDecl();
759 Enum->setInvalidDecl();
760 }
761
762 if (EnumConst) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000763 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +0000764
John McCallf9b528c2010-01-23 22:37:59 +0000765 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000766 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +0000767 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000768 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000769
Richard Smith4b38ded2012-03-14 23:13:10 +0000770 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
771 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000772 // If the enumeration is within a function or method, record the enum
773 // constant as a local.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000774 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000775 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000776 }
777 }
Mike Stump11289f42009-09-09 15:08:12 +0000778
Richard Smith4b38ded2012-03-14 23:13:10 +0000779 // FIXME: Fixup LBraceLoc
780 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
781 Enum->getRBraceLoc(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +0000782 Enumerators,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +0000783 0, 0);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000784}
785
Douglas Gregor9106b822009-03-25 15:04:13 +0000786Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000787 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +0000788}
789
John McCall87a44eb2009-08-20 01:44:21 +0000790Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000791 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
792
Douglas Gregor954de172009-10-31 17:21:17 +0000793 // Create a local instantiation scope for this class template, which
794 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +0000795 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +0000796 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000797 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000798 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +0000799 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +0000800
801 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +0000802
803 // Instantiate the qualifier. We have to do this first in case
804 // we're a friend declaration, because if we are then we need to put
805 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +0000806 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
807 if (QualifierLoc) {
808 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
809 TemplateArgs);
810 if (!QualifierLoc)
811 return 0;
John McCall598b4402010-03-25 06:39:04 +0000812 }
813
814 CXXRecordDecl *PrevDecl = 0;
815 ClassTemplateDecl *PrevClassTemplate = 0;
816
Douglas Gregorec9fd132012-01-14 16:38:05 +0000817 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky61478912010-11-08 23:29:42 +0000818 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000819 if (!Found.empty()) {
820 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +0000821 if (PrevClassTemplate)
822 PrevDecl = PrevClassTemplate->getTemplatedDecl();
823 }
824 }
825
John McCall598b4402010-03-25 06:39:04 +0000826 // If this isn't a friend, then it's a member template, in which
827 // case we just want to build the instantiation in the
828 // specialization. If it is a friend, we want to build it in
829 // the appropriate context.
830 DeclContext *DC = Owner;
831 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +0000832 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000833 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +0000834 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +0000835 DC = SemaRef.computeDeclContext(SS);
836 if (!DC) return 0;
837 } else {
838 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
839 Pattern->getDeclContext(),
840 TemplateArgs);
841 }
842
843 // Look for a previous declaration of the template in the owning
844 // context.
845 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
846 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
847 SemaRef.LookupQualifiedName(R, DC);
848
849 if (R.isSingleResult()) {
850 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
851 if (PrevClassTemplate)
852 PrevDecl = PrevClassTemplate->getTemplatedDecl();
853 }
854
Douglas Gregor14454802011-02-25 02:25:35 +0000855 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000856 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +0000857 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +0000858 << QualifierLoc.getSourceRange();
John McCall598b4402010-03-25 06:39:04 +0000859 return 0;
860 }
861
Douglas Gregor01e09d92010-04-08 18:16:15 +0000862 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +0000863 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +0000864 bool Complain = true;
865
866 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
867 // template for struct std::tr1::__detail::_Map_base, where the
868 // template parameters of the friend declaration don't match the
869 // template parameters of the original declaration. In this one
870 // case, we don't complain about the ill-formed friend
871 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000872 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +0000873 Pattern->getIdentifier()->isStr("_Map_base") &&
874 DC->isNamespace() &&
875 cast<NamespaceDecl>(DC)->getIdentifier() &&
876 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
877 DeclContext *DCParent = DC->getParent();
878 if (DCParent->isNamespace() &&
879 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
880 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
881 DeclContext *DCParent2 = DCParent->getParent();
882 if (DCParent2->isNamespace() &&
883 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
884 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
885 DCParent2->getParent()->isTranslationUnit())
886 Complain = false;
887 }
888 }
889
John McCall598b4402010-03-25 06:39:04 +0000890 TemplateParameterList *PrevParams
891 = PrevClassTemplate->getTemplateParameters();
892
893 // Make sure the parameter lists match.
894 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000895 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +0000896 Sema::TPL_TemplateMatch)) {
897 if (Complain)
898 return 0;
899
900 AdoptedPreviousTemplateParams = true;
901 InstParams = PrevParams;
902 }
John McCall598b4402010-03-25 06:39:04 +0000903
904 // Do some additional validation, then merge default arguments
905 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +0000906 if (!AdoptedPreviousTemplateParams &&
907 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +0000908 Sema::TPC_ClassTemplate))
909 return 0;
910 }
911 }
912
John McCall87a44eb2009-08-20 01:44:21 +0000913 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +0000914 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000915 Pattern->getLocStart(), Pattern->getLocation(),
916 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000917 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +0000918
Douglas Gregor14454802011-02-25 02:25:35 +0000919 if (QualifierLoc)
920 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +0000921
John McCall87a44eb2009-08-20 01:44:21 +0000922 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +0000923 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
924 D->getIdentifier(), InstParams, RecordInst,
925 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +0000926 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +0000927
John McCall598b4402010-03-25 06:39:04 +0000928 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +0000929 if (PrevClassTemplate)
930 Inst->setAccess(PrevClassTemplate->getAccess());
931 else
932 Inst->setAccess(D->getAccess());
933
Richard Smith64017682013-07-17 23:53:16 +0000934 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +0000935 // TODO: do we want to track the instantiation progeny of this
936 // friend target decl?
937 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000938 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +0000939 if (!PrevClassTemplate)
940 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +0000941 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000942
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000943 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +0000944 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +0000945 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +0000946
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000947 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +0000948 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +0000949 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000950 Inst->setLexicalDeclContext(Owner);
951 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000952 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000953 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000954
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000955 if (D->isOutOfLine()) {
956 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
957 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
958 }
959
John McCall87a44eb2009-08-20 01:44:21 +0000960 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +0000961
962 if (!PrevClassTemplate) {
963 // Queue up any out-of-line partial specializations of this member
964 // class template; the client will force their instantiation once
965 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000966 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +0000967 D->getPartialSpecializations(PartialSpecs);
968 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000969 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +0000970 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
971 }
972
John McCall87a44eb2009-08-20 01:44:21 +0000973 return Inst;
974}
975
Douglas Gregore704c9d2009-08-27 16:57:43 +0000976Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +0000977TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
978 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +0000979 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000980
Douglas Gregor21610382009-10-29 00:04:11 +0000981 // Lookup the already-instantiated declaration in the instantiation
982 // of the class template and return that.
983 DeclContext::lookup_result Found
984 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000985 if (Found.empty())
Douglas Gregor21610382009-10-29 00:04:11 +0000986 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000987
Douglas Gregor21610382009-10-29 00:04:11 +0000988 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +0000989 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +0000990 if (!InstClassTemplate)
991 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000992
Douglas Gregor869853e2010-11-10 19:44:59 +0000993 if (ClassTemplatePartialSpecializationDecl *Result
994 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
995 return Result;
996
997 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +0000998}
999
Larisse Voufo39a1e502013-08-06 01:03:05 +00001000Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1001 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1002 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001003
1004 // Create a local instantiation scope for this variable template, which
1005 // will contain the instantiations of the template parameters.
1006 LocalInstantiationScope Scope(SemaRef);
1007 TemplateParameterList *TempParams = D->getTemplateParameters();
1008 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1009 if (!InstParams)
1010 return NULL;
1011
1012 VarDecl *Pattern = D->getTemplatedDecl();
1013 VarTemplateDecl *PrevVarTemplate = 0;
1014
1015 if (Pattern->getPreviousDecl()) {
1016 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1017 if (!Found.empty())
1018 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1019 }
1020
Richard Smith1c34fb72013-08-13 18:18:50 +00001021 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001022 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1023 /*InstantiatingVarTemplate=*/true));
Larisse Voufo39a1e502013-08-06 01:03:05 +00001024
1025 DeclContext *DC = Owner;
1026
Larisse Voufo39a1e502013-08-06 01:03:05 +00001027 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1028 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001029 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001030 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001031 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001032
1033 Inst->setAccess(D->getAccess());
1034 if (!PrevVarTemplate)
1035 Inst->setInstantiatedFromMemberTemplate(D);
1036
1037 if (D->isOutOfLine()) {
1038 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1039 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1040 }
1041
1042 Owner->addDecl(Inst);
1043
1044 if (!PrevVarTemplate) {
1045 // Queue up any out-of-line partial specializations of this member
1046 // variable template; the client will force their instantiation once
1047 // the enclosing class has been instantiated.
1048 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1049 D->getPartialSpecializations(PartialSpecs);
1050 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001051 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001052 OutOfLineVarPartialSpecs.push_back(
1053 std::make_pair(Inst, PartialSpecs[I]));
1054 }
1055
1056 return Inst;
1057}
1058
1059Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1060 VarTemplatePartialSpecializationDecl *D) {
1061 assert(D->isStaticDataMember() &&
1062 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001063
1064 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1065
1066 // Lookup the already-instantiated declaration and return that.
1067 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1068 assert(!Found.empty() && "Instantiation found nothing?");
1069
1070 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1071 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1072
1073 if (VarTemplatePartialSpecializationDecl *Result =
1074 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1075 return Result;
1076
1077 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1078}
1079
Douglas Gregore4b05162009-10-07 17:21:34 +00001080Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001081TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001082 // Create a local instantiation scope for this function template, which
1083 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001084 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001085 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001086 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001087
Douglas Gregore704c9d2009-08-27 16:57:43 +00001088 TemplateParameterList *TempParams = D->getTemplateParameters();
1089 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001090 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001091 return NULL;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001092
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001093 FunctionDecl *Instantiated = 0;
1094 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001095 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001096 InstParams));
1097 else
1098 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001099 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001100 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001101
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001102 if (!Instantiated)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001103 return 0;
1104
Mike Stump11289f42009-09-09 15:08:12 +00001105 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001106 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001107 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001108 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001109 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001110 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001111 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001112
John McCall30837102010-03-26 23:10:15 +00001113 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1114
John McCall2079d0b2009-12-14 23:19:40 +00001115 // Link the instantiation back to the pattern *unless* this is a
1116 // non-definition friend declaration.
1117 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001118 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001119 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001120
John McCall30837102010-03-26 23:10:15 +00001121 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001122 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001123 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001124 } else if (InstTemplate->getDeclContext()->isRecord() &&
1125 !D->getPreviousDecl()) {
1126 SemaRef.CheckFriendAccess(InstTemplate);
1127 }
John McCall30837102010-03-26 23:10:15 +00001128
Douglas Gregore704c9d2009-08-27 16:57:43 +00001129 return InstTemplate;
1130}
1131
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001132Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1133 CXXRecordDecl *PrevDecl = 0;
1134 if (D->isInjectedClassName())
1135 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001136 else if (D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001137 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregorec9fd132012-01-14 16:38:05 +00001138 D->getPreviousDecl(),
John McCalle9f92a02009-12-15 22:29:06 +00001139 TemplateArgs);
1140 if (!Prev) return 0;
1141 PrevDecl = cast<CXXRecordDecl>(Prev);
1142 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001143
1144 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001145 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001146 D->getLocStart(), D->getLocation(),
1147 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001148
1149 // Substitute the nested name specifier, if any.
1150 if (SubstQualifier(D, Record))
1151 return 0;
1152
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001153 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001154 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1155 // the tag decls introduced by friend class declarations don't have an access
1156 // specifier. Remove once this area of the code gets sorted out.
1157 if (D->getAccess() != AS_none)
1158 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001159 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001160 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001161
John McCallaa74a0c2009-08-28 07:59:38 +00001162 // If the original function was part of a friend declaration,
1163 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001164 if (D->getFriendObjectKind())
1165 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001166
Douglas Gregor04163182010-05-21 00:31:19 +00001167 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001168 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001169 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001170
1171 if (D->isLocalClass())
1172 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001173
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001174 // Forward the mangling number from the template to the instantiated decl.
1175 SemaRef.Context.setManglingNumber(Record,
1176 SemaRef.Context.getManglingNumber(D));
1177
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001178 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001179
1180 // DR1484 clarifies that the members of a local class are instantiated as part
1181 // of the instantiation of their enclosing entity.
1182 if (D->isCompleteDefinition() && D->isLocalClass()) {
David Majnemera64cb5a2014-02-22 00:17:46 +00001183 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1184 TSK_ImplicitInstantiation,
1185 /*Complain=*/true);
1186 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1187 TSK_ImplicitInstantiation);
David Majnemer192d1792013-11-27 08:20:38 +00001188 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001189 return Record;
1190}
1191
Douglas Gregor89f593a2012-09-13 21:56:43 +00001192/// \brief Adjust the given function type for an instantiation of the
1193/// given declaration, to cope with modifications to the function's type that
1194/// aren't reflected in the type-source information.
1195///
1196/// \param D The declaration we're instantiating.
1197/// \param TInfo The already-instantiated type.
1198static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1199 FunctionDecl *D,
1200 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001201 const FunctionProtoType *OrigFunc
1202 = D->getType()->castAs<FunctionProtoType>();
1203 const FunctionProtoType *NewFunc
1204 = TInfo->getType()->castAs<FunctionProtoType>();
1205 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1206 return TInfo->getType();
1207
1208 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1209 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001210 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001211 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001212}
1213
John McCallaa74a0c2009-08-28 07:59:38 +00001214/// Normal class members are of more specific types and therefore
1215/// don't make it here. This function serves two purposes:
1216/// 1) instantiating function templates
1217/// 2) substituting friend declarations
Douglas Gregor33636e62009-12-24 20:56:24 +00001218Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001219 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001220 // Check whether there is already a function template specialization for
1221 // this declaration.
1222 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001223 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001224 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001225
Douglas Gregorce9978f2012-03-28 14:34:23 +00001226 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001227 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001228 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001229 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001230
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001231 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001232 if (SpecFunc)
1233 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001234 }
Mike Stump11289f42009-09-09 15:08:12 +00001235
John McCall2f88d7d2010-03-27 05:57:59 +00001236 bool isFriend;
1237 if (FunctionTemplate)
1238 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1239 else
1240 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1241
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001242 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001243 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001244 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001245 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001246 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001247
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001248 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001249 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001250 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001251 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001252 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001253
Douglas Gregor14454802011-02-25 02:25:35 +00001254 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1255 if (QualifierLoc) {
1256 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1257 TemplateArgs);
1258 if (!QualifierLoc)
1259 return 0;
John McCalle0b2ddb2010-03-26 04:53:08 +00001260 }
1261
John McCallce410662010-02-06 01:50:47 +00001262 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001263 // in the enclosing namespace; otherwise we need to find the instantiated
1264 // context.
John McCallce410662010-02-06 01:50:47 +00001265 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001266 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001267 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001268 SemaRef.adjustContextForLocalExternDecl(DC);
1269 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001270 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001271 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001272 DC = SemaRef.computeDeclContext(SS);
1273 if (!DC) return 0;
1274 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001275 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001276 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001277 }
John McCallce410662010-02-06 01:50:47 +00001278
John McCallaa74a0c2009-08-28 07:59:38 +00001279 FunctionDecl *Function =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001280 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara0d4fce12012-10-04 21:40:42 +00001281 D->getNameInfo(), T, TInfo,
Rafael Espindola9dd86de2013-04-16 02:29:15 +00001282 D->getCanonicalDecl()->getStorageClass(),
Richard Smitha77a0a62011-08-15 21:04:07 +00001283 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001284 D->isConstexpr());
Enea Zaffanella25723ce2013-07-19 18:02:36 +00001285 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCall3e11ebe2010-03-15 10:12:16 +00001286
Richard Smithf3814ad2013-01-25 00:08:28 +00001287 if (D->isInlined())
1288 Function->setImplicitlyInline();
1289
Douglas Gregor14454802011-02-25 02:25:35 +00001290 if (QualifierLoc)
1291 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001292
Richard Smith541b38b2013-09-20 01:15:31 +00001293 if (D->isLocalExternDecl())
1294 Function->setLocalExternDecl();
1295
John McCall30837102010-03-26 23:10:15 +00001296 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001297 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001298 assert(D->getDeclContext()->isFileContext());
1299 LexicalDC = D->getDeclContext();
1300 }
1301
1302 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001303
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001304 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001305 for (unsigned P = 0; P < Params.size(); ++P)
1306 if (Params[P])
1307 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001308 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001309
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001310 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001311 if (TemplateParams) {
1312 // Our resulting instantiation is actually a function template, since we
1313 // are substituting only the outer template parameters. For example, given
1314 //
1315 // template<typename T>
1316 // struct X {
1317 // template<typename U> friend void f(T, U);
1318 // };
1319 //
1320 // X<int> x;
1321 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001322 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001323 // which means substituting int for T, but leaving "f" as a friend function
1324 // template.
1325 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001326 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001327 Function->getLocation(),
1328 Function->getDeclName(),
1329 TemplateParams, Function);
1330 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001331
1332 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001333
1334 if (isFriend && D->isThisDeclarationADefinition()) {
1335 // TODO: should we remember this connection regardless of whether
1336 // the friend declaration provided a body?
1337 FunctionTemplate->setInstantiatedFromMemberTemplate(
1338 D->getDescribedFunctionTemplate());
1339 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001340 } else if (FunctionTemplate) {
1341 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001342 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001343 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001344 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001345 Innermost.begin(),
1346 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001347 /*InsertPos=*/0);
Chandler Carruth48b28312011-08-18 09:09:59 +00001348 } else if (isFriend) {
1349 // Note, we need this connection even if the friend doesn't have a body.
1350 // Its body may exist but not have been attached yet due to deferred
1351 // parsing.
1352 // FIXME: It might be cleaner to set this when attaching the body to the
1353 // friend function declaration, however that would require finding all the
1354 // instantiations and modifying them.
John McCalle0b2ddb2010-03-26 04:53:08 +00001355 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001356 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001357
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001358 if (InitFunctionInstantiation(Function, D))
1359 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001360
John McCallb9c78482010-04-08 09:05:18 +00001361 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001362
Richard Smith541b38b2013-09-20 01:15:31 +00001363 LookupResult Previous(
1364 SemaRef, Function->getDeclName(), SourceLocation(),
1365 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1366 : Sema::LookupOrdinaryName,
1367 Sema::ForRedeclaration);
John McCall1f82f242009-11-18 22:49:29 +00001368
John McCallb9c78482010-04-08 09:05:18 +00001369 if (DependentFunctionTemplateSpecializationInfo *Info
1370 = D->getDependentSpecializationInfo()) {
1371 assert(isFriend && "non-friend has dependent specialization info?");
1372
1373 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001374 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001375
1376 // Instantiate the explicit template arguments.
1377 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1378 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001379 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1380 ExplicitArgs, TemplateArgs))
1381 return 0;
John McCallb9c78482010-04-08 09:05:18 +00001382
1383 // Map the candidate templates to their instantiations.
1384 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1385 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1386 Info->getTemplate(I),
1387 TemplateArgs);
1388 if (!Temp) return 0;
1389
1390 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1391 }
1392
1393 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1394 &ExplicitArgs,
1395 Previous))
1396 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001397
John McCallb9c78482010-04-08 09:05:18 +00001398 isExplicitSpecialization = true;
1399
1400 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001401 // Look only into the namespace where the friend would be declared to
1402 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001403 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001404 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001405
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001406 // In C++, the previous declaration we find might be a tag type
1407 // (class or enum). In this case, the new declaration will hide the
1408 // tag type. Note that this does does not apply if we're declaring a
1409 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001410 if (Previous.isSingleTagDecl())
1411 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001412 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001413
John McCall84d87672009-12-10 09:41:52 +00001414 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001415 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001416
John McCallb9467b62010-04-24 01:30:58 +00001417 NamedDecl *PrincipalDecl = (TemplateParams
1418 ? cast<NamedDecl>(FunctionTemplate)
1419 : Function);
1420
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001421 // If the original function was part of a friend declaration,
1422 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001423 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001424 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001425 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001426
Richard Smith91dfaac2014-02-03 02:37:59 +00001427 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001428
Richard Smith91dfaac2014-02-03 02:37:59 +00001429 // C++11 [temp.friend]p4 (DR329):
1430 // When a function is defined in a friend function declaration in a class
1431 // template, the function is instantiated when the function is odr-used.
1432 // The same restrictions on multiple declarations and definitions that
1433 // apply to non-template function declarations and definitions also apply
1434 // to these implicit definitions.
1435 if (D->isThisDeclarationADefinition()) {
Douglas Gregorb92ea592010-05-18 05:45:02 +00001436 // Check for a function body.
1437 const FunctionDecl *Definition = 0;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001438 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001439 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001440 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1441 << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001442 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001443 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001444 // Check for redefinitions due to other instantiations of this or
1445 // a similar friend function.
Aaron Ballman86c93902014-03-06 23:45:36 +00001446 else for (auto R : Function->redecls()) {
1447 if (R == Function)
Gabor Greif122f1eb2010-08-28 15:42:30 +00001448 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00001449
1450 // If some prior declaration of this function has been used, we need
1451 // to instantiate its definition.
1452 if (!QueuedInstantiation && R->isUsed(false)) {
1453 if (MemberSpecializationInfo *MSInfo =
1454 Function->getMemberSpecializationInfo()) {
1455 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1456 SourceLocation Loc = R->getLocation(); // FIXME
1457 MSInfo->setPointOfInstantiation(Loc);
1458 SemaRef.PendingLocalImplicitInstantiations.push_back(
1459 std::make_pair(Function, Loc));
1460 QueuedInstantiation = true;
Gabor Greif718d5152010-08-30 21:10:05 +00001461 }
1462 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001463 }
1464
1465 // If some prior declaration of this function was a friend with an
1466 // uninstantiated definition, reject it.
1467 if (R->getFriendObjectKind()) {
1468 if (const FunctionDecl *RPattern =
1469 R->getTemplateInstantiationPattern()) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001470 if (RPattern->isDefined(RPattern)) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001471 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001472 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001473 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregorb92ea592010-05-18 05:45:02 +00001474 break;
1475 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001476 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001477 }
1478 }
1479 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001480 }
1481
Richard Smith541b38b2013-09-20 01:15:31 +00001482 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1483 DC->makeDeclVisibleInContext(PrincipalDecl);
1484
John McCallb9467b62010-04-24 01:30:58 +00001485 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1486 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1487 PrincipalDecl->setNonMemberOperator();
1488
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001489 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001490 return Function;
1491}
1492
Douglas Gregore704c9d2009-08-27 16:57:43 +00001493Decl *
1494TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001495 TemplateParameterList *TemplateParams,
1496 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001497 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001498 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001499 // We are creating a function template specialization from a function
1500 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001501 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001502 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001503
Douglas Gregorce9978f2012-03-28 14:34:23 +00001504 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001505 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001506 = FunctionTemplate->findSpecialization(Innermost.begin(),
1507 Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001508 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001509
Douglas Gregor97628d62009-08-21 00:16:32 +00001510 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001511 if (SpecFunc)
1512 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001513 }
1514
John McCall2f88d7d2010-03-27 05:57:59 +00001515 bool isFriend;
1516 if (FunctionTemplate)
1517 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1518 else
1519 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1520
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001521 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001522 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001523 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001524 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001525
John McCalld0e23ec2010-10-19 02:26:41 +00001526 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001527 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001528 unsigned NumTempParamLists = 0;
1529 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1530 TempParamLists.set_size(NumTempParamLists);
1531 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1532 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1533 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1534 if (!InstParams)
1535 return NULL;
1536 TempParamLists[I] = InstParams;
1537 }
1538 }
1539
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001540 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001541 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001542 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001543 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001544 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001545
Douglas Gregor14454802011-02-25 02:25:35 +00001546 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1547 if (QualifierLoc) {
1548 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001549 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001550 if (!QualifierLoc)
Douglas Gregor14454802011-02-25 02:25:35 +00001551 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001552 }
1553
1554 DeclContext *DC = Owner;
1555 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001556 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001557 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001558 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001559 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001560
1561 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1562 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001563 } else {
1564 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1565 D->getDeclContext(),
1566 TemplateArgs);
1567 }
1568 if (!DC) return 0;
1569 }
1570
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001571 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001572 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001573 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001574
Abramo Bagnaradff19302011-03-08 08:55:46 +00001575 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001576 DeclarationNameInfo NameInfo
1577 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001578 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001579 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001580 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001581 Constructor->isExplicit(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001582 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001583 false, Constructor->isConstexpr());
Richard Smith4c163a02013-05-17 02:19:35 +00001584
Richard Smith185be182013-04-10 05:48:59 +00001585 // Claim that the instantiation of a constructor or constructor template
1586 // inherits the same constructor that the template does.
Richard Smith4c163a02013-05-17 02:19:35 +00001587 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1588 Constructor->getInheritedConstructor())) {
1589 // If we're instantiating a specialization of a function template, our
1590 // "inherited constructor" will actually itself be a function template.
1591 // Instantiate a declaration of it, too.
1592 if (FunctionTemplate) {
1593 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1594 !Inh->getParent()->isDependentContext() &&
1595 "inheriting constructor template in dependent context?");
1596 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1597 Inh);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001598 if (Inst.isInvalid())
Richard Smith4c163a02013-05-17 02:19:35 +00001599 return 0;
1600 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1601 LocalInstantiationScope LocalScope(SemaRef);
1602
1603 // Use the same template arguments that we deduced for the inheriting
1604 // constructor. There's no way they could be deduced differently.
1605 MultiLevelTemplateArgumentList InheritedArgs;
1606 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1607 Inh = cast_or_null<CXXConstructorDecl>(
1608 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1609 if (!Inh)
1610 return 0;
1611 }
Richard Smith185be182013-04-10 05:48:59 +00001612 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smith4c163a02013-05-17 02:19:35 +00001613 }
Douglas Gregore8394862009-08-21 22:43:28 +00001614 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001615 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001616 StartLoc, NameInfo, T, TInfo,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001617 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001618 false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001619 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001620 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001621 StartLoc, NameInfo, T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001622 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001623 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001624 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001625 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001626 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001627 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001628 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001629 StartLoc, NameInfo, T, TInfo,
Rafael Espindola29cda592013-04-15 12:38:20 +00001630 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001631 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001632 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001633
Richard Smithf3814ad2013-01-25 00:08:28 +00001634 if (D->isInlined())
1635 Method->setImplicitlyInline();
1636
Douglas Gregor14454802011-02-25 02:25:35 +00001637 if (QualifierLoc)
1638 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001639
Douglas Gregore704c9d2009-08-27 16:57:43 +00001640 if (TemplateParams) {
1641 // Our resulting instantiation is actually a function template, since we
1642 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001643 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001644 // template<typename T>
1645 // struct X {
1646 // template<typename U> void f(T, U);
1647 // };
1648 //
1649 // X<int> x;
1650 //
1651 // We are instantiating the member template "f" within X<int>, which means
1652 // substituting int for T, but leaving "f" as a member function template.
1653 // Build the function template itself.
1654 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1655 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001656 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001657 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001658 if (isFriend) {
1659 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001660 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001661 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001662 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001663 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001664 } else if (FunctionTemplate) {
1665 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001666 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001667 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001668 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001669 Innermost.begin(),
1670 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001671 /*InsertPos=*/0);
John McCall2f88d7d2010-03-27 05:57:59 +00001672 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001673 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001674 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001675 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001676
Mike Stump11289f42009-09-09 15:08:12 +00001677 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001678 // out-of-line, the instantiation will have the same lexical
1679 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001680 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00001681 if (NumTempParamLists)
1682 Method->setTemplateParameterListsInfo(SemaRef.Context,
1683 NumTempParamLists,
1684 TempParamLists.data());
1685
John McCall2f88d7d2010-03-27 05:57:59 +00001686 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001687 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001688 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001689 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001690
Douglas Gregor21342092009-03-24 00:38:23 +00001691 // Attach the parameters
1692 for (unsigned P = 0; P < Params.size(); ++P)
1693 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00001694 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00001695
1696 if (InitMethodInstantiation(Method, D))
1697 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001698
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001699 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1700 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001701
John McCall2f88d7d2010-03-27 05:57:59 +00001702 if (!FunctionTemplate || TemplateParams || isFriend) {
1703 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001704
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001705 // In C++, the previous declaration we find might be a tag type
1706 // (class or enum). In this case, the new declaration will hide the
1707 // tag type. Note that this does does not apply if we're declaring a
1708 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001709 if (Previous.isSingleTagDecl())
1710 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001711 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001712
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001713 if (!IsClassScopeSpecialization)
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001714 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001715
Douglas Gregor21920e372009-12-01 17:24:26 +00001716 if (D->isPure())
1717 SemaRef.CheckPureMethod(Method, SourceRange());
1718
John McCalla0a96892012-08-10 03:15:35 +00001719 // Propagate access. For a non-friend declaration, the access is
1720 // whatever we're propagating from. For a friend, it should be the
1721 // previous declaration we just found.
1722 if (isFriend && Method->getPreviousDecl())
1723 Method->setAccess(Method->getPreviousDecl()->getAccess());
1724 else
1725 Method->setAccess(D->getAccess());
1726 if (FunctionTemplate)
1727 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00001728
Anders Carlsson7c812f52011-01-20 06:52:44 +00001729 SemaRef.CheckOverrideControl(Method);
1730
Eli Friedman41340732011-11-15 22:39:08 +00001731 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00001732 if (D->isExplicitlyDefaulted())
1733 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001734 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00001735 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001736
John McCalla0a96892012-08-10 03:15:35 +00001737 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00001738 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00001739 // do nothing
1740
1741 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00001742 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00001743 // do nothing
1744
1745 // Otherwise, check access to friends and make them visible.
1746 } else if (isFriend) {
1747 // We only need to re-check access for methods which we didn't
1748 // manage to match during parsing.
1749 if (!D->getPreviousDecl())
1750 SemaRef.CheckFriendAccess(Method);
1751
1752 Record->makeDeclVisibleInContext(Method);
1753
1754 // Otherwise, add the declaration. We don't need to do this for
1755 // class-scope specializations because we'll have matched them with
1756 // the appropriate template.
1757 } else if (!IsClassScopeSpecialization) {
1758 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001759 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001760
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001761 return Method;
1762}
1763
Douglas Gregor4044d992009-03-24 16:43:20 +00001764Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001765 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001766}
1767
Douglas Gregor654b07e2009-03-24 00:15:49 +00001768Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001769 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001770}
1771
Douglas Gregor1880ba52009-03-25 00:34:44 +00001772Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001773 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001774}
1775
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00001776Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00001777 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1778 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001779}
1780
John McCall87a44eb2009-08-20 01:44:21 +00001781Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1782 TemplateTypeParmDecl *D) {
1783 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00001784 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00001785
John McCall87a44eb2009-08-20 01:44:21 +00001786 TemplateTypeParmDecl *Inst =
Abramo Bagnarab3185b02011-03-06 15:48:19 +00001787 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1788 D->getLocStart(), D->getLocation(),
Chandler Carruth08836322011-05-01 00:51:33 +00001789 D->getDepth() - TemplateArgs.getNumLevels(),
1790 D->getIndex(), D->getIdentifier(),
John McCall87a44eb2009-08-20 01:44:21 +00001791 D->wasDeclaredWithTypename(),
1792 D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001793 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00001794
David Majnemer89189202013-08-28 23:48:32 +00001795 if (D->hasDefaultArgument()) {
1796 TypeSourceInfo *InstantiatedDefaultArg =
1797 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1798 D->getDefaultArgumentLoc(), D->getDeclName());
1799 if (InstantiatedDefaultArg)
1800 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1801 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001802
1803 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001804 // scope.
1805 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001806
John McCall87a44eb2009-08-20 01:44:21 +00001807 return Inst;
1808}
1809
Douglas Gregor6b815c82009-10-23 23:25:44 +00001810Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1811 NonTypeTemplateParmDecl *D) {
1812 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001813 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001814 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1815 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001816 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001817 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001818 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001819 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001820
1821 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001822 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001823 // expansion of types. Substitute into each of the expanded types.
1824 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1825 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1826 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1827 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1828 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001829 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001830 D->getDeclName());
1831 if (!NewDI)
1832 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001833
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001834 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1835 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1836 D->getLocation());
1837 if (NewT.isNull())
1838 return 0;
1839 ExpandedParameterPackTypes.push_back(NewT);
1840 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001841
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001842 IsExpandedParameterPack = true;
1843 DI = D->getTypeSourceInfo();
1844 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00001845 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001846 // The non-type template parameter pack's type is a pack expansion of types.
1847 // Determine whether we need to expand this parameter pack into separate
1848 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00001849 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001850 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001851 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001852 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001853
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001854 // Determine whether the set of unexpanded parameter packs can and should
1855 // be expanded.
1856 bool Expand = true;
1857 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001858 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001859 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00001860 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001861 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1862 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001863 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001864 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001865 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001866 NumExpansions))
1867 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001868
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001869 if (Expand) {
1870 for (unsigned I = 0; I != *NumExpansions; ++I) {
1871 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1872 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001873 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001874 D->getDeclName());
1875 if (!NewDI)
1876 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001877
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001878 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1879 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1880 NewDI->getType(),
1881 D->getLocation());
1882 if (NewT.isNull())
1883 return 0;
1884 ExpandedParameterPackTypes.push_back(NewT);
1885 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001886
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001887 // Note that we have an expanded parameter pack. The "type" of this
1888 // expanded parameter pack is the original expansion type, but callers
1889 // will end up using the expanded parameter pack types for type-checking.
1890 IsExpandedParameterPack = true;
1891 DI = D->getTypeSourceInfo();
1892 T = DI->getType();
1893 } else {
1894 // We cannot fully expand the pack expansion now, so substitute into the
1895 // pattern and create a new pack expansion type.
1896 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1897 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001898 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001899 D->getDeclName());
1900 if (!NewPattern)
1901 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001902
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001903 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1904 NumExpansions);
1905 if (!DI)
1906 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001907
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001908 T = DI->getType();
1909 }
1910 } else {
1911 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001912 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001913 D->getLocation(), D->getDeclName());
1914 if (!DI)
1915 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001916
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001917 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001918 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001919 D->getLocation());
1920 if (T.isNull()) {
1921 T = SemaRef.Context.IntTy;
1922 Invalid = true;
1923 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00001924 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001925
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001926 NonTypeTemplateParmDecl *Param;
1927 if (IsExpandedParameterPack)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001928 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001929 D->getInnerLocStart(),
1930 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001931 D->getDepth() - TemplateArgs.getNumLevels(),
1932 D->getPosition(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001933 D->getIdentifier(), T,
1934 DI,
1935 ExpandedParameterPackTypes.data(),
1936 ExpandedParameterPackTypes.size(),
1937 ExpandedParameterPackTypesAsWritten.data());
1938 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001939 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001940 D->getInnerLocStart(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001941 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001942 D->getDepth() - TemplateArgs.getNumLevels(),
1943 D->getPosition(),
1944 D->getIdentifier(), T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001945 D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001946
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001947 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001948 if (Invalid)
1949 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001950
David Majnemer89189202013-08-28 23:48:32 +00001951 if (D->hasDefaultArgument()) {
1952 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1953 if (!Value.isInvalid())
1954 Param->setDefaultArgument(Value.get(), false);
1955 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001956
1957 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001958 // scope.
1959 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001960 return Param;
1961}
1962
Richard Smith1fde8ec2012-09-07 02:06:42 +00001963static void collectUnexpandedParameterPacks(
1964 Sema &S,
1965 TemplateParameterList *Params,
1966 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1967 for (TemplateParameterList::const_iterator I = Params->begin(),
1968 E = Params->end(); I != E; ++I) {
1969 if ((*I)->isTemplateParameterPack())
1970 continue;
1971 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1972 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1973 Unexpanded);
1974 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1975 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1976 Unexpanded);
1977 }
1978}
1979
Anders Carlsson4bd78752009-08-28 15:18:15 +00001980Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00001981TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1982 TemplateTemplateParmDecl *D) {
1983 // Instantiate the template parameter list of the template template parameter.
1984 TemplateParameterList *TempParams = D->getTemplateParameters();
1985 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001986 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1987
1988 bool IsExpandedParameterPack = false;
1989
1990 if (D->isExpandedParameterPack()) {
1991 // The template template parameter pack is an already-expanded pack
1992 // expansion of template parameters. Substitute into each of the expanded
1993 // parameters.
1994 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1995 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1996 I != N; ++I) {
1997 LocalInstantiationScope Scope(SemaRef);
1998 TemplateParameterList *Expansion =
1999 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2000 if (!Expansion)
2001 return 0;
2002 ExpandedParams.push_back(Expansion);
2003 }
2004
2005 IsExpandedParameterPack = true;
2006 InstParams = TempParams;
2007 } else if (D->isPackExpansion()) {
2008 // The template template parameter pack expands to a pack of template
2009 // template parameters. Determine whether we need to expand this parameter
2010 // pack into separate parameters.
2011 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2012 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2013 Unexpanded);
2014
2015 // Determine whether the set of unexpanded parameter packs can and should
2016 // be expanded.
2017 bool Expand = true;
2018 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002019 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002020 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2021 TempParams->getSourceRange(),
2022 Unexpanded,
2023 TemplateArgs,
2024 Expand, RetainExpansion,
2025 NumExpansions))
2026 return 0;
2027
2028 if (Expand) {
2029 for (unsigned I = 0; I != *NumExpansions; ++I) {
2030 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2031 LocalInstantiationScope Scope(SemaRef);
2032 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2033 if (!Expansion)
2034 return 0;
2035 ExpandedParams.push_back(Expansion);
2036 }
2037
2038 // Note that we have an expanded parameter pack. The "type" of this
2039 // expanded parameter pack is the original expansion type, but callers
2040 // will end up using the expanded parameter pack types for type-checking.
2041 IsExpandedParameterPack = true;
2042 InstParams = TempParams;
2043 } else {
2044 // We cannot fully expand the pack expansion now, so just substitute
2045 // into the pattern.
2046 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2047
2048 LocalInstantiationScope Scope(SemaRef);
2049 InstParams = SubstTemplateParams(TempParams);
2050 if (!InstParams)
2051 return 0;
2052 }
2053 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002054 // Perform the actual substitution of template parameters within a new,
2055 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002056 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002057 InstParams = SubstTemplateParams(TempParams);
2058 if (!InstParams)
Richard Smith1fde8ec2012-09-07 02:06:42 +00002059 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002060 }
2061
Douglas Gregor38fee962009-11-11 16:58:32 +00002062 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002063 TemplateTemplateParmDecl *Param;
2064 if (IsExpandedParameterPack)
2065 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2066 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002067 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00002068 D->getPosition(),
2069 D->getIdentifier(), InstParams,
2070 ExpandedParams);
2071 else
2072 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2073 D->getLocation(),
2074 D->getDepth() - TemplateArgs.getNumLevels(),
2075 D->getPosition(),
2076 D->isParameterPack(),
2077 D->getIdentifier(), InstParams);
David Majnemer89189202013-08-28 23:48:32 +00002078 if (D->hasDefaultArgument()) {
2079 NestedNameSpecifierLoc QualifierLoc =
2080 D->getDefaultArgument().getTemplateQualifierLoc();
2081 QualifierLoc =
2082 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2083 TemplateName TName = SemaRef.SubstTemplateName(
2084 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2085 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2086 if (!TName.isNull())
2087 Param->setDefaultArgument(
2088 TemplateArgumentLoc(TemplateArgument(TName),
2089 D->getDefaultArgument().getTemplateQualifierLoc(),
2090 D->getDefaultArgument().getTemplateNameLoc()),
2091 false);
2092 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002093 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002094
2095 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002096 // scope.
2097 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002098
Douglas Gregor38fee962009-11-11 16:58:32 +00002099 return Param;
2100}
2101
Douglas Gregore0b28662009-11-17 06:07:40 +00002102Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002103 // Using directives are never dependent (and never contain any types or
2104 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002105
Douglas Gregore0b28662009-11-17 06:07:40 +00002106 UsingDirectiveDecl *Inst
2107 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002108 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002109 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002110 D->getIdentLocation(),
2111 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002112 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002113
2114 // Add the using directive to its declaration context
2115 // only if this is not a function or method.
2116 if (!Owner->isFunctionOrMethod())
2117 Owner->addDecl(Inst);
2118
Douglas Gregore0b28662009-11-17 06:07:40 +00002119 return Inst;
2120}
2121
John McCallb96ec562009-12-04 22:46:56 +00002122Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002123
2124 // The nested name specifier may be dependent, for example
2125 // template <typename T> struct t {
2126 // struct s1 { T f1(); };
2127 // struct s2 : s1 { using s1::f1; };
2128 // };
2129 // template struct t<int>;
2130 // Here, in using s1::f1, s1 refers to t<T>::s1;
2131 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002132 NestedNameSpecifierLoc QualifierLoc
2133 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2134 TemplateArgs);
2135 if (!QualifierLoc)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00002136 return 0;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002137
2138 // The name info is non-dependent, so no transformation
2139 // is required.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002140 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCallb96ec562009-12-04 22:46:56 +00002141
John McCall84d87672009-12-10 09:41:52 +00002142 // We only need to do redeclaration lookups if we're in a class
2143 // scope (in fact, it's not really even possible in non-class
2144 // scopes).
2145 bool CheckRedeclaration = Owner->isRecord();
2146
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002147 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2148 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002149
John McCallb96ec562009-12-04 22:46:56 +00002150 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002151 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002152 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002153 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002154 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002155
Douglas Gregor0499ab62011-02-25 15:54:31 +00002156 CXXScopeSpec SS;
2157 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002158 if (CheckRedeclaration) {
2159 Prev.setHideTags(false);
2160 SemaRef.LookupQualifiedName(Prev, Owner);
2161
2162 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002163 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2164 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002165 D->getLocation(), Prev))
2166 NewUD->setInvalidDecl();
2167
2168 }
2169
2170 if (!NewUD->isInvalidDecl() &&
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002171 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
John McCallb96ec562009-12-04 22:46:56 +00002172 D->getLocation()))
2173 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002174
John McCallb96ec562009-12-04 22:46:56 +00002175 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2176 NewUD->setAccess(D->getAccess());
2177 Owner->addDecl(NewUD);
2178
John McCall84d87672009-12-10 09:41:52 +00002179 // Don't process the shadow decls for an invalid decl.
2180 if (NewUD->isInvalidDecl())
2181 return NewUD;
2182
Richard Smith23d55872012-04-02 01:30:27 +00002183 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2184 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2185 NewUD->setInvalidDecl();
2186 return NewUD;
2187 }
2188
John McCalla1d85502009-12-22 22:26:37 +00002189 bool isFunctionScope = Owner->isFunctionOrMethod();
2190
John McCall84d87672009-12-10 09:41:52 +00002191 // Process the shadow decls.
2192 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2193 I != E; ++I) {
2194 UsingShadowDecl *Shadow = *I;
2195 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002196 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2197 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002198 if (!InstTarget)
2199 return 0;
John McCall84d87672009-12-10 09:41:52 +00002200
Richard Smithfd8634a2013-10-23 02:17:46 +00002201 UsingShadowDecl *PrevDecl = 0;
2202 if (CheckRedeclaration) {
2203 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2204 continue;
2205 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2206 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2207 Shadow->getLocation(), OldPrev, TemplateArgs));
2208 }
John McCall84d87672009-12-10 09:41:52 +00002209
Richard Smithfd8634a2013-10-23 02:17:46 +00002210 UsingShadowDecl *InstShadow =
2211 SemaRef.BuildUsingShadowDecl(/*Scope*/0, NewUD, InstTarget, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002212 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002213
2214 if (isFunctionScope)
2215 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002216 }
John McCallb96ec562009-12-04 22:46:56 +00002217
2218 return NewUD;
2219}
2220
2221Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002222 // Ignore these; we handle them in bulk when processing the UsingDecl.
2223 return 0;
John McCallb96ec562009-12-04 22:46:56 +00002224}
2225
John McCalle61f2ba2009-11-18 02:36:19 +00002226Decl * TemplateDeclInstantiator
2227 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002228 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002229 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002230 TemplateArgs);
2231 if (!QualifierLoc)
Anders Carlsson4bd78752009-08-28 15:18:15 +00002232 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002233
Anders Carlsson4bd78752009-08-28 15:18:15 +00002234 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002235 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002236
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002237 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Kramerd81108f2012-11-14 15:08:31 +00002238 // Hence, no transformation is required for it.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002239 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002240 NamedDecl *UD =
John McCall3f746822009-11-17 05:59:44 +00002241 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002242 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002243 /*instantiation*/ true,
2244 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor6044d692010-05-19 17:02:24 +00002245 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002246 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2247
John McCalle61f2ba2009-11-18 02:36:19 +00002248 return UD;
2249}
2250
2251Decl * TemplateDeclInstantiator
2252 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002253 NestedNameSpecifierLoc QualifierLoc
2254 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2255 if (!QualifierLoc)
John McCalle61f2ba2009-11-18 02:36:19 +00002256 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002257
John McCalle61f2ba2009-11-18 02:36:19 +00002258 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002259 SS.Adopt(QualifierLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00002260
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002261 DeclarationNameInfo NameInfo
2262 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2263
John McCalle61f2ba2009-11-18 02:36:19 +00002264 NamedDecl *UD =
2265 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002266 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002267 /*instantiation*/ true,
2268 /*typename*/ false, SourceLocation());
Douglas Gregor6044d692010-05-19 17:02:24 +00002269 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002270 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2271
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002272 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00002273}
2274
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002275
2276Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2277 ClassScopeFunctionSpecializationDecl *Decl) {
2278 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber7b5a7162012-06-25 17:21:05 +00002279 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2280 0, true));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002281
2282 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2283 Sema::ForRedeclaration);
2284
Nico Weber7b5a7162012-06-25 17:21:05 +00002285 TemplateArgumentListInfo TemplateArgs;
2286 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2287 if (Decl->hasExplicitTemplateArgs()) {
2288 TemplateArgs = Decl->templateArgs();
2289 TemplateArgsPtr = &TemplateArgs;
2290 }
2291
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002292 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002293 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2294 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002295 NewFD->setInvalidDecl();
2296 return NewFD;
2297 }
2298
2299 // Associate the specialization with the pattern.
2300 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2301 assert(Specialization && "Class scope Specialization is null");
2302 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2303
2304 return NewFD;
2305}
2306
Alexey Bataeva769e072013-03-22 06:34:35 +00002307Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2308 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002309 SmallVector<Expr *, 5> Vars;
2310 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2311 E = D->varlist_end();
Alexey Bataeva769e072013-03-22 06:34:35 +00002312 I != E; ++I) {
2313 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2314 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002315 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002316 }
2317
2318 OMPThreadPrivateDecl *TD =
2319 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2320
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002321 TD->setAccess(AS_public);
2322 Owner->addDecl(TD);
2323
Alexey Bataeva769e072013-03-22 06:34:35 +00002324 return TD;
2325}
2326
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002327Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2328 return VisitFunctionDecl(D, 0);
2329}
2330
2331Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2332 return VisitCXXMethodDecl(D, 0);
2333}
2334
2335Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2336 llvm_unreachable("There are only CXXRecordDecls in C++");
2337}
2338
2339Decl *
2340TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2341 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00002342 // As a MS extension, we permit class-scope explicit specialization
2343 // of member class templates.
2344 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2345 assert(ClassTemplate->getDeclContext()->isRecord() &&
2346 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2347 "can only instantiate an explicit specialization "
2348 "for a member class template");
2349
2350 // Lookup the already-instantiated declaration in the instantiation
2351 // of the class template. FIXME: Diagnose or assert if this fails?
2352 DeclContext::lookup_result Found
2353 = Owner->lookup(ClassTemplate->getDeclName());
2354 if (Found.empty())
2355 return 0;
2356 ClassTemplateDecl *InstClassTemplate
2357 = dyn_cast<ClassTemplateDecl>(Found.front());
2358 if (!InstClassTemplate)
2359 return 0;
2360
2361 // Substitute into the template arguments of the class template explicit
2362 // specialization.
2363 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2364 castAs<TemplateSpecializationTypeLoc>();
2365 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2366 Loc.getRAngleLoc());
2367 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2368 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2369 ArgLocs.push_back(Loc.getArgLoc(I));
2370 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2371 InstTemplateArgs, TemplateArgs))
2372 return 0;
2373
2374 // Check that the template argument list is well-formed for this
2375 // class template.
2376 SmallVector<TemplateArgument, 4> Converted;
2377 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2378 D->getLocation(),
2379 InstTemplateArgs,
2380 false,
2381 Converted))
2382 return 0;
2383
2384 // Figure out where to insert this class template explicit specialization
2385 // in the member template's set of class template explicit specializations.
2386 void *InsertPos = 0;
2387 ClassTemplateSpecializationDecl *PrevDecl =
2388 InstClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2389 InsertPos);
2390
2391 // Check whether we've already seen a conflicting instantiation of this
2392 // declaration (for instance, if there was a prior implicit instantiation).
2393 bool Ignored;
2394 if (PrevDecl &&
2395 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2396 D->getSpecializationKind(),
2397 PrevDecl,
2398 PrevDecl->getSpecializationKind(),
2399 PrevDecl->getPointOfInstantiation(),
2400 Ignored))
2401 return 0;
2402
2403 // If PrevDecl was a definition and D is also a definition, diagnose.
2404 // This happens in cases like:
2405 //
2406 // template<typename T, typename U>
2407 // struct Outer {
2408 // template<typename X> struct Inner;
2409 // template<> struct Inner<T> {};
2410 // template<> struct Inner<U> {};
2411 // };
2412 //
2413 // Outer<int, int> outer; // error: the explicit specializations of Inner
2414 // // have the same signature.
2415 if (PrevDecl && PrevDecl->getDefinition() &&
2416 D->isThisDeclarationADefinition()) {
2417 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2418 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2419 diag::note_previous_definition);
2420 return 0;
2421 }
2422
2423 // Create the class template partial specialization declaration.
2424 ClassTemplateSpecializationDecl *InstD
2425 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2426 D->getTagKind(),
2427 Owner,
2428 D->getLocStart(),
2429 D->getLocation(),
2430 InstClassTemplate,
2431 Converted.data(),
2432 Converted.size(),
2433 PrevDecl);
2434
2435 // Add this partial specialization to the set of class template partial
2436 // specializations.
2437 if (!PrevDecl)
2438 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2439
2440 // Substitute the nested name specifier, if any.
2441 if (SubstQualifier(D, InstD))
2442 return 0;
2443
2444 // Build the canonical type that describes the converted template
2445 // arguments of the class template explicit specialization.
2446 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2447 TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2448 SemaRef.Context.getRecordType(InstD));
2449
2450 // Build the fully-sugared type for this class template
2451 // specialization as the user wrote in the specialization
2452 // itself. This means that we'll pretty-print the type retrieved
2453 // from the specialization's declaration the way that the user
2454 // actually wrote the specialization, rather than formatting the
2455 // name based on the "canonical" representation used to store the
2456 // template arguments in the specialization.
2457 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2458 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2459 CanonType);
2460
2461 InstD->setAccess(D->getAccess());
2462 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2463 InstD->setSpecializationKind(D->getSpecializationKind());
2464 InstD->setTypeAsWritten(WrittenTy);
2465 InstD->setExternLoc(D->getExternLoc());
2466 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2467
2468 Owner->addDecl(InstD);
2469
2470 // Instantiate the members of the class-scope explicit specialization eagerly.
2471 // We don't have support for lazy instantiation of an explicit specialization
2472 // yet, and MSVC eagerly instantiates in this case.
2473 if (D->isThisDeclarationADefinition() &&
2474 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2475 TSK_ImplicitInstantiation,
2476 /*Complain=*/true))
2477 return 0;
2478
2479 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002480}
2481
Larisse Voufo39a1e502013-08-06 01:03:05 +00002482Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2483 VarTemplateSpecializationDecl *D) {
2484
2485 TemplateArgumentListInfo VarTemplateArgsInfo;
2486 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2487 assert(VarTemplate &&
2488 "A template specialization without specialized template?");
2489
2490 // Substitute the current template arguments.
2491 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2492 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2493 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2494
2495 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2496 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2497 return 0;
2498
2499 // Check that the template argument list is well-formed for this template.
2500 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002501 if (SemaRef.CheckTemplateArgumentList(
2502 VarTemplate, VarTemplate->getLocStart(),
2503 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002504 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002505 return 0;
2506
2507 // Find the variable template specialization declaration that
2508 // corresponds to these arguments.
2509 void *InsertPos = 0;
2510 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2511 Converted.data(), Converted.size(), InsertPos))
2512 // If we already have a variable template specialization, return it.
2513 return VarSpec;
2514
2515 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2516 VarTemplateArgsInfo, Converted);
2517}
2518
2519Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2520 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2521 const TemplateArgumentListInfo &TemplateArgsInfo,
Richard Smith8809a0c2013-09-27 20:14:12 +00002522 llvm::ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002523
2524 // If this is the variable for an anonymous struct or union,
2525 // instantiate the anonymous struct/union type first.
2526 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2527 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2528 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2529 return 0;
2530
2531 // Do substitution on the type of the declaration
2532 TypeSourceInfo *DI =
2533 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2534 D->getTypeSpecStartLoc(), D->getDeclName());
2535 if (!DI)
2536 return 0;
2537
2538 if (DI->getType()->isFunctionType()) {
2539 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2540 << D->isStaticDataMember() << DI->getType();
2541 return 0;
2542 }
2543
2544 // Build the instantiated declaration
2545 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2546 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2547 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2548 Converted.size());
2549 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00002550 if (InsertPos)
2551 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002552
2553 // Substitute the nested name specifier, if any.
2554 if (SubstQualifier(D, Var))
2555 return 0;
2556
2557 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00002558 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002559
2560 return Var;
2561}
2562
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002563Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2564 llvm_unreachable("@defs is not supported in Objective-C++");
2565}
2566
2567Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2568 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2569 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2570 DiagnosticsEngine::Error,
2571 "cannot instantiate %0 yet");
2572 SemaRef.Diag(D->getLocation(), DiagID)
2573 << D->getDeclKindName();
2574
2575 return 0;
2576}
2577
2578Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2579 llvm_unreachable("Unexpected decl");
2580}
2581
John McCall76d824f2009-08-25 22:02:44 +00002582Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002583 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00002584 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00002585 if (D->isInvalidDecl())
2586 return 0;
2587
Douglas Gregord7e7a512009-03-17 21:15:40 +00002588 return Instantiator.Visit(D);
2589}
2590
John McCall87a44eb2009-08-20 01:44:21 +00002591/// \brief Instantiates a nested template parameter list in the current
2592/// instantiation context.
2593///
2594/// \param L The parameter list to instantiate
2595///
2596/// \returns NULL if there was an error
2597TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00002598TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00002599 // Get errors for all the parameters before bailing out.
2600 bool Invalid = false;
2601
2602 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002603 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00002604 ParamVector Params;
2605 Params.reserve(N);
2606 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2607 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002608 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00002609 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00002610 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00002611 }
2612
2613 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00002614 if (Invalid)
John McCall87a44eb2009-08-20 01:44:21 +00002615 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +00002616
2617 TemplateParameterList *InstL
2618 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2619 L->getLAngleLoc(), &Params.front(), N,
2620 L->getRAngleLoc());
2621 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00002622}
John McCall87a44eb2009-08-20 01:44:21 +00002623
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002624/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002625/// specialization.
2626///
2627/// \param ClassTemplate the (instantiated) class template that is partially
2628// specialized by the instantiation of \p PartialSpec.
2629///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002630/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002631/// specialization that we are instantiating.
2632///
Douglas Gregor869853e2010-11-10 19:44:59 +00002633/// \returns The instantiated partial specialization, if successful; otherwise,
2634/// NULL to indicate an error.
2635ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00002636TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2637 ClassTemplateDecl *ClassTemplate,
2638 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00002639 // Create a local instantiation scope for this class template partial
2640 // specialization, which will contain the instantiations of the template
2641 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00002642 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002643
Douglas Gregor21610382009-10-29 00:04:11 +00002644 // Substitute into the template parameters of the class template partial
2645 // specialization.
2646 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2647 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2648 if (!InstParams)
Douglas Gregor869853e2010-11-10 19:44:59 +00002649 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002650
Douglas Gregor21610382009-10-29 00:04:11 +00002651 // Substitute into the template arguments of the class template partial
2652 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002653 const ASTTemplateArgumentListInfo *TemplArgInfo
2654 = PartialSpec->getTemplateArgsAsWritten();
2655 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2656 TemplArgInfo->RAngleLoc);
2657 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2658 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002659 InstTemplateArgs, TemplateArgs))
2660 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002661
Douglas Gregor21610382009-10-29 00:04:11 +00002662 // Check that the template argument list is well-formed for this
2663 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002664 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002665 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00002666 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002667 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002668 false,
2669 Converted))
Douglas Gregor869853e2010-11-10 19:44:59 +00002670 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002671
2672 // Figure out where to insert this class template partial specialization
2673 // in the member template's set of class template partial specializations.
Douglas Gregor21610382009-10-29 00:04:11 +00002674 void *InsertPos = 0;
2675 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002676 = ClassTemplate->findPartialSpecialization(Converted.data(),
2677 Converted.size(), InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002678
Douglas Gregor21610382009-10-29 00:04:11 +00002679 // Build the canonical type that describes the converted template
2680 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002681 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00002682 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002683 Converted.data(),
2684 Converted.size());
Douglas Gregor21610382009-10-29 00:04:11 +00002685
2686 // Build the fully-sugared type for this class template
2687 // specialization as the user wrote in the specialization
2688 // itself. This means that we'll pretty-print the type retrieved
2689 // from the specialization's declaration the way that the user
2690 // actually wrote the specialization, rather than formatting the
2691 // name based on the "canonical" representation used to store the
2692 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00002693 TypeSourceInfo *WrittenTy
2694 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2695 TemplateName(ClassTemplate),
2696 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002697 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002698 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002699
Douglas Gregor21610382009-10-29 00:04:11 +00002700 if (PrevDecl) {
2701 // We've already seen a partial specialization with the same template
2702 // parameters and template arguments. This can happen, for example, when
2703 // substituting the outer template arguments ends up causing two
2704 // class template partial specializations of a member class template
2705 // to have identical forms, e.g.,
2706 //
2707 // template<typename T, typename U>
2708 // struct Outer {
2709 // template<typename X, typename Y> struct Inner;
2710 // template<typename Y> struct Inner<T, Y>;
2711 // template<typename Y> struct Inner<U, Y>;
2712 // };
2713 //
2714 // Outer<int, int> outer; // error: the partial specializations of Inner
2715 // // have the same signature.
2716 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00002717 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00002718 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2719 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregor869853e2010-11-10 19:44:59 +00002720 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002721 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002722
2723
Douglas Gregor21610382009-10-29 00:04:11 +00002724 // Create the class template partial specialization declaration.
2725 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002726 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002727 PartialSpec->getTagKind(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002728 Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002729 PartialSpec->getLocStart(),
2730 PartialSpec->getLocation(),
Douglas Gregor21610382009-10-29 00:04:11 +00002731 InstParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002732 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002733 Converted.data(),
2734 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00002735 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00002736 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00002737 0);
John McCall3e11ebe2010-03-15 10:12:16 +00002738 // Substitute the nested name specifier, if any.
2739 if (SubstQualifier(PartialSpec, InstPartialSpec))
2740 return 0;
2741
Douglas Gregor21610382009-10-29 00:04:11 +00002742 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00002743 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002744
Douglas Gregor21610382009-10-29 00:04:11 +00002745 // Add this partial specialization to the set of class template partial
2746 // specializations.
Douglas Gregorce9978f2012-03-28 14:34:23 +00002747 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregor869853e2010-11-10 19:44:59 +00002748 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00002749}
2750
Larisse Voufo39a1e502013-08-06 01:03:05 +00002751/// \brief Instantiate the declaration of a variable template partial
2752/// specialization.
2753///
2754/// \param VarTemplate the (instantiated) variable template that is partially
2755/// specialized by the instantiation of \p PartialSpec.
2756///
2757/// \param PartialSpec the (uninstantiated) variable template partial
2758/// specialization that we are instantiating.
2759///
2760/// \returns The instantiated partial specialization, if successful; otherwise,
2761/// NULL to indicate an error.
2762VarTemplatePartialSpecializationDecl *
2763TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2764 VarTemplateDecl *VarTemplate,
2765 VarTemplatePartialSpecializationDecl *PartialSpec) {
2766 // Create a local instantiation scope for this variable template partial
2767 // specialization, which will contain the instantiations of the template
2768 // parameters.
2769 LocalInstantiationScope Scope(SemaRef);
2770
2771 // Substitute into the template parameters of the variable template partial
2772 // specialization.
2773 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2774 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2775 if (!InstParams)
2776 return 0;
2777
2778 // Substitute into the template arguments of the variable template partial
2779 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002780 const ASTTemplateArgumentListInfo *TemplArgInfo
2781 = PartialSpec->getTemplateArgsAsWritten();
2782 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2783 TemplArgInfo->RAngleLoc);
2784 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2785 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002786 InstTemplateArgs, TemplateArgs))
2787 return 0;
2788
2789 // Check that the template argument list is well-formed for this
2790 // class template.
2791 SmallVector<TemplateArgument, 4> Converted;
2792 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2793 InstTemplateArgs, false, Converted))
2794 return 0;
2795
2796 // Figure out where to insert this variable template partial specialization
2797 // in the member template's set of variable template partial specializations.
2798 void *InsertPos = 0;
2799 VarTemplateSpecializationDecl *PrevDecl =
2800 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2801 InsertPos);
2802
2803 // Build the canonical type that describes the converted template
2804 // arguments of the variable template partial specialization.
2805 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2806 TemplateName(VarTemplate), Converted.data(), Converted.size());
2807
2808 // Build the fully-sugared type for this variable template
2809 // specialization as the user wrote in the specialization
2810 // itself. This means that we'll pretty-print the type retrieved
2811 // from the specialization's declaration the way that the user
2812 // actually wrote the specialization, rather than formatting the
2813 // name based on the "canonical" representation used to store the
2814 // template arguments in the specialization.
2815 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2816 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2817 CanonType);
2818
2819 if (PrevDecl) {
2820 // We've already seen a partial specialization with the same template
2821 // parameters and template arguments. This can happen, for example, when
2822 // substituting the outer template arguments ends up causing two
2823 // variable template partial specializations of a member variable template
2824 // to have identical forms, e.g.,
2825 //
2826 // template<typename T, typename U>
2827 // struct Outer {
2828 // template<typename X, typename Y> pair<X,Y> p;
2829 // template<typename Y> pair<T, Y> p;
2830 // template<typename Y> pair<U, Y> p;
2831 // };
2832 //
2833 // Outer<int, int> outer; // error: the partial specializations of Inner
2834 // // have the same signature.
2835 SemaRef.Diag(PartialSpec->getLocation(),
2836 diag::err_var_partial_spec_redeclared)
2837 << WrittenTy->getType();
2838 SemaRef.Diag(PrevDecl->getLocation(),
2839 diag::note_var_prev_partial_spec_here);
2840 return 0;
2841 }
2842
2843 // Do substitution on the type of the declaration
2844 TypeSourceInfo *DI = SemaRef.SubstType(
2845 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2846 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2847 if (!DI)
2848 return 0;
2849
2850 if (DI->getType()->isFunctionType()) {
2851 SemaRef.Diag(PartialSpec->getLocation(),
2852 diag::err_variable_instantiates_to_function)
2853 << PartialSpec->isStaticDataMember() << DI->getType();
2854 return 0;
2855 }
2856
2857 // Create the variable template partial specialization declaration.
2858 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2859 VarTemplatePartialSpecializationDecl::Create(
2860 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2861 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2862 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smithb2f61b42013-08-22 23:27:37 +00002863 Converted.size(), InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002864
2865 // Substitute the nested name specifier, if any.
2866 if (SubstQualifier(PartialSpec, InstPartialSpec))
2867 return 0;
2868
2869 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2870 InstPartialSpec->setTypeAsWritten(WrittenTy);
2871
Larisse Voufo39a1e502013-08-06 01:03:05 +00002872 // Add this partial specialization to the set of variable template partial
2873 // specializations. The instantiation of the initializer is not necessary.
2874 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002875
Larisse Voufo4cda4612013-08-22 00:28:27 +00002876 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00002877 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002878
Larisse Voufo39a1e502013-08-06 01:03:05 +00002879 return InstPartialSpec;
2880}
2881
John McCall58f10c32010-03-11 09:03:00 +00002882TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00002883TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002884 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00002885 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2886 assert(OldTInfo && "substituting function without type source info");
2887 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregor3024f072012-04-16 07:05:22 +00002888
2889 CXXRecordDecl *ThisContext = 0;
2890 unsigned ThisTypeQuals = 0;
2891 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002892 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00002893 ThisTypeQuals = Method->getTypeQualifiers();
2894 }
2895
John McCallb29f78f2010-04-09 17:38:44 +00002896 TypeSourceInfo *NewTInfo
2897 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2898 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002899 D->getDeclName(),
2900 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00002901 if (!NewTInfo)
2902 return 0;
Douglas Gregor21342092009-03-24 00:38:23 +00002903
Reid Klecknera09e44c2013-07-31 21:00:18 +00002904 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2905 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2906 if (NewTInfo != OldTInfo) {
2907 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00002908 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00002909 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00002910 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002911 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00002912 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002913 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00002914 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2915
David Blaikie05785d12013-02-20 22:23:23 +00002916 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00002917 if (OldParam->isParameterPack())
2918 NumArgumentsInExpansion =
2919 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2920 TemplateArgs);
2921 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002922 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00002923 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002924 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00002925 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00002926 Scope->InstantiatedLocal(OldParam, NewParam);
2927 } else {
2928 // Parameter pack expansion: make the instantiation an argument pack.
2929 Scope->MakeInstantiatedLocalArgPack(OldParam);
2930 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002931 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00002932 Params.push_back(NewParam);
2933 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2934 }
Douglas Gregorf3010112011-01-07 16:43:16 +00002935 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002936 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002937 } else {
2938 // The function type itself was not dependent and therefore no
2939 // substitution occurred. However, we still need to instantiate
2940 // the function parameters themselves.
2941 const FunctionProtoType *OldProto =
2942 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002943 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
2944 ++i) {
2945 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00002946 if (!OldParam) {
2947 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00002948 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00002949 continue;
2950 }
2951
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002952 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00002953 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002954 if (!Parm)
2955 return 0;
2956 Params.push_back(Parm);
2957 }
Douglas Gregor940bca72010-04-12 07:48:19 +00002958 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002959 } else {
2960 // If the type of this function, after ignoring parentheses, is not
2961 // *directly* a function type, then we're instantiating a function that
2962 // was declared via a typedef or with attributes, e.g.,
2963 //
2964 // typedef int functype(int, int);
2965 // functype func;
2966 // int __cdecl meth(int, int);
2967 //
2968 // In this case, we'll just go instantiate the ParmVarDecls that we
2969 // synthesized in the method declaration.
2970 SmallVector<QualType, 4> ParamTypes;
2971 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2972 D->getNumParams(), TemplateArgs, ParamTypes,
2973 &Params))
2974 return 0;
Douglas Gregor940bca72010-04-12 07:48:19 +00002975 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002976
John McCall58f10c32010-03-11 09:03:00 +00002977 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00002978}
2979
Richard Smithf623c962012-04-17 00:58:00 +00002980/// Introduce the instantiated function parameters into the local
2981/// instantiation scope, and set the parameter names to those used
2982/// in the template.
2983static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2984 const FunctionDecl *PatternDecl,
2985 LocalInstantiationScope &Scope,
2986 const MultiLevelTemplateArgumentList &TemplateArgs) {
2987 unsigned FParamIdx = 0;
2988 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2989 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2990 if (!PatternParam->isParameterPack()) {
2991 // Simple case: not a parameter pack.
2992 assert(FParamIdx < Function->getNumParams());
2993 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2994 FunctionParam->setDeclName(PatternParam->getDeclName());
2995 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2996 ++FParamIdx;
2997 continue;
2998 }
2999
3000 // Expand the parameter pack.
3001 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003002 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003003 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00003004 assert(NumArgumentsInExpansion &&
3005 "should only be called when all template arguments are known");
3006 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00003007 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3008 FunctionParam->setDeclName(PatternParam->getDeclName());
3009 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3010 ++FParamIdx;
3011 }
3012 }
3013}
3014
3015static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
3016 const FunctionProtoType *Proto,
3017 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smithd3729422012-04-19 00:08:28 +00003018 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
3019
Richard Smithf623c962012-04-17 00:58:00 +00003020 // C++11 [expr.prim.general]p3:
3021 // If a declaration declares a member function or member function
3022 // template of a class X, the expression this is a prvalue of type
3023 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3024 // and the end of the function-definition, member-declarator, or
3025 // declarator.
3026 CXXRecordDecl *ThisContext = 0;
3027 unsigned ThisTypeQuals = 0;
3028 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
3029 ThisContext = Method->getParent();
3030 ThisTypeQuals = Method->getTypeQualifiers();
3031 }
3032 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003033 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithf623c962012-04-17 00:58:00 +00003034
3035 // The function has an exception specification or a "noreturn"
3036 // attribute. Substitute into each of the exception types.
3037 SmallVector<QualType, 4> Exceptions;
3038 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
3039 // FIXME: Poor location information!
3040 if (const PackExpansionType *PackExpansion
3041 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
3042 // We have a pack expansion. Instantiate it.
3043 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3044 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
3045 Unexpanded);
3046 assert(!Unexpanded.empty() &&
3047 "Pack expansion without parameter packs?");
3048
3049 bool Expand = false;
3050 bool RetainExpansion = false;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003051 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithf623c962012-04-17 00:58:00 +00003052 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
3053 SourceRange(),
3054 Unexpanded,
3055 TemplateArgs,
3056 Expand,
3057 RetainExpansion,
3058 NumExpansions))
3059 break;
3060
3061 if (!Expand) {
3062 // We can't expand this pack expansion into separate arguments yet;
3063 // just substitute into the pattern and create a new pack expansion
3064 // type.
3065 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3066 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3067 TemplateArgs,
3068 New->getLocation(), New->getDeclName());
3069 if (T.isNull())
3070 break;
3071
3072 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
3073 Exceptions.push_back(T);
3074 continue;
3075 }
3076
3077 // Substitute into the pack expansion pattern for each template
3078 bool Invalid = false;
3079 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
3080 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
3081
3082 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3083 TemplateArgs,
3084 New->getLocation(), New->getDeclName());
3085 if (T.isNull()) {
3086 Invalid = true;
3087 break;
3088 }
3089
3090 Exceptions.push_back(T);
3091 }
3092
3093 if (Invalid)
3094 break;
3095
3096 continue;
3097 }
3098
3099 QualType T
3100 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
3101 New->getLocation(), New->getDeclName());
3102 if (T.isNull() ||
3103 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
3104 continue;
3105
3106 Exceptions.push_back(T);
3107 }
3108 Expr *NoexceptExpr = 0;
3109 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
3110 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3111 Sema::ConstantEvaluated);
3112 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
3113 if (E.isUsable())
3114 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
3115
3116 if (E.isUsable()) {
3117 NoexceptExpr = E.take();
3118 if (!NoexceptExpr->isTypeDependent() &&
3119 !NoexceptExpr->isValueDependent())
Douglas Gregore2b37442012-05-04 22:38:52 +00003120 NoexceptExpr
3121 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
3122 0, diag::err_noexcept_needs_constant_expression,
3123 /*AllowFold*/ false).take();
Richard Smithf623c962012-04-17 00:58:00 +00003124 }
3125 }
3126
3127 // Rebuild the function type
3128 const FunctionProtoType *NewProto
3129 = New->getType()->getAs<FunctionProtoType>();
3130 assert(NewProto && "Template instantiation without function prototype?");
3131
3132 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
3133 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
3134 EPI.NumExceptions = Exceptions.size();
3135 EPI.Exceptions = Exceptions.data();
3136 EPI.NoexceptExpr = NoexceptExpr;
3137
Alp Toker314cc812014-01-25 16:55:45 +00003138 New->setType(SemaRef.Context.getFunctionType(NewProto->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00003139 NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003140}
3141
3142void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3143 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003144 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3145 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003146 return;
3147
3148 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3149 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003150 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003151 // We hit the instantiation depth limit. Clear the exception specification
3152 // so that our callers don't have to cope with EST_Uninstantiated.
3153 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3154 EPI.ExceptionSpecType = EST_None;
Alp Toker314cc812014-01-25 16:55:45 +00003155 Decl->setType(Context.getFunctionType(Proto->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00003156 Proto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003157 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003158 }
Richard Smithf623c962012-04-17 00:58:00 +00003159
3160 // Enter the scope of this instantiation. We don't use
3161 // PushDeclContext because we don't have a scope.
3162 Sema::ContextRAII savedContext(*this, Decl);
3163 LocalInstantiationScope Scope(*this);
3164
3165 MultiLevelTemplateArgumentList TemplateArgs =
3166 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
3167
Richard Smithd3729422012-04-19 00:08:28 +00003168 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3169 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003170
Richard Smithd3729422012-04-19 00:08:28 +00003171 ::InstantiateExceptionSpec(*this, Decl,
3172 Template->getType()->castAs<FunctionProtoType>(),
3173 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003174}
3175
Mike Stump11289f42009-09-09 15:08:12 +00003176/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003177/// declaration (New) from the corresponding fields of its template (Tmpl).
3178///
3179/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003180bool
3181TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003182 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003183 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003184 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003185
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003186 // Forward the mangling number from the template to the instantiated decl.
3187 SemaRef.Context.setManglingNumber(New,
3188 SemaRef.Context.getManglingNumber(Tmpl));
3189
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003190 // If we are performing substituting explicitly-specified template arguments
3191 // or deduced template arguments into a function template and we reach this
3192 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003193 // to keeping the new function template specialization. We therefore
3194 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003195 // into a template instantiation for this specific function template
3196 // specialization, which is not a SFINAE context, so that we diagnose any
3197 // further errors in the declaration itself.
3198 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3199 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3200 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3201 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003202 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003203 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003204 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003205 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003206 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003207 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003208 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003209 }
3210 }
Mike Stump11289f42009-09-09 15:08:12 +00003211
Douglas Gregor049bdca2009-12-08 17:45:32 +00003212 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3213 assert(Proto && "Function template without prototype?");
3214
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003215 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003216 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003217
Richard Smithf623c962012-04-17 00:58:00 +00003218 // DR1330: In C++11, defer instantiation of a non-trivial
3219 // exception specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003220 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithf623c962012-04-17 00:58:00 +00003221 EPI.ExceptionSpecType != EST_None &&
3222 EPI.ExceptionSpecType != EST_DynamicNone &&
3223 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smithd3729422012-04-19 00:08:28 +00003224 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3225 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3226 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003227 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3228 if (EPI.ExceptionSpecType == EST_Unevaluated)
3229 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003230
Richard Smithf623c962012-04-17 00:58:00 +00003231 // Mark the function has having an uninstantiated exception specification.
3232 const FunctionProtoType *NewProto
3233 = New->getType()->getAs<FunctionProtoType>();
3234 assert(NewProto && "Template instantiation without function prototype?");
3235 EPI = NewProto->getExtProtoInfo();
Richard Smith185be182013-04-10 05:48:59 +00003236 EPI.ExceptionSpecType = NewEST;
Richard Smithf623c962012-04-17 00:58:00 +00003237 EPI.ExceptionSpecDecl = New;
Richard Smithd3729422012-04-19 00:08:28 +00003238 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003239 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003240 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003241 } else {
3242 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3243 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003244 }
3245
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003246 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003247 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003248 Tmpl->isDefined(Definition);
3249
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003250 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3251 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003252
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003253 return false;
3254}
3255
Douglas Gregor21342092009-03-24 00:38:23 +00003256/// \brief Initializes common fields of an instantiated method
3257/// declaration (New) from the corresponding fields of its template
3258/// (Tmpl).
3259///
3260/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003261bool
3262TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003263 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003264 if (InitFunctionInstantiation(New, Tmpl))
3265 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003266
Douglas Gregor21342092009-03-24 00:38:23 +00003267 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003268 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003269 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003270
Douglas Gregor21342092009-03-24 00:38:23 +00003271 // FIXME: New needs a pointer to Tmpl
3272 return false;
3273}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003274
3275/// \brief Instantiate the definition of the given function from its
3276/// template.
3277///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003278/// \param PointOfInstantiation the point at which the instantiation was
3279/// required. Note that this is not precisely a "point of instantiation"
3280/// for the function, but it's close.
3281///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003282/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003283/// function template specialization or member function of a class template
3284/// specialization.
3285///
3286/// \param Recursive if true, recursively instantiates any functions that
3287/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003288///
3289/// \param DefinitionRequired if true, then we are performing an explicit
3290/// instantiation where the body of the function is required. Complain if
3291/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003292void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003293 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003294 bool Recursive,
3295 bool DefinitionRequired) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003296 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00003297 return;
3298
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003299 // Never instantiate an explicit specialization except if it is a class scope
3300 // explicit specialization.
3301 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3302 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003303 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003304
Douglas Gregor24c332b2009-05-14 21:06:31 +00003305 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003306 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003307 assert(PatternDecl && "instantiating a non-template");
3308
3309 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3310 assert(PatternDecl && "template definition is not a template");
3311 if (!Pattern) {
3312 // Try to find a defaulted definition
3313 PatternDecl->isDefined(PatternDecl);
Alexis Hunt92a0adf2011-05-25 22:02:25 +00003314 }
Alexis Hunt23f6b832011-05-27 20:00:14 +00003315 assert(PatternDecl && "template definition is not a template");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003316
Francois Pichet1c229c02011-04-22 22:18:13 +00003317 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003318 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003319 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00003320 PendingInstantiations.push_back(
3321 std::make_pair(Function, PointOfInstantiation));
3322 return;
3323 }
3324
David Majnemerf0a84f22013-08-16 08:29:13 +00003325 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003326 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003327 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003328 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003329 // FIXME: Optimize to allow individual templates to be deserialized.
3330 if (PatternDecl->isFromASTFile())
3331 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3332
3333 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3334 assert(LPT && "missing LateParsedTemplate");
3335 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet1c229c02011-04-22 22:18:13 +00003336 Pattern = PatternDecl->getBody(PatternDecl);
3337 }
3338
Alexis Hunt23f6b832011-05-27 20:00:14 +00003339 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003340 if (DefinitionRequired) {
3341 if (Function->getPrimaryTemplate())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003342 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003343 diag::err_explicit_instantiation_undefined_func_template)
3344 << Function->getPrimaryTemplate();
3345 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003346 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003347 diag::err_explicit_instantiation_undefined_member)
3348 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003349
Douglas Gregora8b89d22009-10-15 14:05:49 +00003350 if (PatternDecl)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003351 Diag(PatternDecl->getLocation(),
Douglas Gregora8b89d22009-10-15 14:05:49 +00003352 diag::note_explicit_instantiation_here);
Douglas Gregorfd7224f2010-05-17 17:57:54 +00003353 Function->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003354 } else if (Function->getTemplateSpecializationKind()
3355 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003356 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003357 std::make_pair(Function, PointOfInstantiation));
Douglas Gregora8b89d22009-10-15 14:05:49 +00003358 }
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003359
Douglas Gregor24c332b2009-05-14 21:06:31 +00003360 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00003361 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003362
Richard Smith2a7d4812013-05-04 07:00:32 +00003363 // C++1y [temp.explicit]p10:
3364 // Except for inline functions, declarations with types deduced from their
3365 // initializer or return value, and class template specializations, other
3366 // explicit instantiation declarations have the effect of suppressing the
3367 // implicit instantiation of the entity to which they refer.
Alp Toker314cc812014-01-25 16:55:45 +00003368 if (Function->getTemplateSpecializationKind() ==
3369 TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003370 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00003371 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003372 return;
Mike Stump11289f42009-09-09 15:08:12 +00003373
Richard Smithf3814ad2013-01-25 00:08:28 +00003374 if (PatternDecl->isInlined())
3375 Function->setImplicitlyInline();
3376
Douglas Gregor85673582009-05-18 17:01:57 +00003377 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003378 if (Inst.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003379 return;
3380
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00003381 // Copy the inner loc start from the pattern.
3382 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3383
Douglas Gregordda7ced2009-06-30 17:20:14 +00003384 // If we're performing recursive template instantiation, create our own
3385 // queue of pending implicit instantiations that we will instantiate later,
3386 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003387 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003388 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003389 SavePendingLocalImplicitInstantiationsRAII
3390 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003391 if (Recursive) {
3392 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003393 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003394 }
Mike Stump11289f42009-09-09 15:08:12 +00003395
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003396 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00003397 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00003398
Douglas Gregorb4850462009-05-14 23:26:13 +00003399 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003400 // recorded, unless we're actually a member function within a local
3401 // class, in which case we need to merge our results with the parent
3402 // scope (of the enclosing function).
3403 bool MergeWithParentScope = false;
3404 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3405 MergeWithParentScope = Rec->isLocalClass();
3406
3407 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00003408
Richard Smithbd305122012-12-11 01:14:52 +00003409 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003410 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00003411 else {
3412 ActOnStartOfFunctionDef(0, Function);
3413
3414 // Enter the scope of this instantiation. We don't use
3415 // PushDeclContext because we don't have a scope.
3416 Sema::ContextRAII savedContext(*this, Function);
3417
3418 MultiLevelTemplateArgumentList TemplateArgs =
3419 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3420
3421 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3422 TemplateArgs);
3423
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003424 // If this is a constructor, instantiate the member initializers.
3425 if (const CXXConstructorDecl *Ctor =
3426 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3427 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3428 TemplateArgs);
3429 }
3430
3431 // Instantiate the function body.
3432 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3433
3434 if (Body.isInvalid())
3435 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003436
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003437 ActOnFinishFunctionBody(Function, Body.get(),
3438 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00003439
3440 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3441
3442 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00003443 }
3444
Douglas Gregor28ad4b52009-05-26 20:50:29 +00003445 DeclGroupRef DG(Function);
3446 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003447
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003448 // This class may have local implicit instantiations that need to be
3449 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003450 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003451 Scope.Exit();
3452
Douglas Gregordda7ced2009-06-30 17:20:14 +00003453 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003454 // Define any pending vtables.
3455 DefineUsedVTables();
3456
Douglas Gregordda7ced2009-06-30 17:20:14 +00003457 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003458 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003459 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003460
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003461 // Restore the set of pending vtables.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003462 assert(VTableUses.empty() &&
3463 "VTableUses should be empty before it is discarded.");
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003464 VTableUses.swap(SavedVTableUses);
3465
Douglas Gregordda7ced2009-06-30 17:20:14 +00003466 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003467 assert(PendingInstantiations.empty() &&
3468 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003469 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregordda7ced2009-06-30 17:20:14 +00003470 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003471}
3472
Larisse Voufo39a1e502013-08-06 01:03:05 +00003473VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3474 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3475 const TemplateArgumentList &TemplateArgList,
3476 const TemplateArgumentListInfo &TemplateArgsInfo,
3477 SmallVectorImpl<TemplateArgument> &Converted,
3478 SourceLocation PointOfInstantiation, void *InsertPos,
3479 LateInstantiatedAttrVec *LateAttrs,
3480 LocalInstantiationScope *StartingScope) {
3481 if (FromVar->isInvalidDecl())
3482 return 0;
3483
3484 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003485 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003486 return 0;
3487
3488 MultiLevelTemplateArgumentList TemplateArgLists;
3489 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3490
Richard Smith8809a0c2013-09-27 20:14:12 +00003491 // Instantiate the first declaration of the variable template: for a partial
3492 // specialization of a static data member template, the first declaration may
3493 // or may not be the declaration in the class; if it's in the class, we want
3494 // to instantiate a member in the class (a declaration), and if it's outside,
3495 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00003496 //
3497 // If we're instantiating an explicitly-specialized member template or member
3498 // partial specialization, don't do this. The member specialization completely
3499 // replaces the original declaration in this case.
3500 bool IsMemberSpec = false;
3501 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3502 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3503 IsMemberSpec = PartialSpec->isMemberSpecialization();
3504 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3505 IsMemberSpec = FromTemplate->isMemberSpecialization();
3506 if (!IsMemberSpec)
3507 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00003508
Manuel Klimek5843add2013-09-30 13:29:01 +00003509 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3510 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3511 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003512
3513 // TODO: Set LateAttrs and StartingScope ...
3514
3515 return cast_or_null<VarTemplateSpecializationDecl>(
3516 Instantiator.VisitVarTemplateSpecializationDecl(
3517 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3518}
3519
3520/// \brief Instantiates a variable template specialization by completing it
3521/// with appropriate type information and initializer.
3522VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3523 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3524 const MultiLevelTemplateArgumentList &TemplateArgs) {
3525
3526 // Do substitution on the type of the declaration
3527 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00003528 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003529 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3530 if (!DI)
3531 return 0;
3532
3533 // Update the type of this variable template specialization.
3534 VarSpec->setType(DI->getType());
3535
3536 // Instantiate the initializer.
3537 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3538
3539 return VarSpec;
3540}
3541
3542/// BuildVariableInstantiation - Used after a new variable has been created.
3543/// Sets basic variable data and decides whether to postpone the
3544/// variable instantiation.
3545void Sema::BuildVariableInstantiation(
3546 VarDecl *NewVar, VarDecl *OldVar,
3547 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003548 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3549 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003550 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003551
Richard Smith541b38b2013-09-20 01:15:31 +00003552 // If we are instantiating a local extern declaration, the
3553 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003554 // If we are instantiating a static data member defined
3555 // out-of-line, the instantiation will have the same lexical
3556 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00003557 if (OldVar->isLocalExternDecl()) {
3558 NewVar->setLocalExternDecl();
3559 NewVar->setLexicalDeclContext(Owner);
3560 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003561 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3562 NewVar->setTSCSpec(OldVar->getTSCSpec());
3563 NewVar->setInitStyle(OldVar->getInitStyle());
3564 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3565 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00003566 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00003567 NewVar->setPreviousDeclInSameBlockScope(
3568 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003569 NewVar->setAccess(OldVar->getAccess());
3570
Richard Smith0b551192013-09-23 23:12:22 +00003571 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00003572 if (OldVar->isUsed(false))
3573 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003574 NewVar->setReferenced(OldVar->isReferenced());
3575 }
3576
David Majnemer50ce8352013-09-17 23:57:10 +00003577 // See if the old variable had a type-specifier that defined an anonymous tag.
3578 // If it did, mark the new variable as being the declarator for the new
3579 // anonymous tag.
3580 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3581 TagDecl *OldTag = OldTagType->getDecl();
3582 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3583 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3584 assert(!NewTag->hasNameForLinkage() &&
3585 !NewTag->hasDeclaratorForAnonDecl());
3586 NewTag->setDeclaratorForAnonDecl(NewVar);
3587 }
3588 }
3589
Larisse Voufo39a1e502013-08-06 01:03:05 +00003590 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3591
3592 if (NewVar->hasAttrs())
3593 CheckAlignasUnderalignment(NewVar);
3594
Richard Smith541b38b2013-09-20 01:15:31 +00003595 LookupResult Previous(
3596 *this, NewVar->getDeclName(), NewVar->getLocation(),
3597 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3598 : Sema::LookupOrdinaryName,
3599 Sema::ForRedeclaration);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003600
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00003601 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3602 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3603 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00003604 // We have a previous declaration. Use that one, so we merge with the
3605 // right type.
3606 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3607 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3608 Previous.addDecl(NewPrev);
3609 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3610 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003611 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003612 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003613
Richard Smith541b38b2013-09-20 01:15:31 +00003614 if (!InstantiatingVarTemplate) {
3615 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3616 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003617 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00003618 }
3619
3620 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003621 if (NewVar->getDeclContext()->isFunctionOrMethod())
3622 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3623 }
3624
3625 // Link instantiations of static data members back to the template from
3626 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003627 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003628 NewVar->setInstantiationOfStaticDataMember(OldVar,
3629 TSK_ImplicitInstantiation);
3630
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003631 // Forward the mangling number from the template to the instantiated decl.
3632 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00003633 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003634
Richard Smith8809a0c2013-09-27 20:14:12 +00003635 // Delay instantiation of the initializer for variable templates until a
3636 // definition of the variable is needed.
3637 if (!isa<VarTemplateSpecializationDecl>(NewVar) && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003638 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3639
3640 // Diagnose unused local variables with dependent types, where the diagnostic
3641 // will have been deferred.
3642 if (!NewVar->isInvalidDecl() &&
3643 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3644 OldVar->getType()->isDependentType())
3645 DiagnoseUnusedDecl(NewVar);
3646}
3647
3648/// \brief Instantiate the initializer of a variable.
3649void Sema::InstantiateVariableInitializer(
3650 VarDecl *Var, VarDecl *OldVar,
3651 const MultiLevelTemplateArgumentList &TemplateArgs) {
3652
3653 if (Var->getAnyInitializer())
3654 // We already have an initializer in the class.
3655 return;
3656
3657 if (OldVar->getInit()) {
3658 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3659 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3660 else
3661 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3662
3663 // Instantiate the initializer.
3664 ExprResult Init =
3665 SubstInitializer(OldVar->getInit(), TemplateArgs,
3666 OldVar->getInitStyle() == VarDecl::CallInit);
3667 if (!Init.isInvalid()) {
3668 bool TypeMayContainAuto = true;
3669 if (Init.get()) {
3670 bool DirectInit = OldVar->isDirectInit();
3671 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3672 } else
3673 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3674 } else {
3675 // FIXME: Not too happy about invalidating the declaration
3676 // because of a bogus initializer.
3677 Var->setInvalidDecl();
3678 }
3679
3680 PopExpressionEvaluationContext();
3681 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3682 !Var->isCXXForRangeDecl())
3683 ActOnUninitializedDecl(Var, false);
3684}
3685
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003686/// \brief Instantiate the definition of the given variable from its
3687/// template.
3688///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003689/// \param PointOfInstantiation the point at which the instantiation was
3690/// required. Note that this is not precisely a "point of instantiation"
3691/// for the function, but it's close.
3692///
3693/// \param Var the already-instantiated declaration of a static member
3694/// variable of a class template specialization.
3695///
3696/// \param Recursive if true, recursively instantiates any functions that
3697/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003698///
3699/// \param DefinitionRequired if true, then we are performing an explicit
3700/// instantiation where an out-of-line definition of the member variable
3701/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003702void Sema::InstantiateStaticDataMemberDefinition(
3703 SourceLocation PointOfInstantiation,
3704 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003705 bool Recursive,
3706 bool DefinitionRequired) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003707 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3708 DefinitionRequired);
3709}
3710
3711void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3712 VarDecl *Var, bool Recursive,
3713 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003714 if (Var->isInvalidDecl())
3715 return;
Mike Stump11289f42009-09-09 15:08:12 +00003716
Larisse Voufo39a1e502013-08-06 01:03:05 +00003717 VarTemplateSpecializationDecl *VarSpec =
3718 dyn_cast<VarTemplateSpecializationDecl>(Var);
Richard Smith8809a0c2013-09-27 20:14:12 +00003719 VarDecl *PatternDecl = 0, *Def = 0;
3720 MultiLevelTemplateArgumentList TemplateArgs =
3721 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00003722
Larisse Voufo39a1e502013-08-06 01:03:05 +00003723 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003724 // If this is a variable template specialization, make sure that it is
3725 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003726 bool InstantiationDependent = false;
3727 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3728 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3729 "Only instantiate variable template specializations that are "
3730 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00003731 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003732
Richard Smith8809a0c2013-09-27 20:14:12 +00003733 // Find the variable initialization that we'll be substituting. If the
3734 // pattern was instantiated from a member template, look back further to
3735 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003736 assert(VarSpec->getSpecializedTemplate() &&
3737 "Specialization without specialized template?");
3738 llvm::PointerUnion<VarTemplateDecl *,
3739 VarTemplatePartialSpecializationDecl *> PatternPtr =
3740 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003741 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003742 VarTemplatePartialSpecializationDecl *Tmpl =
3743 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3744 while (VarTemplatePartialSpecializationDecl *From =
3745 Tmpl->getInstantiatedFromMember()) {
3746 if (Tmpl->isMemberSpecialization())
3747 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003748
Richard Smith8809a0c2013-09-27 20:14:12 +00003749 Tmpl = From;
3750 }
3751 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003752 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00003753 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3754 while (VarTemplateDecl *From =
3755 Tmpl->getInstantiatedFromMemberTemplate()) {
3756 if (Tmpl->isMemberSpecialization())
3757 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003758
Richard Smith8809a0c2013-09-27 20:14:12 +00003759 Tmpl = From;
3760 }
3761 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003762 }
Richard Smith8809a0c2013-09-27 20:14:12 +00003763
3764 // If this is a static data member template, there might be an
3765 // uninstantiated initializer on the declaration. If so, instantiate
3766 // it now.
3767 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00003768 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00003769 !Var->hasInit()) {
3770 // FIXME: Factor out the duplicated instantiation context setup/tear down
3771 // code here.
3772 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003773 if (Inst.isInvalid())
Richard Smith8809a0c2013-09-27 20:14:12 +00003774 return;
3775
3776 // If we're performing recursive template instantiation, create our own
3777 // queue of pending implicit instantiations that we will instantiate
3778 // later, while we're still within our own instantiation context.
3779 SmallVector<VTableUse, 16> SavedVTableUses;
3780 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3781 if (Recursive) {
3782 VTableUses.swap(SavedVTableUses);
3783 PendingInstantiations.swap(SavedPendingInstantiations);
3784 }
3785
3786 LocalInstantiationScope Local(*this);
3787
3788 // Enter the scope of this instantiation. We don't use
3789 // PushDeclContext because we don't have a scope.
3790 ContextRAII PreviousContext(*this, Var->getDeclContext());
3791 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3792 PreviousContext.pop();
3793
3794 // FIXME: Need to inform the ASTConsumer that we instantiated the
3795 // initializer?
3796
3797 // This variable may have local implicit instantiations that need to be
3798 // instantiated within this scope.
3799 PerformPendingInstantiations(/*LocalOnly=*/true);
3800
3801 Local.Exit();
3802
3803 if (Recursive) {
3804 // Define any newly required vtables.
3805 DefineUsedVTables();
3806
3807 // Instantiate any pending implicit instantiations found during the
3808 // instantiation of this template.
3809 PerformPendingInstantiations();
3810
3811 // Restore the set of pending vtables.
3812 assert(VTableUses.empty() &&
3813 "VTableUses should be empty before it is discarded.");
3814 VTableUses.swap(SavedVTableUses);
3815
3816 // Restore the set of pending implicit instantiations.
3817 assert(PendingInstantiations.empty() &&
3818 "PendingInstantiations should be empty before it is discarded.");
3819 PendingInstantiations.swap(SavedPendingInstantiations);
3820 }
3821 }
3822
3823 // Find actual definition
3824 Def = PatternDecl->getDefinition(getASTContext());
3825 } else {
3826 // If this is a static data member, find its out-of-line definition.
3827 assert(Var->isStaticDataMember() && "not a static data member?");
3828 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3829
3830 assert(PatternDecl && "data member was not instantiated from a template?");
3831 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3832 Def = PatternDecl->getOutOfLineDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003833 }
3834
Richard Smith8809a0c2013-09-27 20:14:12 +00003835 // If we don't have a definition of the variable template, we won't perform
3836 // any instantiation. Rather, we rely on the user to instantiate this
3837 // definition (or provide a specialization for it) in another translation
3838 // unit.
3839 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003840 if (DefinitionRequired) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003841 if (VarSpec)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003842 Diag(PointOfInstantiation,
Richard Smith8809a0c2013-09-27 20:14:12 +00003843 diag::err_explicit_instantiation_undefined_var_template) << Var;
3844 else
Larisse Voufo39a1e502013-08-06 01:03:05 +00003845 Diag(PointOfInstantiation,
3846 diag::err_explicit_instantiation_undefined_member)
Richard Smith8809a0c2013-09-27 20:14:12 +00003847 << 2 << Var->getDeclName() << Var->getDeclContext();
3848 Diag(PatternDecl->getLocation(),
3849 diag::note_explicit_instantiation_here);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003850 if (VarSpec)
3851 Var->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003852 } else if (Var->getTemplateSpecializationKind()
3853 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003854 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003855 std::make_pair(Var, PointOfInstantiation));
3856 }
3857
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003858 return;
3859 }
3860
Rafael Espindola189fa742012-03-05 10:54:55 +00003861 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3862
Douglas Gregor86d142a2009-10-08 07:24:58 +00003863 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00003864 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003865 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003866
Larisse Voufo39a1e502013-08-06 01:03:05 +00003867 // C++11 [temp.explicit]p10:
3868 // Except for inline functions, [...] explicit instantiation declarations
3869 // have the effect of suppressing the implicit instantiation of the entity
3870 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00003871 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003872 return;
Mike Stump11289f42009-09-09 15:08:12 +00003873
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003874 // Make sure to pass the instantiated variable to the consumer at the end.
3875 struct PassToConsumerRAII {
3876 ASTConsumer &Consumer;
3877 VarDecl *Var;
3878
3879 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3880 : Consumer(Consumer), Var(Var) { }
3881
3882 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00003883 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003884 }
3885 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003886
Richard Smith8809a0c2013-09-27 20:14:12 +00003887 // If we already have a definition, we're done.
3888 if (VarDecl *Def = Var->getDefinition()) {
3889 // We may be explicitly instantiating something we've already implicitly
3890 // instantiated.
3891 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3892 PointOfInstantiation);
3893 return;
Nick Lewyckya995a472012-04-04 02:38:36 +00003894 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00003895
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003896 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003897 if (Inst.isInvalid())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003898 return;
Mike Stump11289f42009-09-09 15:08:12 +00003899
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003900 // If we're performing recursive template instantiation, create our own
3901 // queue of pending implicit instantiations that we will instantiate later,
3902 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003903 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003904 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003905 SavePendingLocalImplicitInstantiationsRAII
3906 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003907 if (Recursive) {
3908 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003909 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003910 }
Mike Stump11289f42009-09-09 15:08:12 +00003911
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003912 // Enter the scope of this instantiation. We don't use
3913 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003914 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00003915 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00003916
Larisse Voufo39a1e502013-08-06 01:03:05 +00003917 VarDecl *OldVar = Var;
3918 if (!VarSpec)
3919 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00003920 TemplateArgs));
3921 else if (Var->isStaticDataMember() &&
3922 Var->getLexicalDeclContext()->isRecord()) {
3923 // We need to instantiate the definition of a static data member template,
3924 // and all we have is the in-class declaration of it. Instantiate a separate
3925 // declaration of the definition.
3926 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3927 TemplateArgs);
3928 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3929 VarSpec->getSpecializedTemplate(), Def, 0,
3930 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3931 if (Var) {
3932 llvm::PointerUnion<VarTemplateDecl *,
3933 VarTemplatePartialSpecializationDecl *> PatternPtr =
3934 VarSpec->getSpecializedTemplateOrPartial();
3935 if (VarTemplatePartialSpecializationDecl *Partial =
3936 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3937 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3938 Partial, &VarSpec->getTemplateInstantiationArgs());
3939
3940 // Merge the definition with the declaration.
3941 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3942 LookupOrdinaryName, ForRedeclaration);
3943 R.addDecl(OldVar);
3944 MergeVarDecl(Var, R);
3945
3946 // Attach the initializer.
3947 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3948 }
3949 } else
3950 // Complete the existing variable's definition with an appropriately
3951 // substituted type and initializer.
3952 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003953
3954 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003955
3956 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003957 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00003958 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3959 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003960 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003961
3962 // This variable may have local implicit instantiations that need to be
3963 // instantiated within this scope.
3964 PerformPendingInstantiations(/*LocalOnly=*/true);
3965
Douglas Gregora86bc002012-02-16 21:36:18 +00003966 Local.Exit();
3967
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003968 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003969 // Define any newly required vtables.
3970 DefineUsedVTables();
3971
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003972 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003973 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003974 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003975
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003976 // Restore the set of pending vtables.
3977 assert(VTableUses.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003978 "VTableUses should be empty before it is discarded.");
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003979 VTableUses.swap(SavedVTableUses);
3980
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003981 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003982 assert(PendingInstantiations.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003983 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003984 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00003985 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003986}
Douglas Gregor51783312009-05-27 05:35:12 +00003987
Anders Carlsson70553942009-08-29 05:16:22 +00003988void
3989Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3990 const CXXConstructorDecl *Tmpl,
3991 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003992
Richard Trieu9becef62011-09-09 03:18:59 +00003993 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00003994 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003995
Anders Carlsson70553942009-08-29 05:16:22 +00003996 // Instantiate all the initializers.
3997 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregora3a3f6f2009-09-01 21:04:42 +00003998 InitsEnd = Tmpl->init_end();
3999 Inits != InitsEnd; ++Inits) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004000 CXXCtorInitializer *Init = *Inits;
Anders Carlsson70553942009-08-29 05:16:22 +00004001
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004002 // Only instantiate written initializers, let Sema re-construct implicit
4003 // ones.
4004 if (!Init->isWritten())
4005 continue;
4006
Douglas Gregor44e7df62011-01-04 00:32:56 +00004007 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004008
Douglas Gregor44e7df62011-01-04 00:32:56 +00004009 if (Init->isPackExpansion()) {
4010 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004011 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004012 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004013 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004014 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004015 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004016 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004017 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004018 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004019 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004020 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004021 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004022 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004023 NumExpansions)) {
4024 AnyErrors = true;
4025 New->setInvalidDecl();
4026 continue;
4027 }
4028 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004029
4030 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004031 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004032 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4033
4034 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004035 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4036 /*CXXDirectInit=*/true);
4037 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004038 AnyErrors = true;
4039 break;
4040 }
4041
4042 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004043 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004044 TemplateArgs,
4045 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004046 New->getDeclName());
4047 if (!BaseTInfo) {
4048 AnyErrors = true;
4049 break;
4050 }
4051
4052 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004053 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redla9351792012-02-11 23:51:47 +00004054 BaseTInfo, TempInit.take(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004055 New->getParent(),
4056 SourceLocation());
4057 if (NewInit.isInvalid()) {
4058 AnyErrors = true;
4059 break;
4060 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004061
Douglas Gregor44e7df62011-01-04 00:32:56 +00004062 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004063 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004064
Douglas Gregor44e7df62011-01-04 00:32:56 +00004065 continue;
4066 }
4067
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004068 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004069 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4070 /*CXXDirectInit=*/true);
4071 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004072 AnyErrors = true;
4073 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004074 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004075
Anders Carlsson70553942009-08-29 05:16:22 +00004076 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004077 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4078 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4079 TemplateArgs,
4080 Init->getSourceLocation(),
4081 New->getDeclName());
4082 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004083 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004084 New->setInvalidDecl();
4085 continue;
4086 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004087
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004088 if (Init->isBaseInitializer())
Sebastian Redla9351792012-02-11 23:51:47 +00004089 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004090 New->getParent(), EllipsisLoc);
4091 else
Sebastian Redla9351792012-02-11 23:51:47 +00004092 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004093 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004094 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004095 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004096 Init->getMemberLocation(),
4097 Init->getMember(),
4098 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004099 if (!Member) {
4100 AnyErrors = true;
4101 New->setInvalidDecl();
4102 continue;
4103 }
Mike Stump11289f42009-09-09 15:08:12 +00004104
Sebastian Redla9351792012-02-11 23:51:47 +00004105 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004106 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004107 } else if (Init->isIndirectMemberInitializer()) {
4108 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004109 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004110 Init->getMemberLocation(),
4111 Init->getIndirectMember(), TemplateArgs));
4112
Douglas Gregor55e6b312011-03-04 19:46:35 +00004113 if (!IndirectMember) {
4114 AnyErrors = true;
4115 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004116 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004117 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004118
Sebastian Redla9351792012-02-11 23:51:47 +00004119 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004120 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004121 }
4122
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004123 if (NewInit.isInvalid()) {
4124 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004125 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004126 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004127 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004128 }
4129 }
Mike Stump11289f42009-09-09 15:08:12 +00004130
Anders Carlsson70553942009-08-29 05:16:22 +00004131 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004132 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004133 /*FIXME: ColonLoc */
4134 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004135 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004136 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004137}
4138
John McCall59660882009-08-29 08:11:13 +00004139// TODO: this could be templated if the various decl types used the
4140// same method name.
4141static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4142 ClassTemplateDecl *Instance) {
4143 Pattern = Pattern->getCanonicalDecl();
4144
4145 do {
4146 Instance = Instance->getCanonicalDecl();
4147 if (Pattern == Instance) return true;
4148 Instance = Instance->getInstantiatedFromMemberTemplate();
4149 } while (Instance);
4150
4151 return false;
4152}
4153
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004154static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4155 FunctionTemplateDecl *Instance) {
4156 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004157
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004158 do {
4159 Instance = Instance->getCanonicalDecl();
4160 if (Pattern == Instance) return true;
4161 Instance = Instance->getInstantiatedFromMemberTemplate();
4162 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004163
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004164 return false;
4165}
4166
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004167static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004168isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4169 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004170 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004171 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4172 do {
4173 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4174 Instance->getCanonicalDecl());
4175 if (Pattern == Instance)
4176 return true;
4177 Instance = Instance->getInstantiatedFromMember();
4178 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004179
Douglas Gregor21610382009-10-29 00:04:11 +00004180 return false;
4181}
4182
John McCall59660882009-08-29 08:11:13 +00004183static bool isInstantiationOf(CXXRecordDecl *Pattern,
4184 CXXRecordDecl *Instance) {
4185 Pattern = Pattern->getCanonicalDecl();
4186
4187 do {
4188 Instance = Instance->getCanonicalDecl();
4189 if (Pattern == Instance) return true;
4190 Instance = Instance->getInstantiatedFromMemberClass();
4191 } while (Instance);
4192
4193 return false;
4194}
4195
4196static bool isInstantiationOf(FunctionDecl *Pattern,
4197 FunctionDecl *Instance) {
4198 Pattern = Pattern->getCanonicalDecl();
4199
4200 do {
4201 Instance = Instance->getCanonicalDecl();
4202 if (Pattern == Instance) return true;
4203 Instance = Instance->getInstantiatedFromMemberFunction();
4204 } while (Instance);
4205
4206 return false;
4207}
4208
4209static bool isInstantiationOf(EnumDecl *Pattern,
4210 EnumDecl *Instance) {
4211 Pattern = Pattern->getCanonicalDecl();
4212
4213 do {
4214 Instance = Instance->getCanonicalDecl();
4215 if (Pattern == Instance) return true;
4216 Instance = Instance->getInstantiatedFromMemberEnum();
4217 } while (Instance);
4218
4219 return false;
4220}
4221
John McCallb96ec562009-12-04 22:46:56 +00004222static bool isInstantiationOf(UsingShadowDecl *Pattern,
4223 UsingShadowDecl *Instance,
4224 ASTContext &C) {
4225 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4226}
4227
4228static bool isInstantiationOf(UsingDecl *Pattern,
4229 UsingDecl *Instance,
4230 ASTContext &C) {
4231 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4232}
4233
John McCalle61f2ba2009-11-18 02:36:19 +00004234static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4235 UsingDecl *Instance,
4236 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004237 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCalle61f2ba2009-11-18 02:36:19 +00004238}
4239
4240static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004241 UsingDecl *Instance,
4242 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004243 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004244}
4245
John McCall59660882009-08-29 08:11:13 +00004246static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4247 VarDecl *Instance) {
4248 assert(Instance->isStaticDataMember());
4249
4250 Pattern = Pattern->getCanonicalDecl();
4251
4252 do {
4253 Instance = Instance->getCanonicalDecl();
4254 if (Pattern == Instance) return true;
4255 Instance = Instance->getInstantiatedFromStaticDataMember();
4256 } while (Instance);
4257
4258 return false;
4259}
4260
John McCallb96ec562009-12-04 22:46:56 +00004261// Other is the prospective instantiation
4262// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004263static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004264 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004265 if (UnresolvedUsingTypenameDecl *UUD
4266 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4267 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4268 return isInstantiationOf(UUD, UD, Ctx);
4269 }
4270 }
4271
4272 if (UnresolvedUsingValueDecl *UUD
4273 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004274 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4275 return isInstantiationOf(UUD, UD, Ctx);
4276 }
4277 }
Douglas Gregor51783312009-05-27 05:35:12 +00004278
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004279 return false;
4280 }
Mike Stump11289f42009-09-09 15:08:12 +00004281
John McCall59660882009-08-29 08:11:13 +00004282 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4283 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004284
John McCall59660882009-08-29 08:11:13 +00004285 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4286 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004287
John McCall59660882009-08-29 08:11:13 +00004288 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4289 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004290
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004291 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004292 if (Var->isStaticDataMember())
4293 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4294
4295 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4296 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004297
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004298 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4299 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4300
Douglas Gregor21610382009-10-29 00:04:11 +00004301 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4302 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4303 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4304 PartialSpec);
4305
Anders Carlsson5da84842009-09-01 04:26:58 +00004306 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4307 if (!Field->getDeclName()) {
4308 // This is an unnamed field.
Mike Stump11289f42009-09-09 15:08:12 +00004309 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlsson5da84842009-09-01 04:26:58 +00004310 cast<FieldDecl>(D);
4311 }
4312 }
Mike Stump11289f42009-09-09 15:08:12 +00004313
John McCallb96ec562009-12-04 22:46:56 +00004314 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4315 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4316
4317 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4318 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4319
Douglas Gregor51783312009-05-27 05:35:12 +00004320 return D->getDeclName() && isa<NamedDecl>(Other) &&
4321 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4322}
4323
4324template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004325static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004326 NamedDecl *D,
4327 ForwardIterator first,
4328 ForwardIterator last) {
4329 for (; first != last; ++first)
4330 if (isInstantiationOf(Ctx, D, *first))
4331 return cast<NamedDecl>(*first);
4332
4333 return 0;
4334}
4335
John McCallaa74a0c2009-08-28 07:59:38 +00004336/// \brief Finds the instantiation of the given declaration context
4337/// within the current instantiation.
4338///
4339/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004340DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004341 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004342 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004343 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00004344 return cast_or_null<DeclContext>(ID);
4345 } else return DC;
4346}
4347
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004348/// \brief Find the instantiation of the given declaration within the
4349/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004350///
4351/// This routine is intended to be used when \p D is a declaration
4352/// referenced from within a template, that needs to mapped into the
4353/// corresponding declaration within an instantiation. For example,
4354/// given:
4355///
4356/// \code
4357/// template<typename T>
4358/// struct X {
4359/// enum Kind {
4360/// KnownValue = sizeof(T)
4361/// };
4362///
4363/// bool getKind() const { return KnownValue; }
4364/// };
4365///
4366/// template struct X<int>;
4367/// \endcode
4368///
Serge Pavloved5fe902013-07-10 04:59:14 +00004369/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4370/// \p EnumConstantDecl for \p KnownValue (which refers to
4371/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4372/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4373/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004374NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00004375 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00004376 DeclContext *ParentDC = D->getDeclContext();
Faisal Vali2cba1332013-10-23 06:44:28 +00004377 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4378 // parameters (p below) can have their ParentDC set to the translation-unit
4379 // - thus we can not consistently check if the ParentDC of such a parameter
4380 // is Dependent or/and a FunctionOrMethod.
4381 // For e.g. this code, during Template argument deduction tries to
4382 // find an instantiated decl for (T y) when the ParentDC for y is
4383 // the translation unit.
4384 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00004385 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00004386 // Foo(baz);
4387 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4388 // it gets here, always has a FunctionOrMethod as its ParentDC??
4389 // For now:
4390 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4391 // whose type is not instantiation dependent, do nothing to the decl
4392 // - otherwise find its instantiated decl.
4393 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4394 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4395 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00004396 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00004397 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00004398 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4399 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004400 // D is a local of some kind. Look into the map of local
4401 // declarations to their instantiations.
Chris Lattner50c3c132011-02-17 19:47:42 +00004402 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4403 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4404 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004405
Chris Lattnercab02a62011-02-17 20:34:02 +00004406 if (Found) {
4407 if (Decl *FD = Found->dyn_cast<Decl *>())
4408 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004409
Richard Smithb15fe3a2012-09-12 00:56:43 +00004410 int PackIdx = ArgumentPackSubstitutionIndex;
4411 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattnercab02a62011-02-17 20:34:02 +00004412 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4413 }
4414
Serge Pavlov7cd8f602013-07-15 06:14:07 +00004415 // If we're performing a partial substitution during template argument
4416 // deduction, we may not have values for template parameters yet. They
4417 // just map to themselves.
4418 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4419 isa<TemplateTemplateParmDecl>(D))
4420 return D;
4421
Serge Pavlov074a5182013-08-10 12:00:21 +00004422 if (D->isInvalidDecl())
4423 return 0;
4424
Chris Lattnercab02a62011-02-17 20:34:02 +00004425 // If we didn't find the decl, then we must have a label decl that hasn't
4426 // been found yet. Lazily instantiate it and return it now.
4427 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004428
Chris Lattnercab02a62011-02-17 20:34:02 +00004429 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4430 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004431
Chris Lattnercab02a62011-02-17 20:34:02 +00004432 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4433 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004434 }
Douglas Gregor51783312009-05-27 05:35:12 +00004435
Larisse Voufo39a1e502013-08-06 01:03:05 +00004436 // For variable template specializations, update those that are still
4437 // type-dependent.
4438 if (VarTemplateSpecializationDecl *VarSpec =
4439 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4440 bool InstantiationDependent = false;
4441 const TemplateArgumentListInfo &VarTemplateArgs =
4442 VarSpec->getTemplateArgsInfo();
4443 if (TemplateSpecializationType::anyDependentTemplateArguments(
4444 VarTemplateArgs, InstantiationDependent))
4445 D = cast<NamedDecl>(
4446 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4447 return D;
4448 }
4449
Douglas Gregor64621e62009-09-16 18:34:49 +00004450 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4451 if (!Record->isDependentContext())
4452 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004453
Douglas Gregor4109afa2011-11-07 17:43:18 +00004454 // Determine whether this record is the "templated" declaration describing
4455 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00004456 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00004457 if (ClassTemplate)
4458 ClassTemplate = ClassTemplate->getCanonicalDecl();
4459 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4460 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4461 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004462
Douglas Gregor4109afa2011-11-07 17:43:18 +00004463 // Walk the current context to find either the record or an instantiation of
4464 // it.
4465 DeclContext *DC = CurContext;
4466 while (!DC->isFileContext()) {
4467 // If we're performing substitution while we're inside the template
4468 // definition, we'll find our own context. We're done.
4469 if (DC->Equals(Record))
4470 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004471
Douglas Gregor4109afa2011-11-07 17:43:18 +00004472 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4473 // Check whether we're in the process of instantiating a class template
4474 // specialization of the template we're mapping.
4475 if (ClassTemplateSpecializationDecl *InstSpec
4476 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4477 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4478 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4479 return InstRecord;
4480 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004481
Douglas Gregor4109afa2011-11-07 17:43:18 +00004482 // Check whether we're in the process of instantiating a member class.
4483 if (isInstantiationOf(Record, InstRecord))
4484 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00004485 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004486
Douglas Gregor4109afa2011-11-07 17:43:18 +00004487 // Move to the outer template scope.
4488 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4489 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4490 DC = FD->getLexicalDeclContext();
4491 continue;
4492 }
John McCall59660882009-08-29 08:11:13 +00004493 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004494
Douglas Gregor4109afa2011-11-07 17:43:18 +00004495 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00004496 }
Douglas Gregord225fa02010-02-05 22:40:03 +00004497
Douglas Gregor64621e62009-09-16 18:34:49 +00004498 // Fall through to deal with other dependent record types (e.g.,
4499 // anonymous unions in class templates).
4500 }
John McCall59660882009-08-29 08:11:13 +00004501
Douglas Gregor64621e62009-09-16 18:34:49 +00004502 if (!ParentDC->isDependentContext())
4503 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004504
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004505 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004506 if (!ParentDC)
Douglas Gregor2ffd9652009-09-01 17:53:10 +00004507 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004508
Douglas Gregor51783312009-05-27 05:35:12 +00004509 if (ParentDC != D->getDeclContext()) {
4510 // We performed some kind of instantiation in the parent context,
4511 // so now we need to look into the instantiated parent context to
4512 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004513
John McCalle78aac42010-03-10 03:28:59 +00004514 // If our context used to be dependent, we may need to instantiate
4515 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00004516 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00004517 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004518 if (!Spec->isDependentContext()) {
4519 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00004520 const RecordType *Tag = T->getAs<RecordType>();
4521 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00004522 if (Tag->isBeingDefined())
4523 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00004524 if (!Tag->isBeingDefined() &&
4525 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4526 return 0;
Douglas Gregor25edf432010-11-05 23:22:45 +00004527
4528 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004529 }
4530 }
4531
Douglas Gregor51783312009-05-27 05:35:12 +00004532 NamedDecl *Result = 0;
4533 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004534 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00004535 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00004536 } else {
4537 // Since we don't have a name for the entity we're looking for,
4538 // our only option is to walk through all of the declarations to
4539 // find that name. This will occur in a few cases:
4540 //
4541 // - anonymous struct/union within a template
4542 // - unnamed class/struct/union/enum within a template
4543 //
4544 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00004545 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004546 ParentDC->decls_begin(),
4547 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00004548 }
Mike Stump11289f42009-09-09 15:08:12 +00004549
Douglas Gregor528ad932011-03-06 20:12:45 +00004550 if (!Result) {
4551 if (isa<UsingShadowDecl>(D)) {
4552 // UsingShadowDecls can instantiate to nothing because of using hiding.
4553 } else if (Diags.hasErrorOccurred()) {
4554 // We've already complained about something, so most likely this
4555 // declaration failed to instantiate. There's no point in complaining
4556 // further, since this is normal in invalid code.
4557 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004558 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00004559 // instantiated, and we haven't gotten around to instantiating this
4560 // member yet. This can happen when the code uses forward declarations
4561 // of member classes, and introduces ordering dependencies via
4562 // template instantiation.
4563 Diag(Loc, diag::err_member_not_yet_instantiated)
4564 << D->getDeclName()
4565 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4566 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00004567 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4568 // This enumeration constant was found when the template was defined,
4569 // but can't be found in the instantiation. This can happen if an
4570 // unscoped enumeration member is explicitly specialized.
4571 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4572 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4573 TemplateArgs));
4574 assert(Spec->getTemplateSpecializationKind() ==
4575 TSK_ExplicitSpecialization);
4576 Diag(Loc, diag::err_enumerator_does_not_exist)
4577 << D->getDeclName()
4578 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4579 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4580 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00004581 } else {
4582 // We should have found something, but didn't.
4583 llvm_unreachable("Unable to find instantiation of declaration!");
4584 }
4585 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004586
Douglas Gregor51783312009-05-27 05:35:12 +00004587 D = Result;
4588 }
4589
Douglas Gregor51783312009-05-27 05:35:12 +00004590 return D;
4591}
Douglas Gregor77b50e12009-06-22 23:06:13 +00004592
Mike Stump11289f42009-09-09 15:08:12 +00004593/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00004594/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00004595void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregore39f97c2011-07-28 19:49:54 +00004596 // Load pending instantiations from the external source.
4597 if (!LocalOnly && ExternalSource) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00004598 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregore39f97c2011-07-28 19:49:54 +00004599 ExternalSource->ReadPendingInstantiations(Pending);
4600 PendingInstantiations.insert(PendingInstantiations.begin(),
4601 Pending.begin(), Pending.end());
4602 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004603
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004604 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00004605 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004606 PendingImplicitInstantiation Inst;
4607
4608 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00004609 Inst = PendingInstantiations.front();
4610 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004611 } else {
4612 Inst = PendingLocalImplicitInstantiations.front();
4613 PendingLocalImplicitInstantiations.pop_front();
4614 }
Mike Stump11289f42009-09-09 15:08:12 +00004615
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004616 // Instantiate function definitions
4617 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallfaf5fb42010-08-26 23:41:50 +00004618 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4619 "instantiating function definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004620 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4621 TSK_ExplicitInstantiationDefinition;
4622 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4623 DefinitionRequired);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004624 continue;
4625 }
Mike Stump11289f42009-09-09 15:08:12 +00004626
Larisse Voufo39a1e502013-08-06 01:03:05 +00004627 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004628 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004629
4630 assert((Var->isStaticDataMember() ||
4631 isa<VarTemplateSpecializationDecl>(Var)) &&
4632 "Not a static data member, nor a variable template"
4633 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00004634
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004635 // Don't try to instantiate declarations if the most recent redeclaration
4636 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004637 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004638 continue;
4639
4640 // Check if the most recent declaration has changed the specialization kind
4641 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004642 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004643 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00004644 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004645 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004646 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004647 continue; // No longer need to instantiate this type.
4648 case TSK_ExplicitInstantiationDefinition:
4649 // We only need an instantiation if the pending instantiation *is* the
4650 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004651 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004652 case TSK_ImplicitInstantiation:
4653 break;
4654 }
4655
Larisse Voufo39a1e502013-08-06 01:03:05 +00004656 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4657 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004658 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4659 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004660
4661 // Instantiate static data member definitions or variable template
4662 // specializations.
4663 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4664 DefinitionRequired);
Douglas Gregor77b50e12009-06-22 23:06:13 +00004665 }
4666}
John McCallc62bb642010-03-24 05:22:00 +00004667
4668void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4669 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00004670 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00004671 switch (DD->getKind()) {
4672 case DependentDiagnostic::Access:
4673 HandleDependentAccessCheck(*DD, TemplateArgs);
4674 break;
4675 }
4676 }
4677}