blob: 136bb5aa4f827f1bb4fc9578754d72b934c17d5d [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
John McCall6602bb12010-08-01 02:01:53 +0000132void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000133 const Decl *Tmpl, Decl *New,
134 LateInstantiatedAttrVec *LateAttrs,
135 LocalInstantiationScope *OuterMostScope) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000136 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
137 i != e; ++i) {
138 const Attr *TmplAttr = *i;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000139
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000140 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000141 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
142 if (Aligned && Aligned->isAlignmentDependent()) {
143 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
144 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000145 }
146
Richard Smith44c247f2013-02-22 08:32:16 +0000147 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000148 if (TmplAttr->isLateParsed() && LateAttrs) {
149 // Late parsed attributes must be instantiated and attached after the
150 // enclosing class has been instantiated. See Sema::InstantiateClass.
151 LocalInstantiationScope *Saved = 0;
152 if (CurrentInstantiationScope)
153 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
154 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
155 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000156 // Allow 'this' within late-parsed attributes.
157 NamedDecl *ND = dyn_cast<NamedDecl>(New);
158 CXXRecordDecl *ThisContext =
159 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
160 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
161 ND && ND->isCXXInstanceMember());
162
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000163 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
164 *this, TemplateArgs);
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000165 if (NewAttr)
166 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000167 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000168 }
169}
170
Douglas Gregor8a655532009-03-25 15:45:12 +0000171Decl *
172TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000173 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000174}
175
176Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000177TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
178 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
179 D->getIdentifier());
180 Owner->addDecl(Inst);
181 return Inst;
182}
183
184Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000185TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000186 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000187}
188
John McCalld8d0d432010-02-16 06:53:13 +0000189Decl *
190TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
191 NamespaceAliasDecl *Inst
192 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
193 D->getNamespaceLoc(),
194 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000195 D->getIdentifier(),
196 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000197 D->getTargetNameLoc(),
198 D->getNamespace());
199 Owner->addDecl(Inst);
200 return Inst;
201}
202
Richard Smith3f1b5d02011-05-05 21:57:07 +0000203Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
204 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000205 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000206 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000207 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000208 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000209 DI = SemaRef.SubstType(DI, TemplateArgs,
210 D->getLocation(), D->getDeclName());
211 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000212 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000213 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000214 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000215 } else {
216 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000217 }
Mike Stump11289f42009-09-09 15:08:12 +0000218
Richard Smith2ddcbab2012-10-23 00:32:41 +0000219 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
220 // libstdc++ relies upon this bug in its implementation of common_type.
221 // If we happen to be processing that implementation, fake up the g++ ?:
222 // semantics. See LWG issue 2141 for more information on the bug.
223 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
224 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
225 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
226 DT->isReferenceType() &&
227 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
228 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
229 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
230 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
231 // Fold it to the (non-reference) type which g++ would have produced.
232 DI = SemaRef.Context.getTrivialTypeSourceInfo(
233 DI->getType().getNonReferenceType());
234
Douglas Gregord7e7a512009-03-17 21:15:40 +0000235 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000236 TypedefNameDecl *Typedef;
237 if (IsTypeAlias)
238 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
239 D->getLocation(), D->getIdentifier(), DI);
240 else
241 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
242 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000243 if (Invalid)
244 Typedef->setInvalidDecl();
245
John McCall04fcd0d2011-02-01 08:20:08 +0000246 // If the old typedef was the name for linkage purposes of an anonymous
247 // tag decl, re-establish that relationship for the new typedef.
248 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
249 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000250 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000251 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000252 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000253 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000254 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000255 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000256
Douglas Gregorec9fd132012-01-14 16:38:05 +0000257 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000258 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
259 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000260 if (!InstPrev)
261 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000262
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000263 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
264
265 // If the typedef types are not identical, reject them.
266 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
267
Rafael Espindola8db352d2013-10-17 15:37:26 +0000268 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000269 }
270
John McCall6602bb12010-08-01 02:01:53 +0000271 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000272
John McCall401982f2010-01-20 21:53:11 +0000273 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000274
Douglas Gregord7e7a512009-03-17 21:15:40 +0000275 return Typedef;
276}
277
Richard Smithdda56e42011-04-15 14:24:37 +0000278Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000279 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
280 Owner->addDecl(Typedef);
281 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000282}
283
284Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000285 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
286 Owner->addDecl(Typedef);
287 return Typedef;
288}
289
290Decl *
291TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
292 // Create a local instantiation scope for this type alias template, which
293 // will contain the instantiations of the template parameters.
294 LocalInstantiationScope Scope(SemaRef);
295
296 TemplateParameterList *TempParams = D->getTemplateParameters();
297 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
298 if (!InstParams)
299 return 0;
300
301 TypeAliasDecl *Pattern = D->getTemplatedDecl();
302
303 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000304 if (Pattern->getPreviousDecl()) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000305 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000306 if (!Found.empty()) {
307 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000308 }
309 }
310
311 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
312 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
313 if (!AliasInst)
314 return 0;
315
316 TypeAliasTemplateDecl *Inst
317 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
318 D->getDeclName(), InstParams, AliasInst);
319 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000320 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000321
322 Inst->setAccess(D->getAccess());
323
324 if (!PrevAliasTemplate)
325 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000326
Richard Smith3f1b5d02011-05-05 21:57:07 +0000327 Owner->addDecl(Inst);
328
329 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000330}
331
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000332Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000333 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000334}
335
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000336Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
337 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000338
Douglas Gregor04163182010-05-21 00:31:19 +0000339 // If this is the variable for an anonymous struct or union,
340 // instantiate the anonymous struct/union type first.
341 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
342 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
343 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
344 return 0;
345
John McCall76d824f2009-08-25 22:02:44 +0000346 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000347 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000348 TemplateArgs,
349 D->getTypeSpecStartLoc(),
350 D->getDeclName());
351 if (!DI)
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000352 return 0;
353
Douglas Gregor61623342010-09-12 07:37:24 +0000354 if (DI->getType()->isFunctionType()) {
355 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
356 << D->isStaticDataMember() << DI->getType();
357 return 0;
358 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000359
Richard Smith541b38b2013-09-20 01:15:31 +0000360 DeclContext *DC = Owner;
361 if (D->isLocalExternDecl())
362 SemaRef.adjustContextForLocalExternDecl(DC);
363
Larisse Voufo39a1e502013-08-06 01:03:05 +0000364 // Build the instantiated declaration.
Richard Smith541b38b2013-09-20 01:15:31 +0000365 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000366 D->getLocation(), D->getIdentifier(),
Larisse Voufo39a1e502013-08-06 01:03:05 +0000367 DI->getType(), DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000368
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000369 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000370 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000371 SemaRef.inferObjCARCLifetime(Var))
372 Var->setInvalidDecl();
373
Larisse Voufo39a1e502013-08-06 01:03:05 +0000374 // Substitute the nested name specifier, if any.
375 if (SubstQualifier(D, Var))
376 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000377
Richard Smith541b38b2013-09-20 01:15:31 +0000378 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000379 StartingScope, InstantiatingVarTemplate);
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000380 return Var;
381}
382
Abramo Bagnarad7340582010-06-05 05:09:32 +0000383Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
384 AccessSpecDecl* AD
385 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
386 D->getAccessSpecifierLoc(), D->getColonLoc());
387 Owner->addHiddenDecl(AD);
388 return AD;
389}
390
Douglas Gregord7e7a512009-03-17 21:15:40 +0000391Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
392 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000393 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000394 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000395 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000396 DI = SemaRef.SubstType(DI, TemplateArgs,
397 D->getLocation(), D->getDeclName());
398 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000399 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000400 Invalid = true;
401 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000402 // C++ [temp.arg.type]p3:
403 // If a declaration acquires a function type through a type
404 // dependent on a template-parameter and this causes a
405 // declaration that does not use the syntactic form of a
406 // function declarator to have function type, the program is
407 // ill-formed.
408 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000409 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000410 Invalid = true;
411 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000412 } else {
413 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000414 }
415
416 Expr *BitWidth = D->getBitWidth();
417 if (Invalid)
418 BitWidth = 0;
419 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000420 // The bit-width expression is a constant expression.
421 EnterExpressionEvaluationContext Unevaluated(SemaRef,
422 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000423
John McCalldadc5752010-08-24 06:29:42 +0000424 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000425 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000426 if (InstantiatedBitWidth.isInvalid()) {
427 Invalid = true;
428 BitWidth = 0;
429 } else
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000430 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000431 }
432
John McCall90459c52009-10-22 23:33:21 +0000433 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
434 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000435 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000436 D->getLocation(),
437 D->isMutable(),
438 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000439 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000440 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000441 D->getAccess(),
442 0);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000443 if (!Field) {
444 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000445 return 0;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000446 }
Mike Stump11289f42009-09-09 15:08:12 +0000447
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000448 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000449
Richard Smith848e1f12013-02-01 08:12:08 +0000450 if (Field->hasAttrs())
451 SemaRef.CheckAlignasUnderalignment(Field);
452
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000453 if (Invalid)
454 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000455
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000456 if (!Field->getDeclName()) {
457 // Keep track of where this decl came from.
458 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000459 }
Douglas Gregor04163182010-05-21 00:31:19 +0000460 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
461 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000462 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000463 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000464 }
Mike Stump11289f42009-09-09 15:08:12 +0000465
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000466 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000467 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000468 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000469
470 return Field;
471}
472
John McCall5e77d762013-04-16 07:28:30 +0000473Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
474 bool Invalid = false;
475 TypeSourceInfo *DI = D->getTypeSourceInfo();
476
477 if (DI->getType()->isVariablyModifiedType()) {
478 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
479 << D->getName();
480 Invalid = true;
481 } else if (DI->getType()->isInstantiationDependentType()) {
482 DI = SemaRef.SubstType(DI, TemplateArgs,
483 D->getLocation(), D->getDeclName());
484 if (!DI) {
485 DI = D->getTypeSourceInfo();
486 Invalid = true;
487 } else if (DI->getType()->isFunctionType()) {
488 // C++ [temp.arg.type]p3:
489 // If a declaration acquires a function type through a type
490 // dependent on a template-parameter and this causes a
491 // declaration that does not use the syntactic form of a
492 // function declarator to have function type, the program is
493 // ill-formed.
494 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
495 << DI->getType();
496 Invalid = true;
497 }
498 } else {
499 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
500 }
501
Richard Smithf7981722013-11-22 09:01:48 +0000502 MSPropertyDecl *Property = MSPropertyDecl::Create(
503 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
504 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000505
506 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
507 StartingScope);
508
509 if (Invalid)
510 Property->setInvalidDecl();
511
512 Property->setAccess(D->getAccess());
513 Owner->addDecl(Property);
514
515 return Property;
516}
517
Francois Pichet783dd6e2010-11-21 06:08:52 +0000518Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
519 NamedDecl **NamedChain =
520 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
521
522 int i = 0;
523 for (IndirectFieldDecl::chain_iterator PI =
524 D->chain_begin(), PE = D->chain_end();
Douglas Gregor55e6b312011-03-04 19:46:35 +0000525 PI != PE; ++PI) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000526 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000527 TemplateArgs);
528 if (!Next)
529 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000530
Douglas Gregor55e6b312011-03-04 19:46:35 +0000531 NamedChain[i++] = Next;
532 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000533
Francois Pichetdbafc192010-12-09 10:07:54 +0000534 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet783dd6e2010-11-21 06:08:52 +0000535 IndirectFieldDecl* IndirectField
536 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichetdbafc192010-12-09 10:07:54 +0000537 D->getIdentifier(), T,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000538 NamedChain, D->getChainingSize());
539
540
541 IndirectField->setImplicit(D->isImplicit());
542 IndirectField->setAccess(D->getAccess());
543 Owner->addDecl(IndirectField);
544 return IndirectField;
545}
546
John McCallaa74a0c2009-08-28 07:59:38 +0000547Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000548 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000549 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000550 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000551 TypeSourceInfo *InstTy;
552 // If this is an unsupported friend, don't bother substituting template
553 // arguments into it. The actual type referred to won't be used by any
554 // parts of Clang, and may not be valid for instantiating. Just use the
555 // same info for the instantiated friend.
556 if (D->isUnsupportedFriend()) {
557 InstTy = Ty;
558 } else {
559 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
560 D->getLocation(), DeclarationName());
561 }
562 if (!InstTy)
Douglas Gregor33636e62009-12-24 20:56:24 +0000563 return 0;
John McCallaa74a0c2009-08-28 07:59:38 +0000564
Richard Smitha31a89a2012-09-20 01:31:00 +0000565 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000566 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000567 if (!FD)
568 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000569
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000570 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000571 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000572 Owner->addDecl(FD);
573 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000574 }
575
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000576 NamedDecl *ND = D->getFriendDecl();
577 assert(ND && "friend decl must be a decl or a type!");
578
John McCallb9c78482010-04-08 09:05:18 +0000579 // All of the Visit implementations for the various potential friend
580 // declarations have to be carefully written to work for friend
581 // objects, with the most important detail being that the target
582 // decl should almost certainly not be placed in Owner.
583 Decl *NewND = Visit(ND);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000584 if (!NewND) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000585
John McCallaa74a0c2009-08-28 07:59:38 +0000586 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000587 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000588 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000589 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000590 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000591 Owner->addDecl(FD);
592 return FD;
John McCall58de3582009-08-14 02:03:10 +0000593}
594
Douglas Gregord7e7a512009-03-17 21:15:40 +0000595Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
596 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000597
Richard Smith764d2fe2011-12-20 02:08:33 +0000598 // The expression in a static assertion is a constant expression.
599 EnterExpressionEvaluationContext Unevaluated(SemaRef,
600 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000601
John McCalldadc5752010-08-24 06:29:42 +0000602 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000603 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000604 if (InstantiatedAssertExpr.isInvalid())
605 return 0;
606
Richard Smithded9c2e2012-07-11 22:37:56 +0000607 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000608 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000609 D->getMessage(),
610 D->getRParenLoc(),
611 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000612}
613
614Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith2e6610a2012-03-26 04:58:10 +0000615 EnumDecl *PrevDecl = 0;
616 if (D->getPreviousDecl()) {
617 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
618 D->getPreviousDecl(),
619 TemplateArgs);
620 if (!Prev) return 0;
621 PrevDecl = cast<EnumDecl>(Prev);
622 }
623
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000624 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000625 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000626 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000627 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000628 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000629 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000630 // If we have type source information for the underlying type, it means it
631 // has been explicitly set by the user. Perform substitution on it before
632 // moving on.
633 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000634 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
635 DeclarationName());
636 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000637 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000638 else
639 Enum->setIntegerTypeSourceInfo(NewTI);
640 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000641 assert(!D->getIntegerType()->isDependentType()
642 && "Dependent type without type source info");
643 Enum->setIntegerType(D->getIntegerType());
644 }
645 }
646
John McCall811a0f52010-10-22 23:36:17 +0000647 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
648
Richard Smith4b38ded2012-03-14 23:13:10 +0000649 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000650 Enum->setAccess(D->getAccess());
John McCall3e11ebe2010-03-15 10:12:16 +0000651 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000652 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +0000653
Richard Smith258a7442012-03-26 04:08:46 +0000654 EnumDecl *Def = D->getDefinition();
655 if (Def && Def != D) {
656 // If this is an out-of-line definition of an enum member template, check
657 // that the underlying types match in the instantiation of both
658 // declarations.
659 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
660 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
661 QualType DefnUnderlying =
662 SemaRef.SubstType(TI->getType(), TemplateArgs,
663 UnderlyingLoc, DeclarationName());
664 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
665 DefnUnderlying, Enum);
666 }
667 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000668
Richard Smith4b38ded2012-03-14 23:13:10 +0000669 // C++11 [temp.inst]p1: The implicit instantiation of a class template
670 // specialization causes the implicit instantiation of the declarations, but
671 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +0000672 //
673 // DR1484 clarifies that enumeration definitions inside of a template
674 // declaration aren't considered entities that can be separately instantiated
675 // from the rest of the entity they are declared inside of.
676 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
677 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +0000678 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +0000679 }
Richard Smith4b38ded2012-03-14 23:13:10 +0000680
681 return Enum;
682}
683
684void TemplateDeclInstantiator::InstantiateEnumDefinition(
685 EnumDecl *Enum, EnumDecl *Pattern) {
686 Enum->startDefinition();
687
Richard Smith7d137e32012-03-23 03:33:32 +0000688 // Update the location to refer to the definition.
689 Enum->setLocation(Pattern->getLocation());
690
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000691 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000692
693 EnumConstantDecl *LastEnumConst = 0;
Richard Smith4b38ded2012-03-14 23:13:10 +0000694 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
695 ECEnd = Pattern->enumerator_end();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000696 EC != ECEnd; ++EC) {
697 // The specified value for the enumerator.
John McCalldadc5752010-08-24 06:29:42 +0000698 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000699 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000700 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +0000701 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +0000702 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000703
John McCall76d824f2009-08-25 22:02:44 +0000704 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000705 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000706
707 // Drop the initial value and continue.
708 bool isInvalid = false;
709 if (Value.isInvalid()) {
710 Value = SemaRef.Owned((Expr *)0);
711 isInvalid = true;
712 }
713
Mike Stump11289f42009-09-09 15:08:12 +0000714 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +0000715 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
716 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +0000717 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000718
719 if (isInvalid) {
720 if (EnumConst)
721 EnumConst->setInvalidDecl();
722 Enum->setInvalidDecl();
723 }
724
725 if (EnumConst) {
David Blaikie40ed2972012-06-06 20:45:41 +0000726 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +0000727
John McCallf9b528c2010-01-23 22:37:59 +0000728 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000729 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +0000730 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000731 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000732
Richard Smith4b38ded2012-03-14 23:13:10 +0000733 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
734 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000735 // If the enumeration is within a function or method, record the enum
736 // constant as a local.
David Blaikie40ed2972012-06-06 20:45:41 +0000737 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000738 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000739 }
740 }
Mike Stump11289f42009-09-09 15:08:12 +0000741
Richard Smith4b38ded2012-03-14 23:13:10 +0000742 // FIXME: Fixup LBraceLoc
743 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
744 Enum->getRBraceLoc(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +0000745 Enumerators,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +0000746 0, 0);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000747}
748
Douglas Gregor9106b822009-03-25 15:04:13 +0000749Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000750 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +0000751}
752
John McCall87a44eb2009-08-20 01:44:21 +0000753Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000754 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
755
Douglas Gregor954de172009-10-31 17:21:17 +0000756 // Create a local instantiation scope for this class template, which
757 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +0000758 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +0000759 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000760 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000761 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +0000762 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +0000763
764 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +0000765
766 // Instantiate the qualifier. We have to do this first in case
767 // we're a friend declaration, because if we are then we need to put
768 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +0000769 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
770 if (QualifierLoc) {
771 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
772 TemplateArgs);
773 if (!QualifierLoc)
774 return 0;
John McCall598b4402010-03-25 06:39:04 +0000775 }
776
777 CXXRecordDecl *PrevDecl = 0;
778 ClassTemplateDecl *PrevClassTemplate = 0;
779
Douglas Gregorec9fd132012-01-14 16:38:05 +0000780 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky61478912010-11-08 23:29:42 +0000781 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000782 if (!Found.empty()) {
783 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +0000784 if (PrevClassTemplate)
785 PrevDecl = PrevClassTemplate->getTemplatedDecl();
786 }
787 }
788
John McCall598b4402010-03-25 06:39:04 +0000789 // If this isn't a friend, then it's a member template, in which
790 // case we just want to build the instantiation in the
791 // specialization. If it is a friend, we want to build it in
792 // the appropriate context.
793 DeclContext *DC = Owner;
794 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +0000795 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000796 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +0000797 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +0000798 DC = SemaRef.computeDeclContext(SS);
799 if (!DC) return 0;
800 } else {
801 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
802 Pattern->getDeclContext(),
803 TemplateArgs);
804 }
805
806 // Look for a previous declaration of the template in the owning
807 // context.
808 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
809 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
810 SemaRef.LookupQualifiedName(R, DC);
811
812 if (R.isSingleResult()) {
813 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
814 if (PrevClassTemplate)
815 PrevDecl = PrevClassTemplate->getTemplatedDecl();
816 }
817
Douglas Gregor14454802011-02-25 02:25:35 +0000818 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000819 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +0000820 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +0000821 << QualifierLoc.getSourceRange();
John McCall598b4402010-03-25 06:39:04 +0000822 return 0;
823 }
824
Douglas Gregor01e09d92010-04-08 18:16:15 +0000825 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +0000826 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +0000827 bool Complain = true;
828
829 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
830 // template for struct std::tr1::__detail::_Map_base, where the
831 // template parameters of the friend declaration don't match the
832 // template parameters of the original declaration. In this one
833 // case, we don't complain about the ill-formed friend
834 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000835 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +0000836 Pattern->getIdentifier()->isStr("_Map_base") &&
837 DC->isNamespace() &&
838 cast<NamespaceDecl>(DC)->getIdentifier() &&
839 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
840 DeclContext *DCParent = DC->getParent();
841 if (DCParent->isNamespace() &&
842 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
843 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
844 DeclContext *DCParent2 = DCParent->getParent();
845 if (DCParent2->isNamespace() &&
846 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
847 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
848 DCParent2->getParent()->isTranslationUnit())
849 Complain = false;
850 }
851 }
852
John McCall598b4402010-03-25 06:39:04 +0000853 TemplateParameterList *PrevParams
854 = PrevClassTemplate->getTemplateParameters();
855
856 // Make sure the parameter lists match.
857 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000858 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +0000859 Sema::TPL_TemplateMatch)) {
860 if (Complain)
861 return 0;
862
863 AdoptedPreviousTemplateParams = true;
864 InstParams = PrevParams;
865 }
John McCall598b4402010-03-25 06:39:04 +0000866
867 // Do some additional validation, then merge default arguments
868 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +0000869 if (!AdoptedPreviousTemplateParams &&
870 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +0000871 Sema::TPC_ClassTemplate))
872 return 0;
873 }
874 }
875
John McCall87a44eb2009-08-20 01:44:21 +0000876 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +0000877 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000878 Pattern->getLocStart(), Pattern->getLocation(),
879 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000880 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +0000881
Douglas Gregor14454802011-02-25 02:25:35 +0000882 if (QualifierLoc)
883 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +0000884
John McCall87a44eb2009-08-20 01:44:21 +0000885 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +0000886 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
887 D->getIdentifier(), InstParams, RecordInst,
888 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +0000889 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +0000890
John McCall598b4402010-03-25 06:39:04 +0000891 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +0000892 if (PrevClassTemplate)
893 Inst->setAccess(PrevClassTemplate->getAccess());
894 else
895 Inst->setAccess(D->getAccess());
896
Richard Smith64017682013-07-17 23:53:16 +0000897 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +0000898 // TODO: do we want to track the instantiation progeny of this
899 // friend target decl?
900 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000901 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +0000902 if (!PrevClassTemplate)
903 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +0000904 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000905
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000906 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +0000907 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +0000908 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +0000909
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000910 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +0000911 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +0000912 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000913 Inst->setLexicalDeclContext(Owner);
914 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000915 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000916 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000917
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000918 if (D->isOutOfLine()) {
919 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
920 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
921 }
922
John McCall87a44eb2009-08-20 01:44:21 +0000923 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +0000924
925 if (!PrevClassTemplate) {
926 // Queue up any out-of-line partial specializations of this member
927 // class template; the client will force their instantiation once
928 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000929 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +0000930 D->getPartialSpecializations(PartialSpecs);
931 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000932 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +0000933 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
934 }
935
John McCall87a44eb2009-08-20 01:44:21 +0000936 return Inst;
937}
938
Douglas Gregore704c9d2009-08-27 16:57:43 +0000939Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +0000940TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
941 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +0000942 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000943
Douglas Gregor21610382009-10-29 00:04:11 +0000944 // Lookup the already-instantiated declaration in the instantiation
945 // of the class template and return that.
946 DeclContext::lookup_result Found
947 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000948 if (Found.empty())
Douglas Gregor21610382009-10-29 00:04:11 +0000949 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000950
Douglas Gregor21610382009-10-29 00:04:11 +0000951 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +0000952 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +0000953 if (!InstClassTemplate)
954 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000955
Douglas Gregor869853e2010-11-10 19:44:59 +0000956 if (ClassTemplatePartialSpecializationDecl *Result
957 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
958 return Result;
959
960 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +0000961}
962
Larisse Voufo39a1e502013-08-06 01:03:05 +0000963Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
964 assert(D->getTemplatedDecl()->isStaticDataMember() &&
965 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +0000966
967 // Create a local instantiation scope for this variable template, which
968 // will contain the instantiations of the template parameters.
969 LocalInstantiationScope Scope(SemaRef);
970 TemplateParameterList *TempParams = D->getTemplateParameters();
971 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
972 if (!InstParams)
973 return NULL;
974
975 VarDecl *Pattern = D->getTemplatedDecl();
976 VarTemplateDecl *PrevVarTemplate = 0;
977
978 if (Pattern->getPreviousDecl()) {
979 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
980 if (!Found.empty())
981 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
982 }
983
Richard Smith1c34fb72013-08-13 18:18:50 +0000984 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000985 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
986 /*InstantiatingVarTemplate=*/true));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000987
988 DeclContext *DC = Owner;
989
Larisse Voufo39a1e502013-08-06 01:03:05 +0000990 VarTemplateDecl *Inst = VarTemplateDecl::Create(
991 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
992 VarInst, PrevVarTemplate);
993 VarInst->setDescribedVarTemplate(Inst);
994
995 Inst->setAccess(D->getAccess());
996 if (!PrevVarTemplate)
997 Inst->setInstantiatedFromMemberTemplate(D);
998
999 if (D->isOutOfLine()) {
1000 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1001 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1002 }
1003
1004 Owner->addDecl(Inst);
1005
1006 if (!PrevVarTemplate) {
1007 // Queue up any out-of-line partial specializations of this member
1008 // variable template; the client will force their instantiation once
1009 // the enclosing class has been instantiated.
1010 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1011 D->getPartialSpecializations(PartialSpecs);
1012 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001013 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001014 OutOfLineVarPartialSpecs.push_back(
1015 std::make_pair(Inst, PartialSpecs[I]));
1016 }
1017
1018 return Inst;
1019}
1020
1021Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1022 VarTemplatePartialSpecializationDecl *D) {
1023 assert(D->isStaticDataMember() &&
1024 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001025
1026 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1027
1028 // Lookup the already-instantiated declaration and return that.
1029 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1030 assert(!Found.empty() && "Instantiation found nothing?");
1031
1032 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1033 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1034
1035 if (VarTemplatePartialSpecializationDecl *Result =
1036 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1037 return Result;
1038
1039 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1040}
1041
Douglas Gregore4b05162009-10-07 17:21:34 +00001042Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001043TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001044 // Create a local instantiation scope for this function template, which
1045 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001046 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001047 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001048 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001049
Douglas Gregore704c9d2009-08-27 16:57:43 +00001050 TemplateParameterList *TempParams = D->getTemplateParameters();
1051 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001052 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001053 return NULL;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001054
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001055 FunctionDecl *Instantiated = 0;
1056 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001057 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001058 InstParams));
1059 else
1060 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001061 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001062 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001063
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001064 if (!Instantiated)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001065 return 0;
1066
Mike Stump11289f42009-09-09 15:08:12 +00001067 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001068 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001069 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001070 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001071 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001072 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001073 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001074
John McCall30837102010-03-26 23:10:15 +00001075 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1076
John McCall2079d0b2009-12-14 23:19:40 +00001077 // Link the instantiation back to the pattern *unless* this is a
1078 // non-definition friend declaration.
1079 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001080 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001081 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001082
John McCall30837102010-03-26 23:10:15 +00001083 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001084 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001085 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001086 } else if (InstTemplate->getDeclContext()->isRecord() &&
1087 !D->getPreviousDecl()) {
1088 SemaRef.CheckFriendAccess(InstTemplate);
1089 }
John McCall30837102010-03-26 23:10:15 +00001090
Douglas Gregore704c9d2009-08-27 16:57:43 +00001091 return InstTemplate;
1092}
1093
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001094Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1095 CXXRecordDecl *PrevDecl = 0;
1096 if (D->isInjectedClassName())
1097 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001098 else if (D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001099 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregorec9fd132012-01-14 16:38:05 +00001100 D->getPreviousDecl(),
John McCalle9f92a02009-12-15 22:29:06 +00001101 TemplateArgs);
1102 if (!Prev) return 0;
1103 PrevDecl = cast<CXXRecordDecl>(Prev);
1104 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001105
1106 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001107 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001108 D->getLocStart(), D->getLocation(),
1109 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001110
1111 // Substitute the nested name specifier, if any.
1112 if (SubstQualifier(D, Record))
1113 return 0;
1114
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001115 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001116 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1117 // the tag decls introduced by friend class declarations don't have an access
1118 // specifier. Remove once this area of the code gets sorted out.
1119 if (D->getAccess() != AS_none)
1120 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001121 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001122 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001123
John McCallaa74a0c2009-08-28 07:59:38 +00001124 // If the original function was part of a friend declaration,
1125 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001126 if (D->getFriendObjectKind())
1127 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001128
Douglas Gregor04163182010-05-21 00:31:19 +00001129 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001130 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001131 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001132
1133 if (D->isLocalClass())
1134 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001135
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001136 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001137
1138 // DR1484 clarifies that the members of a local class are instantiated as part
1139 // of the instantiation of their enclosing entity.
1140 if (D->isCompleteDefinition() && D->isLocalClass()) {
1141 if (SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1142 TSK_ImplicitInstantiation,
1143 /*Complain=*/true)) {
1144 llvm_unreachable("InstantiateClass shouldn't fail here!");
1145 } else {
1146 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1147 TSK_ImplicitInstantiation);
1148 }
1149 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001150 return Record;
1151}
1152
Douglas Gregor89f593a2012-09-13 21:56:43 +00001153/// \brief Adjust the given function type for an instantiation of the
1154/// given declaration, to cope with modifications to the function's type that
1155/// aren't reflected in the type-source information.
1156///
1157/// \param D The declaration we're instantiating.
1158/// \param TInfo The already-instantiated type.
1159static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1160 FunctionDecl *D,
1161 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001162 const FunctionProtoType *OrigFunc
1163 = D->getType()->castAs<FunctionProtoType>();
1164 const FunctionProtoType *NewFunc
1165 = TInfo->getType()->castAs<FunctionProtoType>();
1166 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1167 return TInfo->getType();
1168
1169 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1170 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1171 return Context.getFunctionType(NewFunc->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00001172 NewFunc->getArgTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001173}
1174
John McCallaa74a0c2009-08-28 07:59:38 +00001175/// Normal class members are of more specific types and therefore
1176/// don't make it here. This function serves two purposes:
1177/// 1) instantiating function templates
1178/// 2) substituting friend declarations
1179/// FIXME: preserve function definitions in case #2
Douglas Gregor33636e62009-12-24 20:56:24 +00001180Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001181 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001182 // Check whether there is already a function template specialization for
1183 // this declaration.
1184 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001185 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001186 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001187
Douglas Gregorce9978f2012-03-28 14:34:23 +00001188 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001189 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001190 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001191 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001192
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001193 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001194 if (SpecFunc)
1195 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001196 }
Mike Stump11289f42009-09-09 15:08:12 +00001197
John McCall2f88d7d2010-03-27 05:57:59 +00001198 bool isFriend;
1199 if (FunctionTemplate)
1200 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1201 else
1202 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1203
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001204 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001205 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001206 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001207 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001208 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001209
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001210 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001211 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001212 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001213 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001214 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001215
Douglas Gregor14454802011-02-25 02:25:35 +00001216 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1217 if (QualifierLoc) {
1218 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1219 TemplateArgs);
1220 if (!QualifierLoc)
1221 return 0;
John McCalle0b2ddb2010-03-26 04:53:08 +00001222 }
1223
John McCallce410662010-02-06 01:50:47 +00001224 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001225 // in the enclosing namespace; otherwise we need to find the instantiated
1226 // context.
John McCallce410662010-02-06 01:50:47 +00001227 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001228 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001229 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001230 SemaRef.adjustContextForLocalExternDecl(DC);
1231 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001232 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001233 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001234 DC = SemaRef.computeDeclContext(SS);
1235 if (!DC) return 0;
1236 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001237 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001238 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001239 }
John McCallce410662010-02-06 01:50:47 +00001240
John McCallaa74a0c2009-08-28 07:59:38 +00001241 FunctionDecl *Function =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001242 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara0d4fce12012-10-04 21:40:42 +00001243 D->getNameInfo(), T, TInfo,
Rafael Espindola9dd86de2013-04-16 02:29:15 +00001244 D->getCanonicalDecl()->getStorageClass(),
Richard Smitha77a0a62011-08-15 21:04:07 +00001245 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001246 D->isConstexpr());
Enea Zaffanella25723ce2013-07-19 18:02:36 +00001247 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCall3e11ebe2010-03-15 10:12:16 +00001248
Richard Smithf3814ad2013-01-25 00:08:28 +00001249 if (D->isInlined())
1250 Function->setImplicitlyInline();
1251
Douglas Gregor14454802011-02-25 02:25:35 +00001252 if (QualifierLoc)
1253 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001254
Richard Smith541b38b2013-09-20 01:15:31 +00001255 if (D->isLocalExternDecl())
1256 Function->setLocalExternDecl();
1257
John McCall30837102010-03-26 23:10:15 +00001258 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001259 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001260 assert(D->getDeclContext()->isFileContext());
1261 LexicalDC = D->getDeclContext();
1262 }
1263
1264 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001265
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001266 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001267 for (unsigned P = 0; P < Params.size(); ++P)
1268 if (Params[P])
1269 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001270 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001271
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001272 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001273 if (TemplateParams) {
1274 // Our resulting instantiation is actually a function template, since we
1275 // are substituting only the outer template parameters. For example, given
1276 //
1277 // template<typename T>
1278 // struct X {
1279 // template<typename U> friend void f(T, U);
1280 // };
1281 //
1282 // X<int> x;
1283 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001284 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001285 // which means substituting int for T, but leaving "f" as a friend function
1286 // template.
1287 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001288 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001289 Function->getLocation(),
1290 Function->getDeclName(),
1291 TemplateParams, Function);
1292 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001293
1294 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001295
1296 if (isFriend && D->isThisDeclarationADefinition()) {
1297 // TODO: should we remember this connection regardless of whether
1298 // the friend declaration provided a body?
1299 FunctionTemplate->setInstantiatedFromMemberTemplate(
1300 D->getDescribedFunctionTemplate());
1301 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001302 } else if (FunctionTemplate) {
1303 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001304 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001305 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001306 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001307 Innermost.begin(),
1308 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001309 /*InsertPos=*/0);
Chandler Carruth48b28312011-08-18 09:09:59 +00001310 } else if (isFriend) {
1311 // Note, we need this connection even if the friend doesn't have a body.
1312 // Its body may exist but not have been attached yet due to deferred
1313 // parsing.
1314 // FIXME: It might be cleaner to set this when attaching the body to the
1315 // friend function declaration, however that would require finding all the
1316 // instantiations and modifying them.
John McCalle0b2ddb2010-03-26 04:53:08 +00001317 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001318 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001319
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001320 if (InitFunctionInstantiation(Function, D))
1321 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001322
John McCallb9c78482010-04-08 09:05:18 +00001323 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001324
Richard Smith541b38b2013-09-20 01:15:31 +00001325 LookupResult Previous(
1326 SemaRef, Function->getDeclName(), SourceLocation(),
1327 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1328 : Sema::LookupOrdinaryName,
1329 Sema::ForRedeclaration);
John McCall1f82f242009-11-18 22:49:29 +00001330
John McCallb9c78482010-04-08 09:05:18 +00001331 if (DependentFunctionTemplateSpecializationInfo *Info
1332 = D->getDependentSpecializationInfo()) {
1333 assert(isFriend && "non-friend has dependent specialization info?");
1334
1335 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001336 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001337
1338 // Instantiate the explicit template arguments.
1339 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1340 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001341 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1342 ExplicitArgs, TemplateArgs))
1343 return 0;
John McCallb9c78482010-04-08 09:05:18 +00001344
1345 // Map the candidate templates to their instantiations.
1346 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1347 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1348 Info->getTemplate(I),
1349 TemplateArgs);
1350 if (!Temp) return 0;
1351
1352 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1353 }
1354
1355 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1356 &ExplicitArgs,
1357 Previous))
1358 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001359
John McCallb9c78482010-04-08 09:05:18 +00001360 isExplicitSpecialization = true;
1361
1362 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001363 // Look only into the namespace where the friend would be declared to
1364 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001365 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001366 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001367
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001368 // In C++, the previous declaration we find might be a tag type
1369 // (class or enum). In this case, the new declaration will hide the
1370 // tag type. Note that this does does not apply if we're declaring a
1371 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001372 if (Previous.isSingleTagDecl())
1373 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001374 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001375
John McCall84d87672009-12-10 09:41:52 +00001376 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001377 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001378
John McCallb9467b62010-04-24 01:30:58 +00001379 NamedDecl *PrincipalDecl = (TemplateParams
1380 ? cast<NamedDecl>(FunctionTemplate)
1381 : Function);
1382
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001383 // If the original function was part of a friend declaration,
1384 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001385 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001386 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001387 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001388
Gabor Greif12866172010-08-30 22:25:56 +00001389 bool queuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001390
Richard Smitha066ccf2011-10-19 00:54:10 +00001391 // C++98 [temp.friend]p5: When a function is defined in a friend function
1392 // declaration in a class template, the function is defined at each
1393 // instantiation of the class template. The function is defined even if it
1394 // is never used.
1395 // C++11 [temp.friend]p4: When a function is defined in a friend function
1396 // declaration in a class template, the function is instantiated when the
1397 // function is odr-used.
1398 //
1399 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1400 // redefinition, but don't instantiate the function.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001401 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smitha066ccf2011-10-19 00:54:10 +00001402 SemaRef.Diags.getDiagnosticLevel(
1403 diag::warn_cxx98_compat_friend_redefinition,
1404 Function->getLocation())
1405 != DiagnosticsEngine::Ignored) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001406 D->isThisDeclarationADefinition()) {
1407 // Check for a function body.
1408 const FunctionDecl *Definition = 0;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001409 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001410 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smitha066ccf2011-10-19 00:54:10 +00001411 SemaRef.Diag(Function->getLocation(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001412 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smitha066ccf2011-10-19 00:54:10 +00001413 diag::warn_cxx98_compat_friend_redefinition :
1414 diag::err_redefinition) << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001415 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001416 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smitha066ccf2011-10-19 00:54:10 +00001417 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001418 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001419 // Check for redefinitions due to other instantiations of this or
1420 // a similar friend function.
1421 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1422 REnd = Function->redecls_end();
1423 R != REnd; ++R) {
Gabor Greif122f1eb2010-08-28 15:42:30 +00001424 if (*R == Function)
1425 continue;
Gabor Greif718d5152010-08-30 21:10:05 +00001426 switch (R->getFriendObjectKind()) {
1427 case Decl::FOK_None:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001428 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smitha066ccf2011-10-19 00:54:10 +00001429 !queuedInstantiation && R->isUsed(false)) {
Gabor Greif718d5152010-08-30 21:10:05 +00001430 if (MemberSpecializationInfo *MSInfo
1431 = Function->getMemberSpecializationInfo()) {
1432 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1433 SourceLocation Loc = R->getLocation(); // FIXME
1434 MSInfo->setPointOfInstantiation(Loc);
1435 SemaRef.PendingLocalImplicitInstantiations.push_back(
1436 std::make_pair(Function, Loc));
1437 queuedInstantiation = true;
1438 }
1439 }
1440 }
1441 break;
1442 default:
Douglas Gregorb92ea592010-05-18 05:45:02 +00001443 if (const FunctionDecl *RPattern
Gabor Greifae849e42010-08-28 15:46:56 +00001444 = R->getTemplateInstantiationPattern())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001445 if (RPattern->isDefined(RPattern)) {
Richard Smitha066ccf2011-10-19 00:54:10 +00001446 SemaRef.Diag(Function->getLocation(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001447 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smitha066ccf2011-10-19 00:54:10 +00001448 diag::warn_cxx98_compat_friend_redefinition :
1449 diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001450 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001451 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001452 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smitha066ccf2011-10-19 00:54:10 +00001453 Function->setInvalidDecl();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001454 break;
1455 }
1456 }
1457 }
1458 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001459 }
1460
Richard Smith541b38b2013-09-20 01:15:31 +00001461 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1462 DC->makeDeclVisibleInContext(PrincipalDecl);
1463
John McCallb9467b62010-04-24 01:30:58 +00001464 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1465 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1466 PrincipalDecl->setNonMemberOperator();
1467
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001468 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001469 return Function;
1470}
1471
Douglas Gregore704c9d2009-08-27 16:57:43 +00001472Decl *
1473TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001474 TemplateParameterList *TemplateParams,
1475 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001476 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001477 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001478 // We are creating a function template specialization from a function
1479 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001480 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001481 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001482
Douglas Gregorce9978f2012-03-28 14:34:23 +00001483 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001484 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001485 = FunctionTemplate->findSpecialization(Innermost.begin(),
1486 Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001487 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001488
Douglas Gregor97628d62009-08-21 00:16:32 +00001489 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001490 if (SpecFunc)
1491 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001492 }
1493
John McCall2f88d7d2010-03-27 05:57:59 +00001494 bool isFriend;
1495 if (FunctionTemplate)
1496 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1497 else
1498 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1499
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001500 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001501 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001502 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001503 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001504
John McCalld0e23ec2010-10-19 02:26:41 +00001505 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001506 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001507 unsigned NumTempParamLists = 0;
1508 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1509 TempParamLists.set_size(NumTempParamLists);
1510 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1511 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1512 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1513 if (!InstParams)
1514 return NULL;
1515 TempParamLists[I] = InstParams;
1516 }
1517 }
1518
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001519 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001520 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001521 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001522 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001523 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001524
Douglas Gregor14454802011-02-25 02:25:35 +00001525 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1526 if (QualifierLoc) {
1527 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001528 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001529 if (!QualifierLoc)
Douglas Gregor14454802011-02-25 02:25:35 +00001530 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001531 }
1532
1533 DeclContext *DC = Owner;
1534 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001535 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001536 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001537 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001538 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001539
1540 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1541 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001542 } else {
1543 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1544 D->getDeclContext(),
1545 TemplateArgs);
1546 }
1547 if (!DC) return 0;
1548 }
1549
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001550 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001551 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001552 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001553
Abramo Bagnaradff19302011-03-08 08:55:46 +00001554 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001555 DeclarationNameInfo NameInfo
1556 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001557 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001558 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001559 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001560 Constructor->isExplicit(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001561 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001562 false, Constructor->isConstexpr());
Richard Smith4c163a02013-05-17 02:19:35 +00001563
Richard Smith185be182013-04-10 05:48:59 +00001564 // Claim that the instantiation of a constructor or constructor template
1565 // inherits the same constructor that the template does.
Richard Smith4c163a02013-05-17 02:19:35 +00001566 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1567 Constructor->getInheritedConstructor())) {
1568 // If we're instantiating a specialization of a function template, our
1569 // "inherited constructor" will actually itself be a function template.
1570 // Instantiate a declaration of it, too.
1571 if (FunctionTemplate) {
1572 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1573 !Inh->getParent()->isDependentContext() &&
1574 "inheriting constructor template in dependent context?");
1575 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1576 Inh);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001577 if (Inst.isInvalid())
Richard Smith4c163a02013-05-17 02:19:35 +00001578 return 0;
1579 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1580 LocalInstantiationScope LocalScope(SemaRef);
1581
1582 // Use the same template arguments that we deduced for the inheriting
1583 // constructor. There's no way they could be deduced differently.
1584 MultiLevelTemplateArgumentList InheritedArgs;
1585 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1586 Inh = cast_or_null<CXXConstructorDecl>(
1587 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1588 if (!Inh)
1589 return 0;
1590 }
Richard Smith185be182013-04-10 05:48:59 +00001591 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smith4c163a02013-05-17 02:19:35 +00001592 }
Douglas Gregore8394862009-08-21 22:43:28 +00001593 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001594 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001595 StartLoc, NameInfo, T, TInfo,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001596 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001597 false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001598 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001599 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001600 StartLoc, NameInfo, T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001601 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001602 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001603 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001604 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001605 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001606 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001607 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001608 StartLoc, NameInfo, T, TInfo,
Rafael Espindola29cda592013-04-15 12:38:20 +00001609 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001610 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001611 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001612
Richard Smithf3814ad2013-01-25 00:08:28 +00001613 if (D->isInlined())
1614 Method->setImplicitlyInline();
1615
Douglas Gregor14454802011-02-25 02:25:35 +00001616 if (QualifierLoc)
1617 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001618
Douglas Gregore704c9d2009-08-27 16:57:43 +00001619 if (TemplateParams) {
1620 // Our resulting instantiation is actually a function template, since we
1621 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001622 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001623 // template<typename T>
1624 // struct X {
1625 // template<typename U> void f(T, U);
1626 // };
1627 //
1628 // X<int> x;
1629 //
1630 // We are instantiating the member template "f" within X<int>, which means
1631 // substituting int for T, but leaving "f" as a member function template.
1632 // Build the function template itself.
1633 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1634 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001635 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001636 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001637 if (isFriend) {
1638 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001639 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001640 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001641 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001642 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001643 } else if (FunctionTemplate) {
1644 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001645 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001646 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001647 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001648 Innermost.begin(),
1649 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001650 /*InsertPos=*/0);
John McCall2f88d7d2010-03-27 05:57:59 +00001651 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001652 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001653 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001654 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001655
Mike Stump11289f42009-09-09 15:08:12 +00001656 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001657 // out-of-line, the instantiation will have the same lexical
1658 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001659 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00001660 if (NumTempParamLists)
1661 Method->setTemplateParameterListsInfo(SemaRef.Context,
1662 NumTempParamLists,
1663 TempParamLists.data());
1664
John McCall2f88d7d2010-03-27 05:57:59 +00001665 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001666 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001667 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001668 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001669
Douglas Gregor21342092009-03-24 00:38:23 +00001670 // Attach the parameters
1671 for (unsigned P = 0; P < Params.size(); ++P)
1672 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00001673 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00001674
1675 if (InitMethodInstantiation(Method, D))
1676 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001677
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001678 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1679 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001680
John McCall2f88d7d2010-03-27 05:57:59 +00001681 if (!FunctionTemplate || TemplateParams || isFriend) {
1682 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001683
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001684 // In C++, the previous declaration we find might be a tag type
1685 // (class or enum). In this case, the new declaration will hide the
1686 // tag type. Note that this does does not apply if we're declaring a
1687 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001688 if (Previous.isSingleTagDecl())
1689 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001690 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001691
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001692 if (!IsClassScopeSpecialization)
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001693 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001694
Douglas Gregor21920e372009-12-01 17:24:26 +00001695 if (D->isPure())
1696 SemaRef.CheckPureMethod(Method, SourceRange());
1697
John McCalla0a96892012-08-10 03:15:35 +00001698 // Propagate access. For a non-friend declaration, the access is
1699 // whatever we're propagating from. For a friend, it should be the
1700 // previous declaration we just found.
1701 if (isFriend && Method->getPreviousDecl())
1702 Method->setAccess(Method->getPreviousDecl()->getAccess());
1703 else
1704 Method->setAccess(D->getAccess());
1705 if (FunctionTemplate)
1706 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00001707
Anders Carlsson7c812f52011-01-20 06:52:44 +00001708 SemaRef.CheckOverrideControl(Method);
1709
Eli Friedman41340732011-11-15 22:39:08 +00001710 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00001711 if (D->isExplicitlyDefaulted())
1712 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001713 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00001714 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001715
John McCalla0a96892012-08-10 03:15:35 +00001716 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00001717 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00001718 // do nothing
1719
1720 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00001721 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00001722 // do nothing
1723
1724 // Otherwise, check access to friends and make them visible.
1725 } else if (isFriend) {
1726 // We only need to re-check access for methods which we didn't
1727 // manage to match during parsing.
1728 if (!D->getPreviousDecl())
1729 SemaRef.CheckFriendAccess(Method);
1730
1731 Record->makeDeclVisibleInContext(Method);
1732
1733 // Otherwise, add the declaration. We don't need to do this for
1734 // class-scope specializations because we'll have matched them with
1735 // the appropriate template.
1736 } else if (!IsClassScopeSpecialization) {
1737 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001738 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001739
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001740 return Method;
1741}
1742
Douglas Gregor4044d992009-03-24 16:43:20 +00001743Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001744 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001745}
1746
Douglas Gregor654b07e2009-03-24 00:15:49 +00001747Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001748 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001749}
1750
Douglas Gregor1880ba52009-03-25 00:34:44 +00001751Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001752 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001753}
1754
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00001755Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00001756 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1757 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001758}
1759
John McCall87a44eb2009-08-20 01:44:21 +00001760Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1761 TemplateTypeParmDecl *D) {
1762 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00001763 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00001764
John McCall87a44eb2009-08-20 01:44:21 +00001765 TemplateTypeParmDecl *Inst =
Abramo Bagnarab3185b02011-03-06 15:48:19 +00001766 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1767 D->getLocStart(), D->getLocation(),
Chandler Carruth08836322011-05-01 00:51:33 +00001768 D->getDepth() - TemplateArgs.getNumLevels(),
1769 D->getIndex(), D->getIdentifier(),
John McCall87a44eb2009-08-20 01:44:21 +00001770 D->wasDeclaredWithTypename(),
1771 D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001772 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00001773
David Majnemer89189202013-08-28 23:48:32 +00001774 if (D->hasDefaultArgument()) {
1775 TypeSourceInfo *InstantiatedDefaultArg =
1776 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1777 D->getDefaultArgumentLoc(), D->getDeclName());
1778 if (InstantiatedDefaultArg)
1779 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1780 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001781
1782 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001783 // scope.
1784 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001785
John McCall87a44eb2009-08-20 01:44:21 +00001786 return Inst;
1787}
1788
Douglas Gregor6b815c82009-10-23 23:25:44 +00001789Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1790 NonTypeTemplateParmDecl *D) {
1791 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001792 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001793 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1794 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001795 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001796 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001797 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001798 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001799
1800 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001801 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001802 // expansion of types. Substitute into each of the expanded types.
1803 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1804 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1805 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1806 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1807 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001808 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001809 D->getDeclName());
1810 if (!NewDI)
1811 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001812
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001813 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1814 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1815 D->getLocation());
1816 if (NewT.isNull())
1817 return 0;
1818 ExpandedParameterPackTypes.push_back(NewT);
1819 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001820
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001821 IsExpandedParameterPack = true;
1822 DI = D->getTypeSourceInfo();
1823 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00001824 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001825 // The non-type template parameter pack's type is a pack expansion of types.
1826 // Determine whether we need to expand this parameter pack into separate
1827 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00001828 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001829 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001830 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001831 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001832
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001833 // Determine whether the set of unexpanded parameter packs can and should
1834 // be expanded.
1835 bool Expand = true;
1836 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001837 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001838 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00001839 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001840 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1841 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001842 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001843 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001844 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001845 NumExpansions))
1846 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001847
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001848 if (Expand) {
1849 for (unsigned I = 0; I != *NumExpansions; ++I) {
1850 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1851 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001852 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001853 D->getDeclName());
1854 if (!NewDI)
1855 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001856
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001857 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1858 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1859 NewDI->getType(),
1860 D->getLocation());
1861 if (NewT.isNull())
1862 return 0;
1863 ExpandedParameterPackTypes.push_back(NewT);
1864 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001865
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001866 // Note that we have an expanded parameter pack. The "type" of this
1867 // expanded parameter pack is the original expansion type, but callers
1868 // will end up using the expanded parameter pack types for type-checking.
1869 IsExpandedParameterPack = true;
1870 DI = D->getTypeSourceInfo();
1871 T = DI->getType();
1872 } else {
1873 // We cannot fully expand the pack expansion now, so substitute into the
1874 // pattern and create a new pack expansion type.
1875 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1876 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001877 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001878 D->getDeclName());
1879 if (!NewPattern)
1880 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001881
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001882 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1883 NumExpansions);
1884 if (!DI)
1885 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001886
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001887 T = DI->getType();
1888 }
1889 } else {
1890 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001891 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001892 D->getLocation(), D->getDeclName());
1893 if (!DI)
1894 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001895
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001896 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001897 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001898 D->getLocation());
1899 if (T.isNull()) {
1900 T = SemaRef.Context.IntTy;
1901 Invalid = true;
1902 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00001903 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001904
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001905 NonTypeTemplateParmDecl *Param;
1906 if (IsExpandedParameterPack)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001907 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001908 D->getInnerLocStart(),
1909 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001910 D->getDepth() - TemplateArgs.getNumLevels(),
1911 D->getPosition(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001912 D->getIdentifier(), T,
1913 DI,
1914 ExpandedParameterPackTypes.data(),
1915 ExpandedParameterPackTypes.size(),
1916 ExpandedParameterPackTypesAsWritten.data());
1917 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001918 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001919 D->getInnerLocStart(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001920 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001921 D->getDepth() - TemplateArgs.getNumLevels(),
1922 D->getPosition(),
1923 D->getIdentifier(), T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001924 D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001925
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001926 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001927 if (Invalid)
1928 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001929
David Majnemer89189202013-08-28 23:48:32 +00001930 if (D->hasDefaultArgument()) {
1931 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1932 if (!Value.isInvalid())
1933 Param->setDefaultArgument(Value.get(), false);
1934 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001935
1936 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001937 // scope.
1938 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001939 return Param;
1940}
1941
Richard Smith1fde8ec2012-09-07 02:06:42 +00001942static void collectUnexpandedParameterPacks(
1943 Sema &S,
1944 TemplateParameterList *Params,
1945 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1946 for (TemplateParameterList::const_iterator I = Params->begin(),
1947 E = Params->end(); I != E; ++I) {
1948 if ((*I)->isTemplateParameterPack())
1949 continue;
1950 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1951 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1952 Unexpanded);
1953 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1954 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1955 Unexpanded);
1956 }
1957}
1958
Anders Carlsson4bd78752009-08-28 15:18:15 +00001959Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00001960TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1961 TemplateTemplateParmDecl *D) {
1962 // Instantiate the template parameter list of the template template parameter.
1963 TemplateParameterList *TempParams = D->getTemplateParameters();
1964 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001965 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1966
1967 bool IsExpandedParameterPack = false;
1968
1969 if (D->isExpandedParameterPack()) {
1970 // The template template parameter pack is an already-expanded pack
1971 // expansion of template parameters. Substitute into each of the expanded
1972 // parameters.
1973 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1974 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1975 I != N; ++I) {
1976 LocalInstantiationScope Scope(SemaRef);
1977 TemplateParameterList *Expansion =
1978 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1979 if (!Expansion)
1980 return 0;
1981 ExpandedParams.push_back(Expansion);
1982 }
1983
1984 IsExpandedParameterPack = true;
1985 InstParams = TempParams;
1986 } else if (D->isPackExpansion()) {
1987 // The template template parameter pack expands to a pack of template
1988 // template parameters. Determine whether we need to expand this parameter
1989 // pack into separate parameters.
1990 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1991 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1992 Unexpanded);
1993
1994 // Determine whether the set of unexpanded parameter packs can and should
1995 // be expanded.
1996 bool Expand = true;
1997 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001998 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001999 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2000 TempParams->getSourceRange(),
2001 Unexpanded,
2002 TemplateArgs,
2003 Expand, RetainExpansion,
2004 NumExpansions))
2005 return 0;
2006
2007 if (Expand) {
2008 for (unsigned I = 0; I != *NumExpansions; ++I) {
2009 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2010 LocalInstantiationScope Scope(SemaRef);
2011 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2012 if (!Expansion)
2013 return 0;
2014 ExpandedParams.push_back(Expansion);
2015 }
2016
2017 // Note that we have an expanded parameter pack. The "type" of this
2018 // expanded parameter pack is the original expansion type, but callers
2019 // will end up using the expanded parameter pack types for type-checking.
2020 IsExpandedParameterPack = true;
2021 InstParams = TempParams;
2022 } else {
2023 // We cannot fully expand the pack expansion now, so just substitute
2024 // into the pattern.
2025 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2026
2027 LocalInstantiationScope Scope(SemaRef);
2028 InstParams = SubstTemplateParams(TempParams);
2029 if (!InstParams)
2030 return 0;
2031 }
2032 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002033 // Perform the actual substitution of template parameters within a new,
2034 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002035 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002036 InstParams = SubstTemplateParams(TempParams);
2037 if (!InstParams)
Richard Smith1fde8ec2012-09-07 02:06:42 +00002038 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002039 }
2040
Douglas Gregor38fee962009-11-11 16:58:32 +00002041 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002042 TemplateTemplateParmDecl *Param;
2043 if (IsExpandedParameterPack)
2044 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2045 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002046 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00002047 D->getPosition(),
2048 D->getIdentifier(), InstParams,
2049 ExpandedParams);
2050 else
2051 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2052 D->getLocation(),
2053 D->getDepth() - TemplateArgs.getNumLevels(),
2054 D->getPosition(),
2055 D->isParameterPack(),
2056 D->getIdentifier(), InstParams);
David Majnemer89189202013-08-28 23:48:32 +00002057 if (D->hasDefaultArgument()) {
2058 NestedNameSpecifierLoc QualifierLoc =
2059 D->getDefaultArgument().getTemplateQualifierLoc();
2060 QualifierLoc =
2061 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2062 TemplateName TName = SemaRef.SubstTemplateName(
2063 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2064 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2065 if (!TName.isNull())
2066 Param->setDefaultArgument(
2067 TemplateArgumentLoc(TemplateArgument(TName),
2068 D->getDefaultArgument().getTemplateQualifierLoc(),
2069 D->getDefaultArgument().getTemplateNameLoc()),
2070 false);
2071 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002072 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002073
2074 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002075 // scope.
2076 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002077
Douglas Gregor38fee962009-11-11 16:58:32 +00002078 return Param;
2079}
2080
Douglas Gregore0b28662009-11-17 06:07:40 +00002081Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002082 // Using directives are never dependent (and never contain any types or
2083 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002084
Douglas Gregore0b28662009-11-17 06:07:40 +00002085 UsingDirectiveDecl *Inst
2086 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002087 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002088 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002089 D->getIdentLocation(),
2090 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002091 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002092
2093 // Add the using directive to its declaration context
2094 // only if this is not a function or method.
2095 if (!Owner->isFunctionOrMethod())
2096 Owner->addDecl(Inst);
2097
Douglas Gregore0b28662009-11-17 06:07:40 +00002098 return Inst;
2099}
2100
John McCallb96ec562009-12-04 22:46:56 +00002101Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002102
2103 // The nested name specifier may be dependent, for example
2104 // template <typename T> struct t {
2105 // struct s1 { T f1(); };
2106 // struct s2 : s1 { using s1::f1; };
2107 // };
2108 // template struct t<int>;
2109 // Here, in using s1::f1, s1 refers to t<T>::s1;
2110 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002111 NestedNameSpecifierLoc QualifierLoc
2112 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2113 TemplateArgs);
2114 if (!QualifierLoc)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00002115 return 0;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002116
2117 // The name info is non-dependent, so no transformation
2118 // is required.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002119 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCallb96ec562009-12-04 22:46:56 +00002120
John McCall84d87672009-12-10 09:41:52 +00002121 // We only need to do redeclaration lookups if we're in a class
2122 // scope (in fact, it's not really even possible in non-class
2123 // scopes).
2124 bool CheckRedeclaration = Owner->isRecord();
2125
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002126 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2127 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002128
John McCallb96ec562009-12-04 22:46:56 +00002129 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002130 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002131 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002132 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002133 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002134
Douglas Gregor0499ab62011-02-25 15:54:31 +00002135 CXXScopeSpec SS;
2136 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002137 if (CheckRedeclaration) {
2138 Prev.setHideTags(false);
2139 SemaRef.LookupQualifiedName(Prev, Owner);
2140
2141 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002142 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2143 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002144 D->getLocation(), Prev))
2145 NewUD->setInvalidDecl();
2146
2147 }
2148
2149 if (!NewUD->isInvalidDecl() &&
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002150 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
John McCallb96ec562009-12-04 22:46:56 +00002151 D->getLocation()))
2152 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002153
John McCallb96ec562009-12-04 22:46:56 +00002154 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2155 NewUD->setAccess(D->getAccess());
2156 Owner->addDecl(NewUD);
2157
John McCall84d87672009-12-10 09:41:52 +00002158 // Don't process the shadow decls for an invalid decl.
2159 if (NewUD->isInvalidDecl())
2160 return NewUD;
2161
Richard Smith23d55872012-04-02 01:30:27 +00002162 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2163 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2164 NewUD->setInvalidDecl();
2165 return NewUD;
2166 }
2167
John McCalla1d85502009-12-22 22:26:37 +00002168 bool isFunctionScope = Owner->isFunctionOrMethod();
2169
John McCall84d87672009-12-10 09:41:52 +00002170 // Process the shadow decls.
2171 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2172 I != E; ++I) {
2173 UsingShadowDecl *Shadow = *I;
2174 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002175 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2176 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002177 if (!InstTarget)
2178 return 0;
John McCall84d87672009-12-10 09:41:52 +00002179
Richard Smithfd8634a2013-10-23 02:17:46 +00002180 UsingShadowDecl *PrevDecl = 0;
2181 if (CheckRedeclaration) {
2182 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2183 continue;
2184 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2185 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2186 Shadow->getLocation(), OldPrev, TemplateArgs));
2187 }
John McCall84d87672009-12-10 09:41:52 +00002188
Richard Smithfd8634a2013-10-23 02:17:46 +00002189 UsingShadowDecl *InstShadow =
2190 SemaRef.BuildUsingShadowDecl(/*Scope*/0, NewUD, InstTarget, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002191 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002192
2193 if (isFunctionScope)
2194 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002195 }
John McCallb96ec562009-12-04 22:46:56 +00002196
2197 return NewUD;
2198}
2199
2200Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002201 // Ignore these; we handle them in bulk when processing the UsingDecl.
2202 return 0;
John McCallb96ec562009-12-04 22:46:56 +00002203}
2204
John McCalle61f2ba2009-11-18 02:36:19 +00002205Decl * TemplateDeclInstantiator
2206 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002207 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002208 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002209 TemplateArgs);
2210 if (!QualifierLoc)
Anders Carlsson4bd78752009-08-28 15:18:15 +00002211 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002212
Anders Carlsson4bd78752009-08-28 15:18:15 +00002213 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002214 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002215
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002216 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Kramerd81108f2012-11-14 15:08:31 +00002217 // Hence, no transformation is required for it.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002218 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002219 NamedDecl *UD =
John McCall3f746822009-11-17 05:59:44 +00002220 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002221 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002222 /*instantiation*/ true,
2223 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor6044d692010-05-19 17:02:24 +00002224 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002225 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2226
John McCalle61f2ba2009-11-18 02:36:19 +00002227 return UD;
2228}
2229
2230Decl * TemplateDeclInstantiator
2231 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002232 NestedNameSpecifierLoc QualifierLoc
2233 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2234 if (!QualifierLoc)
John McCalle61f2ba2009-11-18 02:36:19 +00002235 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002236
John McCalle61f2ba2009-11-18 02:36:19 +00002237 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002238 SS.Adopt(QualifierLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00002239
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002240 DeclarationNameInfo NameInfo
2241 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2242
John McCalle61f2ba2009-11-18 02:36:19 +00002243 NamedDecl *UD =
2244 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002245 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002246 /*instantiation*/ true,
2247 /*typename*/ false, SourceLocation());
Douglas Gregor6044d692010-05-19 17:02:24 +00002248 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002249 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2250
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002251 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00002252}
2253
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002254
2255Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2256 ClassScopeFunctionSpecializationDecl *Decl) {
2257 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber7b5a7162012-06-25 17:21:05 +00002258 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2259 0, true));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002260
2261 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2262 Sema::ForRedeclaration);
2263
Nico Weber7b5a7162012-06-25 17:21:05 +00002264 TemplateArgumentListInfo TemplateArgs;
2265 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2266 if (Decl->hasExplicitTemplateArgs()) {
2267 TemplateArgs = Decl->templateArgs();
2268 TemplateArgsPtr = &TemplateArgs;
2269 }
2270
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002271 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002272 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2273 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002274 NewFD->setInvalidDecl();
2275 return NewFD;
2276 }
2277
2278 // Associate the specialization with the pattern.
2279 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2280 assert(Specialization && "Class scope Specialization is null");
2281 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2282
2283 return NewFD;
2284}
2285
Alexey Bataeva769e072013-03-22 06:34:35 +00002286Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2287 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002288 SmallVector<Expr *, 5> Vars;
2289 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2290 E = D->varlist_end();
Alexey Bataeva769e072013-03-22 06:34:35 +00002291 I != E; ++I) {
2292 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2293 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002294 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002295 }
2296
2297 OMPThreadPrivateDecl *TD =
2298 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2299
2300 return TD;
2301}
2302
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002303Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2304 return VisitFunctionDecl(D, 0);
2305}
2306
2307Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2308 return VisitCXXMethodDecl(D, 0);
2309}
2310
2311Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2312 llvm_unreachable("There are only CXXRecordDecls in C++");
2313}
2314
2315Decl *
2316TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2317 ClassTemplateSpecializationDecl *D) {
2318 llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur"
2319 "inside templates");
2320}
2321
Larisse Voufo39a1e502013-08-06 01:03:05 +00002322Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2323 VarTemplateSpecializationDecl *D) {
2324
2325 TemplateArgumentListInfo VarTemplateArgsInfo;
2326 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2327 assert(VarTemplate &&
2328 "A template specialization without specialized template?");
2329
2330 // Substitute the current template arguments.
2331 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2332 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2333 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2334
2335 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2336 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2337 return 0;
2338
2339 // Check that the template argument list is well-formed for this template.
2340 SmallVector<TemplateArgument, 4> Converted;
2341 bool ExpansionIntoFixedList = false;
2342 if (SemaRef.CheckTemplateArgumentList(
2343 VarTemplate, VarTemplate->getLocStart(),
2344 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2345 Converted, &ExpansionIntoFixedList))
2346 return 0;
2347
2348 // Find the variable template specialization declaration that
2349 // corresponds to these arguments.
2350 void *InsertPos = 0;
2351 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2352 Converted.data(), Converted.size(), InsertPos))
2353 // If we already have a variable template specialization, return it.
2354 return VarSpec;
2355
2356 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2357 VarTemplateArgsInfo, Converted);
2358}
2359
2360Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2361 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2362 const TemplateArgumentListInfo &TemplateArgsInfo,
Richard Smith8809a0c2013-09-27 20:14:12 +00002363 llvm::ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002364
2365 // If this is the variable for an anonymous struct or union,
2366 // instantiate the anonymous struct/union type first.
2367 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2368 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2369 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2370 return 0;
2371
2372 // Do substitution on the type of the declaration
2373 TypeSourceInfo *DI =
2374 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2375 D->getTypeSpecStartLoc(), D->getDeclName());
2376 if (!DI)
2377 return 0;
2378
2379 if (DI->getType()->isFunctionType()) {
2380 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2381 << D->isStaticDataMember() << DI->getType();
2382 return 0;
2383 }
2384
2385 // Build the instantiated declaration
2386 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2387 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2388 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2389 Converted.size());
2390 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00002391 if (InsertPos)
2392 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002393
2394 // Substitute the nested name specifier, if any.
2395 if (SubstQualifier(D, Var))
2396 return 0;
2397
2398 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00002399 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002400
2401 return Var;
2402}
2403
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002404Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2405 llvm_unreachable("@defs is not supported in Objective-C++");
2406}
2407
2408Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2409 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2410 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2411 DiagnosticsEngine::Error,
2412 "cannot instantiate %0 yet");
2413 SemaRef.Diag(D->getLocation(), DiagID)
2414 << D->getDeclKindName();
2415
2416 return 0;
2417}
2418
2419Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2420 llvm_unreachable("Unexpected decl");
2421}
2422
John McCall76d824f2009-08-25 22:02:44 +00002423Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002424 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00002425 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00002426 if (D->isInvalidDecl())
2427 return 0;
2428
Douglas Gregord7e7a512009-03-17 21:15:40 +00002429 return Instantiator.Visit(D);
2430}
2431
John McCall87a44eb2009-08-20 01:44:21 +00002432/// \brief Instantiates a nested template parameter list in the current
2433/// instantiation context.
2434///
2435/// \param L The parameter list to instantiate
2436///
2437/// \returns NULL if there was an error
2438TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00002439TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00002440 // Get errors for all the parameters before bailing out.
2441 bool Invalid = false;
2442
2443 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002444 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00002445 ParamVector Params;
2446 Params.reserve(N);
2447 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2448 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002449 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00002450 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00002451 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00002452 }
2453
2454 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00002455 if (Invalid)
John McCall87a44eb2009-08-20 01:44:21 +00002456 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +00002457
2458 TemplateParameterList *InstL
2459 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2460 L->getLAngleLoc(), &Params.front(), N,
2461 L->getRAngleLoc());
2462 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00002463}
John McCall87a44eb2009-08-20 01:44:21 +00002464
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002465/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002466/// specialization.
2467///
2468/// \param ClassTemplate the (instantiated) class template that is partially
2469// specialized by the instantiation of \p PartialSpec.
2470///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002471/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002472/// specialization that we are instantiating.
2473///
Douglas Gregor869853e2010-11-10 19:44:59 +00002474/// \returns The instantiated partial specialization, if successful; otherwise,
2475/// NULL to indicate an error.
2476ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00002477TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2478 ClassTemplateDecl *ClassTemplate,
2479 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00002480 // Create a local instantiation scope for this class template partial
2481 // specialization, which will contain the instantiations of the template
2482 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00002483 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002484
Douglas Gregor21610382009-10-29 00:04:11 +00002485 // Substitute into the template parameters of the class template partial
2486 // specialization.
2487 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2488 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2489 if (!InstParams)
Douglas Gregor869853e2010-11-10 19:44:59 +00002490 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002491
Douglas Gregor21610382009-10-29 00:04:11 +00002492 // Substitute into the template arguments of the class template partial
2493 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002494 const ASTTemplateArgumentListInfo *TemplArgInfo
2495 = PartialSpec->getTemplateArgsAsWritten();
2496 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2497 TemplArgInfo->RAngleLoc);
2498 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2499 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002500 InstTemplateArgs, TemplateArgs))
2501 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002502
Douglas Gregor21610382009-10-29 00:04:11 +00002503 // Check that the template argument list is well-formed for this
2504 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002505 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002506 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00002507 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002508 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002509 false,
2510 Converted))
Douglas Gregor869853e2010-11-10 19:44:59 +00002511 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002512
2513 // Figure out where to insert this class template partial specialization
2514 // in the member template's set of class template partial specializations.
Douglas Gregor21610382009-10-29 00:04:11 +00002515 void *InsertPos = 0;
2516 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002517 = ClassTemplate->findPartialSpecialization(Converted.data(),
2518 Converted.size(), InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002519
Douglas Gregor21610382009-10-29 00:04:11 +00002520 // Build the canonical type that describes the converted template
2521 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002522 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00002523 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002524 Converted.data(),
2525 Converted.size());
Douglas Gregor21610382009-10-29 00:04:11 +00002526
2527 // Build the fully-sugared type for this class template
2528 // specialization as the user wrote in the specialization
2529 // itself. This means that we'll pretty-print the type retrieved
2530 // from the specialization's declaration the way that the user
2531 // actually wrote the specialization, rather than formatting the
2532 // name based on the "canonical" representation used to store the
2533 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00002534 TypeSourceInfo *WrittenTy
2535 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2536 TemplateName(ClassTemplate),
2537 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002538 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002539 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002540
Douglas Gregor21610382009-10-29 00:04:11 +00002541 if (PrevDecl) {
2542 // We've already seen a partial specialization with the same template
2543 // parameters and template arguments. This can happen, for example, when
2544 // substituting the outer template arguments ends up causing two
2545 // class template partial specializations of a member class template
2546 // to have identical forms, e.g.,
2547 //
2548 // template<typename T, typename U>
2549 // struct Outer {
2550 // template<typename X, typename Y> struct Inner;
2551 // template<typename Y> struct Inner<T, Y>;
2552 // template<typename Y> struct Inner<U, Y>;
2553 // };
2554 //
2555 // Outer<int, int> outer; // error: the partial specializations of Inner
2556 // // have the same signature.
2557 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00002558 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00002559 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2560 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregor869853e2010-11-10 19:44:59 +00002561 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002562 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002563
2564
Douglas Gregor21610382009-10-29 00:04:11 +00002565 // Create the class template partial specialization declaration.
2566 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002567 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002568 PartialSpec->getTagKind(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002569 Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002570 PartialSpec->getLocStart(),
2571 PartialSpec->getLocation(),
Douglas Gregor21610382009-10-29 00:04:11 +00002572 InstParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002573 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002574 Converted.data(),
2575 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00002576 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00002577 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00002578 0);
John McCall3e11ebe2010-03-15 10:12:16 +00002579 // Substitute the nested name specifier, if any.
2580 if (SubstQualifier(PartialSpec, InstPartialSpec))
2581 return 0;
2582
Douglas Gregor21610382009-10-29 00:04:11 +00002583 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00002584 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002585
Douglas Gregor21610382009-10-29 00:04:11 +00002586 // Add this partial specialization to the set of class template partial
2587 // specializations.
Douglas Gregorce9978f2012-03-28 14:34:23 +00002588 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregor869853e2010-11-10 19:44:59 +00002589 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00002590}
2591
Larisse Voufo39a1e502013-08-06 01:03:05 +00002592/// \brief Instantiate the declaration of a variable template partial
2593/// specialization.
2594///
2595/// \param VarTemplate the (instantiated) variable template that is partially
2596/// specialized by the instantiation of \p PartialSpec.
2597///
2598/// \param PartialSpec the (uninstantiated) variable template partial
2599/// specialization that we are instantiating.
2600///
2601/// \returns The instantiated partial specialization, if successful; otherwise,
2602/// NULL to indicate an error.
2603VarTemplatePartialSpecializationDecl *
2604TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2605 VarTemplateDecl *VarTemplate,
2606 VarTemplatePartialSpecializationDecl *PartialSpec) {
2607 // Create a local instantiation scope for this variable template partial
2608 // specialization, which will contain the instantiations of the template
2609 // parameters.
2610 LocalInstantiationScope Scope(SemaRef);
2611
2612 // Substitute into the template parameters of the variable template partial
2613 // specialization.
2614 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2615 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2616 if (!InstParams)
2617 return 0;
2618
2619 // Substitute into the template arguments of the variable template partial
2620 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002621 const ASTTemplateArgumentListInfo *TemplArgInfo
2622 = PartialSpec->getTemplateArgsAsWritten();
2623 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2624 TemplArgInfo->RAngleLoc);
2625 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2626 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002627 InstTemplateArgs, TemplateArgs))
2628 return 0;
2629
2630 // Check that the template argument list is well-formed for this
2631 // class template.
2632 SmallVector<TemplateArgument, 4> Converted;
2633 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2634 InstTemplateArgs, false, Converted))
2635 return 0;
2636
2637 // Figure out where to insert this variable template partial specialization
2638 // in the member template's set of variable template partial specializations.
2639 void *InsertPos = 0;
2640 VarTemplateSpecializationDecl *PrevDecl =
2641 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2642 InsertPos);
2643
2644 // Build the canonical type that describes the converted template
2645 // arguments of the variable template partial specialization.
2646 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2647 TemplateName(VarTemplate), Converted.data(), Converted.size());
2648
2649 // Build the fully-sugared type for this variable template
2650 // specialization as the user wrote in the specialization
2651 // itself. This means that we'll pretty-print the type retrieved
2652 // from the specialization's declaration the way that the user
2653 // actually wrote the specialization, rather than formatting the
2654 // name based on the "canonical" representation used to store the
2655 // template arguments in the specialization.
2656 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2657 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2658 CanonType);
2659
2660 if (PrevDecl) {
2661 // We've already seen a partial specialization with the same template
2662 // parameters and template arguments. This can happen, for example, when
2663 // substituting the outer template arguments ends up causing two
2664 // variable template partial specializations of a member variable template
2665 // to have identical forms, e.g.,
2666 //
2667 // template<typename T, typename U>
2668 // struct Outer {
2669 // template<typename X, typename Y> pair<X,Y> p;
2670 // template<typename Y> pair<T, Y> p;
2671 // template<typename Y> pair<U, Y> p;
2672 // };
2673 //
2674 // Outer<int, int> outer; // error: the partial specializations of Inner
2675 // // have the same signature.
2676 SemaRef.Diag(PartialSpec->getLocation(),
2677 diag::err_var_partial_spec_redeclared)
2678 << WrittenTy->getType();
2679 SemaRef.Diag(PrevDecl->getLocation(),
2680 diag::note_var_prev_partial_spec_here);
2681 return 0;
2682 }
2683
2684 // Do substitution on the type of the declaration
2685 TypeSourceInfo *DI = SemaRef.SubstType(
2686 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2687 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2688 if (!DI)
2689 return 0;
2690
2691 if (DI->getType()->isFunctionType()) {
2692 SemaRef.Diag(PartialSpec->getLocation(),
2693 diag::err_variable_instantiates_to_function)
2694 << PartialSpec->isStaticDataMember() << DI->getType();
2695 return 0;
2696 }
2697
2698 // Create the variable template partial specialization declaration.
2699 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2700 VarTemplatePartialSpecializationDecl::Create(
2701 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2702 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2703 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smithb2f61b42013-08-22 23:27:37 +00002704 Converted.size(), InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002705
2706 // Substitute the nested name specifier, if any.
2707 if (SubstQualifier(PartialSpec, InstPartialSpec))
2708 return 0;
2709
2710 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2711 InstPartialSpec->setTypeAsWritten(WrittenTy);
2712
Larisse Voufo39a1e502013-08-06 01:03:05 +00002713 // Add this partial specialization to the set of variable template partial
2714 // specializations. The instantiation of the initializer is not necessary.
2715 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002716
Larisse Voufo4cda4612013-08-22 00:28:27 +00002717 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00002718 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002719
Larisse Voufo39a1e502013-08-06 01:03:05 +00002720 return InstPartialSpec;
2721}
2722
John McCall58f10c32010-03-11 09:03:00 +00002723TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00002724TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002725 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00002726 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2727 assert(OldTInfo && "substituting function without type source info");
2728 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregor3024f072012-04-16 07:05:22 +00002729
2730 CXXRecordDecl *ThisContext = 0;
2731 unsigned ThisTypeQuals = 0;
2732 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002733 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00002734 ThisTypeQuals = Method->getTypeQualifiers();
2735 }
2736
John McCallb29f78f2010-04-09 17:38:44 +00002737 TypeSourceInfo *NewTInfo
2738 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2739 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002740 D->getDeclName(),
2741 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00002742 if (!NewTInfo)
2743 return 0;
Douglas Gregor21342092009-03-24 00:38:23 +00002744
Reid Klecknera09e44c2013-07-31 21:00:18 +00002745 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2746 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2747 if (NewTInfo != OldTInfo) {
2748 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00002749 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00002750 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00002751 unsigned NewIdx = 0;
David Blaikie6adc78e2013-02-18 22:06:02 +00002752 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregorf3010112011-01-07 16:43:16 +00002753 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002754 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00002755 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2756
David Blaikie05785d12013-02-20 22:23:23 +00002757 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00002758 if (OldParam->isParameterPack())
2759 NumArgumentsInExpansion =
2760 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2761 TemplateArgs);
2762 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002763 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00002764 // instantiated to a (still-dependent) parameter pack.
David Blaikie6adc78e2013-02-18 22:06:02 +00002765 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00002766 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00002767 Scope->InstantiatedLocal(OldParam, NewParam);
2768 } else {
2769 // Parameter pack expansion: make the instantiation an argument pack.
2770 Scope->MakeInstantiatedLocalArgPack(OldParam);
2771 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002772 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00002773 Params.push_back(NewParam);
2774 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2775 }
Douglas Gregorf3010112011-01-07 16:43:16 +00002776 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002777 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002778 } else {
2779 // The function type itself was not dependent and therefore no
2780 // substitution occurred. However, we still need to instantiate
2781 // the function parameters themselves.
2782 const FunctionProtoType *OldProto =
2783 cast<FunctionProtoType>(OldProtoLoc.getType());
David Blaikie6adc78e2013-02-18 22:06:02 +00002784 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00002785 ParmVarDecl *OldParam = OldProtoLoc.getArg(i);
2786 if (!OldParam) {
2787 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2788 D, D->getLocation(), OldProto->getArgType(i)));
2789 continue;
2790 }
2791
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002792 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00002793 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002794 if (!Parm)
2795 return 0;
2796 Params.push_back(Parm);
2797 }
Douglas Gregor940bca72010-04-12 07:48:19 +00002798 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002799 } else {
2800 // If the type of this function, after ignoring parentheses, is not
2801 // *directly* a function type, then we're instantiating a function that
2802 // was declared via a typedef or with attributes, e.g.,
2803 //
2804 // typedef int functype(int, int);
2805 // functype func;
2806 // int __cdecl meth(int, int);
2807 //
2808 // In this case, we'll just go instantiate the ParmVarDecls that we
2809 // synthesized in the method declaration.
2810 SmallVector<QualType, 4> ParamTypes;
2811 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2812 D->getNumParams(), TemplateArgs, ParamTypes,
2813 &Params))
2814 return 0;
Douglas Gregor940bca72010-04-12 07:48:19 +00002815 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002816
John McCall58f10c32010-03-11 09:03:00 +00002817 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00002818}
2819
Richard Smithf623c962012-04-17 00:58:00 +00002820/// Introduce the instantiated function parameters into the local
2821/// instantiation scope, and set the parameter names to those used
2822/// in the template.
2823static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2824 const FunctionDecl *PatternDecl,
2825 LocalInstantiationScope &Scope,
2826 const MultiLevelTemplateArgumentList &TemplateArgs) {
2827 unsigned FParamIdx = 0;
2828 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2829 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2830 if (!PatternParam->isParameterPack()) {
2831 // Simple case: not a parameter pack.
2832 assert(FParamIdx < Function->getNumParams());
2833 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2834 FunctionParam->setDeclName(PatternParam->getDeclName());
2835 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2836 ++FParamIdx;
2837 continue;
2838 }
2839
2840 // Expand the parameter pack.
2841 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00002842 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00002843 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00002844 assert(NumArgumentsInExpansion &&
2845 "should only be called when all template arguments are known");
2846 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00002847 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2848 FunctionParam->setDeclName(PatternParam->getDeclName());
2849 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2850 ++FParamIdx;
2851 }
2852 }
2853}
2854
2855static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2856 const FunctionProtoType *Proto,
2857 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smithd3729422012-04-19 00:08:28 +00002858 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2859
Richard Smithf623c962012-04-17 00:58:00 +00002860 // C++11 [expr.prim.general]p3:
2861 // If a declaration declares a member function or member function
2862 // template of a class X, the expression this is a prvalue of type
2863 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2864 // and the end of the function-definition, member-declarator, or
2865 // declarator.
2866 CXXRecordDecl *ThisContext = 0;
2867 unsigned ThisTypeQuals = 0;
2868 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2869 ThisContext = Method->getParent();
2870 ThisTypeQuals = Method->getTypeQualifiers();
2871 }
2872 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002873 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithf623c962012-04-17 00:58:00 +00002874
2875 // The function has an exception specification or a "noreturn"
2876 // attribute. Substitute into each of the exception types.
2877 SmallVector<QualType, 4> Exceptions;
2878 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2879 // FIXME: Poor location information!
2880 if (const PackExpansionType *PackExpansion
2881 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2882 // We have a pack expansion. Instantiate it.
2883 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2884 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2885 Unexpanded);
2886 assert(!Unexpanded.empty() &&
2887 "Pack expansion without parameter packs?");
2888
2889 bool Expand = false;
2890 bool RetainExpansion = false;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002891 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithf623c962012-04-17 00:58:00 +00002892 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2893 SourceRange(),
2894 Unexpanded,
2895 TemplateArgs,
2896 Expand,
2897 RetainExpansion,
2898 NumExpansions))
2899 break;
2900
2901 if (!Expand) {
2902 // We can't expand this pack expansion into separate arguments yet;
2903 // just substitute into the pattern and create a new pack expansion
2904 // type.
2905 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2906 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2907 TemplateArgs,
2908 New->getLocation(), New->getDeclName());
2909 if (T.isNull())
2910 break;
2911
2912 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2913 Exceptions.push_back(T);
2914 continue;
2915 }
2916
2917 // Substitute into the pack expansion pattern for each template
2918 bool Invalid = false;
2919 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2920 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2921
2922 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2923 TemplateArgs,
2924 New->getLocation(), New->getDeclName());
2925 if (T.isNull()) {
2926 Invalid = true;
2927 break;
2928 }
2929
2930 Exceptions.push_back(T);
2931 }
2932
2933 if (Invalid)
2934 break;
2935
2936 continue;
2937 }
2938
2939 QualType T
2940 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2941 New->getLocation(), New->getDeclName());
2942 if (T.isNull() ||
2943 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2944 continue;
2945
2946 Exceptions.push_back(T);
2947 }
2948 Expr *NoexceptExpr = 0;
2949 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2950 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2951 Sema::ConstantEvaluated);
2952 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2953 if (E.isUsable())
2954 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2955
2956 if (E.isUsable()) {
2957 NoexceptExpr = E.take();
2958 if (!NoexceptExpr->isTypeDependent() &&
2959 !NoexceptExpr->isValueDependent())
Douglas Gregore2b37442012-05-04 22:38:52 +00002960 NoexceptExpr
2961 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2962 0, diag::err_noexcept_needs_constant_expression,
2963 /*AllowFold*/ false).take();
Richard Smithf623c962012-04-17 00:58:00 +00002964 }
2965 }
2966
2967 // Rebuild the function type
2968 const FunctionProtoType *NewProto
2969 = New->getType()->getAs<FunctionProtoType>();
2970 assert(NewProto && "Template instantiation without function prototype?");
2971
2972 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2973 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2974 EPI.NumExceptions = Exceptions.size();
2975 EPI.Exceptions = Exceptions.data();
2976 EPI.NoexceptExpr = NoexceptExpr;
2977
2978 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00002979 NewProto->getArgTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00002980}
2981
2982void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2983 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00002984 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2985 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00002986 return;
2987
2988 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2989 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00002990 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00002991 // We hit the instantiation depth limit. Clear the exception specification
2992 // so that our callers don't have to cope with EST_Uninstantiated.
2993 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2994 EPI.ExceptionSpecType = EST_None;
2995 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00002996 Proto->getArgTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00002997 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00002998 }
Richard Smithf623c962012-04-17 00:58:00 +00002999
3000 // Enter the scope of this instantiation. We don't use
3001 // PushDeclContext because we don't have a scope.
3002 Sema::ContextRAII savedContext(*this, Decl);
3003 LocalInstantiationScope Scope(*this);
3004
3005 MultiLevelTemplateArgumentList TemplateArgs =
3006 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
3007
Richard Smithd3729422012-04-19 00:08:28 +00003008 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3009 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003010
Richard Smithd3729422012-04-19 00:08:28 +00003011 ::InstantiateExceptionSpec(*this, Decl,
3012 Template->getType()->castAs<FunctionProtoType>(),
3013 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003014}
3015
Mike Stump11289f42009-09-09 15:08:12 +00003016/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003017/// declaration (New) from the corresponding fields of its template (Tmpl).
3018///
3019/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003020bool
3021TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003022 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003023 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003024 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003025
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003026 // If we are performing substituting explicitly-specified template arguments
3027 // or deduced template arguments into a function template and we reach this
3028 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003029 // to keeping the new function template specialization. We therefore
3030 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003031 // into a template instantiation for this specific function template
3032 // specialization, which is not a SFINAE context, so that we diagnose any
3033 // further errors in the declaration itself.
3034 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3035 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3036 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3037 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003038 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003039 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003040 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003041 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003042 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003043 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003044 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003045 }
3046 }
Mike Stump11289f42009-09-09 15:08:12 +00003047
Douglas Gregor049bdca2009-12-08 17:45:32 +00003048 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3049 assert(Proto && "Function template without prototype?");
3050
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003051 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003052 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003053
Richard Smithf623c962012-04-17 00:58:00 +00003054 // DR1330: In C++11, defer instantiation of a non-trivial
3055 // exception specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003056 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithf623c962012-04-17 00:58:00 +00003057 EPI.ExceptionSpecType != EST_None &&
3058 EPI.ExceptionSpecType != EST_DynamicNone &&
3059 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smithd3729422012-04-19 00:08:28 +00003060 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3061 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3062 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003063 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3064 if (EPI.ExceptionSpecType == EST_Unevaluated)
3065 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003066
Richard Smithf623c962012-04-17 00:58:00 +00003067 // Mark the function has having an uninstantiated exception specification.
3068 const FunctionProtoType *NewProto
3069 = New->getType()->getAs<FunctionProtoType>();
3070 assert(NewProto && "Template instantiation without function prototype?");
3071 EPI = NewProto->getExtProtoInfo();
Richard Smith185be182013-04-10 05:48:59 +00003072 EPI.ExceptionSpecType = NewEST;
Richard Smithf623c962012-04-17 00:58:00 +00003073 EPI.ExceptionSpecDecl = New;
Richard Smithd3729422012-04-19 00:08:28 +00003074 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003075 New->setType(SemaRef.Context.getFunctionType(
3076 NewProto->getResultType(), NewProto->getArgTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003077 } else {
3078 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3079 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003080 }
3081
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003082 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003083 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003084 Tmpl->isDefined(Definition);
3085
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003086 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3087 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003088
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003089 return false;
3090}
3091
Douglas Gregor21342092009-03-24 00:38:23 +00003092/// \brief Initializes common fields of an instantiated method
3093/// declaration (New) from the corresponding fields of its template
3094/// (Tmpl).
3095///
3096/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003097bool
3098TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003099 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003100 if (InitFunctionInstantiation(New, Tmpl))
3101 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003102
Douglas Gregor21342092009-03-24 00:38:23 +00003103 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003104 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003105 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003106
Douglas Gregor21342092009-03-24 00:38:23 +00003107 // FIXME: New needs a pointer to Tmpl
3108 return false;
3109}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003110
3111/// \brief Instantiate the definition of the given function from its
3112/// template.
3113///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003114/// \param PointOfInstantiation the point at which the instantiation was
3115/// required. Note that this is not precisely a "point of instantiation"
3116/// for the function, but it's close.
3117///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003118/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003119/// function template specialization or member function of a class template
3120/// specialization.
3121///
3122/// \param Recursive if true, recursively instantiates any functions that
3123/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003124///
3125/// \param DefinitionRequired if true, then we are performing an explicit
3126/// instantiation where the body of the function is required. Complain if
3127/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003128void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003129 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003130 bool Recursive,
3131 bool DefinitionRequired) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003132 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00003133 return;
3134
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003135 // Never instantiate an explicit specialization except if it is a class scope
3136 // explicit specialization.
3137 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3138 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003139 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003140
Douglas Gregor24c332b2009-05-14 21:06:31 +00003141 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003142 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003143 assert(PatternDecl && "instantiating a non-template");
3144
3145 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3146 assert(PatternDecl && "template definition is not a template");
3147 if (!Pattern) {
3148 // Try to find a defaulted definition
3149 PatternDecl->isDefined(PatternDecl);
Alexis Hunt92a0adf2011-05-25 22:02:25 +00003150 }
Alexis Hunt23f6b832011-05-27 20:00:14 +00003151 assert(PatternDecl && "template definition is not a template");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003152
Francois Pichet1c229c02011-04-22 22:18:13 +00003153 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003154 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003155 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00003156 PendingInstantiations.push_back(
3157 std::make_pair(Function, PointOfInstantiation));
3158 return;
3159 }
3160
David Majnemerf0a84f22013-08-16 08:29:13 +00003161 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003162 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003163 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003164 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003165 // FIXME: Optimize to allow individual templates to be deserialized.
3166 if (PatternDecl->isFromASTFile())
3167 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3168
3169 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3170 assert(LPT && "missing LateParsedTemplate");
3171 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet1c229c02011-04-22 22:18:13 +00003172 Pattern = PatternDecl->getBody(PatternDecl);
3173 }
3174
Alexis Hunt23f6b832011-05-27 20:00:14 +00003175 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003176 if (DefinitionRequired) {
3177 if (Function->getPrimaryTemplate())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003178 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003179 diag::err_explicit_instantiation_undefined_func_template)
3180 << Function->getPrimaryTemplate();
3181 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003182 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003183 diag::err_explicit_instantiation_undefined_member)
3184 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003185
Douglas Gregora8b89d22009-10-15 14:05:49 +00003186 if (PatternDecl)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003187 Diag(PatternDecl->getLocation(),
Douglas Gregora8b89d22009-10-15 14:05:49 +00003188 diag::note_explicit_instantiation_here);
Douglas Gregorfd7224f2010-05-17 17:57:54 +00003189 Function->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003190 } else if (Function->getTemplateSpecializationKind()
3191 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003192 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003193 std::make_pair(Function, PointOfInstantiation));
Douglas Gregora8b89d22009-10-15 14:05:49 +00003194 }
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003195
Douglas Gregor24c332b2009-05-14 21:06:31 +00003196 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00003197 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003198
Richard Smith2a7d4812013-05-04 07:00:32 +00003199 // C++1y [temp.explicit]p10:
3200 // Except for inline functions, declarations with types deduced from their
3201 // initializer or return value, and class template specializations, other
3202 // explicit instantiation declarations have the effect of suppressing the
3203 // implicit instantiation of the entity to which they refer.
Mike Stump11289f42009-09-09 15:08:12 +00003204 if (Function->getTemplateSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003205 == TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003206 !PatternDecl->isInlined() &&
Richard Smithc58f38f2013-08-14 20:16:31 +00003207 !PatternDecl->getResultType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003208 return;
Mike Stump11289f42009-09-09 15:08:12 +00003209
Richard Smithf3814ad2013-01-25 00:08:28 +00003210 if (PatternDecl->isInlined())
3211 Function->setImplicitlyInline();
3212
Douglas Gregor85673582009-05-18 17:01:57 +00003213 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003214 if (Inst.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003215 return;
3216
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00003217 // Copy the inner loc start from the pattern.
3218 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3219
Douglas Gregordda7ced2009-06-30 17:20:14 +00003220 // If we're performing recursive template instantiation, create our own
3221 // queue of pending implicit instantiations that we will instantiate later,
3222 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003223 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003224 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Faisal Vali18d35982013-06-26 02:34:24 +00003225 std::deque<PendingImplicitInstantiation>
3226 SavedPendingLocalImplicitInstantiations;
3227 SavedPendingLocalImplicitInstantiations.swap(
3228 PendingLocalImplicitInstantiations);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003229 if (Recursive) {
3230 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003231 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003232 }
Mike Stump11289f42009-09-09 15:08:12 +00003233
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003234 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00003235 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00003236
Douglas Gregorb4850462009-05-14 23:26:13 +00003237 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003238 // recorded, unless we're actually a member function within a local
3239 // class, in which case we need to merge our results with the parent
3240 // scope (of the enclosing function).
3241 bool MergeWithParentScope = false;
3242 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3243 MergeWithParentScope = Rec->isLocalClass();
3244
3245 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00003246
Richard Smithbd305122012-12-11 01:14:52 +00003247 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003248 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00003249 else {
3250 ActOnStartOfFunctionDef(0, Function);
3251
3252 // Enter the scope of this instantiation. We don't use
3253 // PushDeclContext because we don't have a scope.
3254 Sema::ContextRAII savedContext(*this, Function);
3255
3256 MultiLevelTemplateArgumentList TemplateArgs =
3257 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3258
3259 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3260 TemplateArgs);
3261
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003262 // If this is a constructor, instantiate the member initializers.
3263 if (const CXXConstructorDecl *Ctor =
3264 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3265 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3266 TemplateArgs);
3267 }
3268
3269 // Instantiate the function body.
3270 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3271
3272 if (Body.isInvalid())
3273 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003274
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003275 ActOnFinishFunctionBody(Function, Body.get(),
3276 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00003277
3278 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3279
3280 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00003281 }
3282
Douglas Gregor28ad4b52009-05-26 20:50:29 +00003283 DeclGroupRef DG(Function);
3284 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003285
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003286 // This class may have local implicit instantiations that need to be
3287 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003288 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003289 Scope.Exit();
3290
Douglas Gregordda7ced2009-06-30 17:20:14 +00003291 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003292 // Define any pending vtables.
3293 DefineUsedVTables();
3294
Douglas Gregordda7ced2009-06-30 17:20:14 +00003295 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003296 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003297 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003298
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003299 // Restore the set of pending vtables.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003300 assert(VTableUses.empty() &&
3301 "VTableUses should be empty before it is discarded.");
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003302 VTableUses.swap(SavedVTableUses);
3303
Douglas Gregordda7ced2009-06-30 17:20:14 +00003304 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003305 assert(PendingInstantiations.empty() &&
3306 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003307 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregordda7ced2009-06-30 17:20:14 +00003308 }
Faisal Vali18d35982013-06-26 02:34:24 +00003309 SavedPendingLocalImplicitInstantiations.swap(
3310 PendingLocalImplicitInstantiations);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003311}
3312
Larisse Voufo39a1e502013-08-06 01:03:05 +00003313VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3314 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3315 const TemplateArgumentList &TemplateArgList,
3316 const TemplateArgumentListInfo &TemplateArgsInfo,
3317 SmallVectorImpl<TemplateArgument> &Converted,
3318 SourceLocation PointOfInstantiation, void *InsertPos,
3319 LateInstantiatedAttrVec *LateAttrs,
3320 LocalInstantiationScope *StartingScope) {
3321 if (FromVar->isInvalidDecl())
3322 return 0;
3323
3324 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003325 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003326 return 0;
3327
3328 MultiLevelTemplateArgumentList TemplateArgLists;
3329 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3330
Richard Smith8809a0c2013-09-27 20:14:12 +00003331 // Instantiate the first declaration of the variable template: for a partial
3332 // specialization of a static data member template, the first declaration may
3333 // or may not be the declaration in the class; if it's in the class, we want
3334 // to instantiate a member in the class (a declaration), and if it's outside,
3335 // we want to instantiate a definition.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003336 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00003337
Manuel Klimek5843add2013-09-30 13:29:01 +00003338 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3339 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3340 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003341
3342 // TODO: Set LateAttrs and StartingScope ...
3343
3344 return cast_or_null<VarTemplateSpecializationDecl>(
3345 Instantiator.VisitVarTemplateSpecializationDecl(
3346 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3347}
3348
3349/// \brief Instantiates a variable template specialization by completing it
3350/// with appropriate type information and initializer.
3351VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3352 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3353 const MultiLevelTemplateArgumentList &TemplateArgs) {
3354
3355 // Do substitution on the type of the declaration
3356 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00003357 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003358 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3359 if (!DI)
3360 return 0;
3361
3362 // Update the type of this variable template specialization.
3363 VarSpec->setType(DI->getType());
3364
3365 // Instantiate the initializer.
3366 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3367
3368 return VarSpec;
3369}
3370
3371/// BuildVariableInstantiation - Used after a new variable has been created.
3372/// Sets basic variable data and decides whether to postpone the
3373/// variable instantiation.
3374void Sema::BuildVariableInstantiation(
3375 VarDecl *NewVar, VarDecl *OldVar,
3376 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003377 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3378 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003379 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003380
Richard Smith541b38b2013-09-20 01:15:31 +00003381 // If we are instantiating a local extern declaration, the
3382 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003383 // If we are instantiating a static data member defined
3384 // out-of-line, the instantiation will have the same lexical
3385 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00003386 if (OldVar->isLocalExternDecl()) {
3387 NewVar->setLocalExternDecl();
3388 NewVar->setLexicalDeclContext(Owner);
3389 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003390 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3391 NewVar->setTSCSpec(OldVar->getTSCSpec());
3392 NewVar->setInitStyle(OldVar->getInitStyle());
3393 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3394 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00003395 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00003396 NewVar->setPreviousDeclInSameBlockScope(
3397 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003398 NewVar->setAccess(OldVar->getAccess());
3399
Richard Smith0b551192013-09-23 23:12:22 +00003400 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00003401 if (OldVar->isUsed(false))
3402 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003403 NewVar->setReferenced(OldVar->isReferenced());
3404 }
3405
David Majnemer50ce8352013-09-17 23:57:10 +00003406 // See if the old variable had a type-specifier that defined an anonymous tag.
3407 // If it did, mark the new variable as being the declarator for the new
3408 // anonymous tag.
3409 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3410 TagDecl *OldTag = OldTagType->getDecl();
3411 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3412 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3413 assert(!NewTag->hasNameForLinkage() &&
3414 !NewTag->hasDeclaratorForAnonDecl());
3415 NewTag->setDeclaratorForAnonDecl(NewVar);
3416 }
3417 }
3418
Larisse Voufo39a1e502013-08-06 01:03:05 +00003419 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3420
3421 if (NewVar->hasAttrs())
3422 CheckAlignasUnderalignment(NewVar);
3423
Richard Smith541b38b2013-09-20 01:15:31 +00003424 LookupResult Previous(
3425 *this, NewVar->getDeclName(), NewVar->getLocation(),
3426 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3427 : Sema::LookupOrdinaryName,
3428 Sema::ForRedeclaration);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003429
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00003430 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3431 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3432 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00003433 // We have a previous declaration. Use that one, so we merge with the
3434 // right type.
3435 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3436 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3437 Previous.addDecl(NewPrev);
3438 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3439 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003440 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003441 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003442
Richard Smith541b38b2013-09-20 01:15:31 +00003443 if (!InstantiatingVarTemplate) {
3444 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3445 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003446 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00003447 }
3448
3449 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003450 if (NewVar->getDeclContext()->isFunctionOrMethod())
3451 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3452 }
3453
3454 // Link instantiations of static data members back to the template from
3455 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003456 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003457 NewVar->setInstantiationOfStaticDataMember(OldVar,
3458 TSK_ImplicitInstantiation);
3459
Richard Smith8809a0c2013-09-27 20:14:12 +00003460 // Delay instantiation of the initializer for variable templates until a
3461 // definition of the variable is needed.
3462 if (!isa<VarTemplateSpecializationDecl>(NewVar) && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003463 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3464
3465 // Diagnose unused local variables with dependent types, where the diagnostic
3466 // will have been deferred.
3467 if (!NewVar->isInvalidDecl() &&
3468 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3469 OldVar->getType()->isDependentType())
3470 DiagnoseUnusedDecl(NewVar);
3471}
3472
3473/// \brief Instantiate the initializer of a variable.
3474void Sema::InstantiateVariableInitializer(
3475 VarDecl *Var, VarDecl *OldVar,
3476 const MultiLevelTemplateArgumentList &TemplateArgs) {
3477
3478 if (Var->getAnyInitializer())
3479 // We already have an initializer in the class.
3480 return;
3481
3482 if (OldVar->getInit()) {
3483 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3484 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3485 else
3486 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3487
3488 // Instantiate the initializer.
3489 ExprResult Init =
3490 SubstInitializer(OldVar->getInit(), TemplateArgs,
3491 OldVar->getInitStyle() == VarDecl::CallInit);
3492 if (!Init.isInvalid()) {
3493 bool TypeMayContainAuto = true;
3494 if (Init.get()) {
3495 bool DirectInit = OldVar->isDirectInit();
3496 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3497 } else
3498 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3499 } else {
3500 // FIXME: Not too happy about invalidating the declaration
3501 // because of a bogus initializer.
3502 Var->setInvalidDecl();
3503 }
3504
3505 PopExpressionEvaluationContext();
3506 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3507 !Var->isCXXForRangeDecl())
3508 ActOnUninitializedDecl(Var, false);
3509}
3510
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003511/// \brief Instantiate the definition of the given variable from its
3512/// template.
3513///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003514/// \param PointOfInstantiation the point at which the instantiation was
3515/// required. Note that this is not precisely a "point of instantiation"
3516/// for the function, but it's close.
3517///
3518/// \param Var the already-instantiated declaration of a static member
3519/// variable of a class template specialization.
3520///
3521/// \param Recursive if true, recursively instantiates any functions that
3522/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003523///
3524/// \param DefinitionRequired if true, then we are performing an explicit
3525/// instantiation where an out-of-line definition of the member variable
3526/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003527void Sema::InstantiateStaticDataMemberDefinition(
3528 SourceLocation PointOfInstantiation,
3529 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003530 bool Recursive,
3531 bool DefinitionRequired) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003532 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3533 DefinitionRequired);
3534}
3535
3536void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3537 VarDecl *Var, bool Recursive,
3538 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003539 if (Var->isInvalidDecl())
3540 return;
Mike Stump11289f42009-09-09 15:08:12 +00003541
Larisse Voufo39a1e502013-08-06 01:03:05 +00003542 VarTemplateSpecializationDecl *VarSpec =
3543 dyn_cast<VarTemplateSpecializationDecl>(Var);
Richard Smith8809a0c2013-09-27 20:14:12 +00003544 VarDecl *PatternDecl = 0, *Def = 0;
3545 MultiLevelTemplateArgumentList TemplateArgs =
3546 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00003547
Larisse Voufo39a1e502013-08-06 01:03:05 +00003548 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003549 // If this is a variable template specialization, make sure that it is
3550 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003551 bool InstantiationDependent = false;
3552 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3553 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3554 "Only instantiate variable template specializations that are "
3555 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00003556 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003557
Richard Smith8809a0c2013-09-27 20:14:12 +00003558 // Find the variable initialization that we'll be substituting. If the
3559 // pattern was instantiated from a member template, look back further to
3560 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003561 assert(VarSpec->getSpecializedTemplate() &&
3562 "Specialization without specialized template?");
3563 llvm::PointerUnion<VarTemplateDecl *,
3564 VarTemplatePartialSpecializationDecl *> PatternPtr =
3565 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003566 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003567 VarTemplatePartialSpecializationDecl *Tmpl =
3568 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3569 while (VarTemplatePartialSpecializationDecl *From =
3570 Tmpl->getInstantiatedFromMember()) {
3571 if (Tmpl->isMemberSpecialization())
3572 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003573
Richard Smith8809a0c2013-09-27 20:14:12 +00003574 Tmpl = From;
3575 }
3576 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003577 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00003578 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3579 while (VarTemplateDecl *From =
3580 Tmpl->getInstantiatedFromMemberTemplate()) {
3581 if (Tmpl->isMemberSpecialization())
3582 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003583
Richard Smith8809a0c2013-09-27 20:14:12 +00003584 Tmpl = From;
3585 }
3586 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003587 }
Richard Smith8809a0c2013-09-27 20:14:12 +00003588
3589 // If this is a static data member template, there might be an
3590 // uninstantiated initializer on the declaration. If so, instantiate
3591 // it now.
3592 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00003593 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00003594 !Var->hasInit()) {
3595 // FIXME: Factor out the duplicated instantiation context setup/tear down
3596 // code here.
3597 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003598 if (Inst.isInvalid())
Richard Smith8809a0c2013-09-27 20:14:12 +00003599 return;
3600
3601 // If we're performing recursive template instantiation, create our own
3602 // queue of pending implicit instantiations that we will instantiate
3603 // later, while we're still within our own instantiation context.
3604 SmallVector<VTableUse, 16> SavedVTableUses;
3605 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3606 if (Recursive) {
3607 VTableUses.swap(SavedVTableUses);
3608 PendingInstantiations.swap(SavedPendingInstantiations);
3609 }
3610
3611 LocalInstantiationScope Local(*this);
3612
3613 // Enter the scope of this instantiation. We don't use
3614 // PushDeclContext because we don't have a scope.
3615 ContextRAII PreviousContext(*this, Var->getDeclContext());
3616 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3617 PreviousContext.pop();
3618
3619 // FIXME: Need to inform the ASTConsumer that we instantiated the
3620 // initializer?
3621
3622 // This variable may have local implicit instantiations that need to be
3623 // instantiated within this scope.
3624 PerformPendingInstantiations(/*LocalOnly=*/true);
3625
3626 Local.Exit();
3627
3628 if (Recursive) {
3629 // Define any newly required vtables.
3630 DefineUsedVTables();
3631
3632 // Instantiate any pending implicit instantiations found during the
3633 // instantiation of this template.
3634 PerformPendingInstantiations();
3635
3636 // Restore the set of pending vtables.
3637 assert(VTableUses.empty() &&
3638 "VTableUses should be empty before it is discarded.");
3639 VTableUses.swap(SavedVTableUses);
3640
3641 // Restore the set of pending implicit instantiations.
3642 assert(PendingInstantiations.empty() &&
3643 "PendingInstantiations should be empty before it is discarded.");
3644 PendingInstantiations.swap(SavedPendingInstantiations);
3645 }
3646 }
3647
3648 // Find actual definition
3649 Def = PatternDecl->getDefinition(getASTContext());
3650 } else {
3651 // If this is a static data member, find its out-of-line definition.
3652 assert(Var->isStaticDataMember() && "not a static data member?");
3653 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3654
3655 assert(PatternDecl && "data member was not instantiated from a template?");
3656 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3657 Def = PatternDecl->getOutOfLineDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003658 }
3659
Richard Smith8809a0c2013-09-27 20:14:12 +00003660 // If we don't have a definition of the variable template, we won't perform
3661 // any instantiation. Rather, we rely on the user to instantiate this
3662 // definition (or provide a specialization for it) in another translation
3663 // unit.
3664 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003665 if (DefinitionRequired) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003666 if (VarSpec)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003667 Diag(PointOfInstantiation,
Richard Smith8809a0c2013-09-27 20:14:12 +00003668 diag::err_explicit_instantiation_undefined_var_template) << Var;
3669 else
Larisse Voufo39a1e502013-08-06 01:03:05 +00003670 Diag(PointOfInstantiation,
3671 diag::err_explicit_instantiation_undefined_member)
Richard Smith8809a0c2013-09-27 20:14:12 +00003672 << 2 << Var->getDeclName() << Var->getDeclContext();
3673 Diag(PatternDecl->getLocation(),
3674 diag::note_explicit_instantiation_here);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003675 if (VarSpec)
3676 Var->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003677 } else if (Var->getTemplateSpecializationKind()
3678 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003679 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003680 std::make_pair(Var, PointOfInstantiation));
3681 }
3682
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003683 return;
3684 }
3685
Rafael Espindola189fa742012-03-05 10:54:55 +00003686 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3687
Douglas Gregor86d142a2009-10-08 07:24:58 +00003688 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00003689 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003690 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003691
Larisse Voufo39a1e502013-08-06 01:03:05 +00003692 // C++11 [temp.explicit]p10:
3693 // Except for inline functions, [...] explicit instantiation declarations
3694 // have the effect of suppressing the implicit instantiation of the entity
3695 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00003696 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003697 return;
Mike Stump11289f42009-09-09 15:08:12 +00003698
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003699 // Make sure to pass the instantiated variable to the consumer at the end.
3700 struct PassToConsumerRAII {
3701 ASTConsumer &Consumer;
3702 VarDecl *Var;
3703
3704 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3705 : Consumer(Consumer), Var(Var) { }
3706
3707 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00003708 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003709 }
3710 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003711
Richard Smith8809a0c2013-09-27 20:14:12 +00003712 // If we already have a definition, we're done.
3713 if (VarDecl *Def = Var->getDefinition()) {
3714 // We may be explicitly instantiating something we've already implicitly
3715 // instantiated.
3716 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3717 PointOfInstantiation);
3718 return;
Nick Lewyckya995a472012-04-04 02:38:36 +00003719 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00003720
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003721 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003722 if (Inst.isInvalid())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003723 return;
Mike Stump11289f42009-09-09 15:08:12 +00003724
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003725 // If we're performing recursive template instantiation, create our own
3726 // queue of pending implicit instantiations that we will instantiate later,
3727 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003728 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003729 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003730 if (Recursive) {
3731 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003732 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003733 }
Mike Stump11289f42009-09-09 15:08:12 +00003734
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003735 // Enter the scope of this instantiation. We don't use
3736 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003737 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00003738 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00003739
Larisse Voufo39a1e502013-08-06 01:03:05 +00003740 VarDecl *OldVar = Var;
3741 if (!VarSpec)
3742 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00003743 TemplateArgs));
3744 else if (Var->isStaticDataMember() &&
3745 Var->getLexicalDeclContext()->isRecord()) {
3746 // We need to instantiate the definition of a static data member template,
3747 // and all we have is the in-class declaration of it. Instantiate a separate
3748 // declaration of the definition.
3749 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3750 TemplateArgs);
3751 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3752 VarSpec->getSpecializedTemplate(), Def, 0,
3753 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3754 if (Var) {
3755 llvm::PointerUnion<VarTemplateDecl *,
3756 VarTemplatePartialSpecializationDecl *> PatternPtr =
3757 VarSpec->getSpecializedTemplateOrPartial();
3758 if (VarTemplatePartialSpecializationDecl *Partial =
3759 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3760 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3761 Partial, &VarSpec->getTemplateInstantiationArgs());
3762
3763 // Merge the definition with the declaration.
3764 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3765 LookupOrdinaryName, ForRedeclaration);
3766 R.addDecl(OldVar);
3767 MergeVarDecl(Var, R);
3768
3769 // Attach the initializer.
3770 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3771 }
3772 } else
3773 // Complete the existing variable's definition with an appropriately
3774 // substituted type and initializer.
3775 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003776
3777 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003778
3779 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003780 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00003781 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3782 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003783 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003784
3785 // This variable may have local implicit instantiations that need to be
3786 // instantiated within this scope.
3787 PerformPendingInstantiations(/*LocalOnly=*/true);
3788
Douglas Gregora86bc002012-02-16 21:36:18 +00003789 Local.Exit();
3790
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003791 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003792 // Define any newly required vtables.
3793 DefineUsedVTables();
3794
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003795 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003796 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003797 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003798
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003799 // Restore the set of pending vtables.
3800 assert(VTableUses.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003801 "VTableUses should be empty before it is discarded.");
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003802 VTableUses.swap(SavedVTableUses);
3803
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003804 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003805 assert(PendingInstantiations.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003806 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003807 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00003808 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003809}
Douglas Gregor51783312009-05-27 05:35:12 +00003810
Anders Carlsson70553942009-08-29 05:16:22 +00003811void
3812Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3813 const CXXConstructorDecl *Tmpl,
3814 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003815
Richard Trieu9becef62011-09-09 03:18:59 +00003816 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00003817 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003818
Anders Carlsson70553942009-08-29 05:16:22 +00003819 // Instantiate all the initializers.
3820 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregora3a3f6f2009-09-01 21:04:42 +00003821 InitsEnd = Tmpl->init_end();
3822 Inits != InitsEnd; ++Inits) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003823 CXXCtorInitializer *Init = *Inits;
Anders Carlsson70553942009-08-29 05:16:22 +00003824
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00003825 // Only instantiate written initializers, let Sema re-construct implicit
3826 // ones.
3827 if (!Init->isWritten())
3828 continue;
3829
Douglas Gregor44e7df62011-01-04 00:32:56 +00003830 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003831
Douglas Gregor44e7df62011-01-04 00:32:56 +00003832 if (Init->isPackExpansion()) {
3833 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003834 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00003835 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003836 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00003837 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003838 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003839 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00003840 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003841 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003842 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00003843 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003844 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003845 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003846 NumExpansions)) {
3847 AnyErrors = true;
3848 New->setInvalidDecl();
3849 continue;
3850 }
3851 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003852
3853 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003854 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003855 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3856
3857 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00003858 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3859 /*CXXDirectInit=*/true);
3860 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003861 AnyErrors = true;
3862 break;
3863 }
3864
3865 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003866 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003867 TemplateArgs,
3868 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003869 New->getDeclName());
3870 if (!BaseTInfo) {
3871 AnyErrors = true;
3872 break;
3873 }
3874
3875 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00003876 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redla9351792012-02-11 23:51:47 +00003877 BaseTInfo, TempInit.take(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003878 New->getParent(),
3879 SourceLocation());
3880 if (NewInit.isInvalid()) {
3881 AnyErrors = true;
3882 break;
3883 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003884
Douglas Gregor44e7df62011-01-04 00:32:56 +00003885 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00003886 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003887
Douglas Gregor44e7df62011-01-04 00:32:56 +00003888 continue;
3889 }
3890
Douglas Gregorb30f22b2010-03-02 07:38:39 +00003891 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00003892 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3893 /*CXXDirectInit=*/true);
3894 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00003895 AnyErrors = true;
3896 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00003897 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003898
Anders Carlsson70553942009-08-29 05:16:22 +00003899 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003900 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3901 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3902 TemplateArgs,
3903 Init->getSourceLocation(),
3904 New->getDeclName());
3905 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003906 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003907 New->setInvalidDecl();
3908 continue;
3909 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003910
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003911 if (Init->isBaseInitializer())
Sebastian Redla9351792012-02-11 23:51:47 +00003912 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003913 New->getParent(), EllipsisLoc);
3914 else
Sebastian Redla9351792012-02-11 23:51:47 +00003915 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003916 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00003917 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00003918 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00003919 Init->getMemberLocation(),
3920 Init->getMember(),
3921 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00003922 if (!Member) {
3923 AnyErrors = true;
3924 New->setInvalidDecl();
3925 continue;
3926 }
Mike Stump11289f42009-09-09 15:08:12 +00003927
Sebastian Redla9351792012-02-11 23:51:47 +00003928 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00003929 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00003930 } else if (Init->isIndirectMemberInitializer()) {
3931 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00003932 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00003933 Init->getMemberLocation(),
3934 Init->getIndirectMember(), TemplateArgs));
3935
Douglas Gregor55e6b312011-03-04 19:46:35 +00003936 if (!IndirectMember) {
3937 AnyErrors = true;
3938 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00003939 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00003940 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003941
Sebastian Redla9351792012-02-11 23:51:47 +00003942 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00003943 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00003944 }
3945
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003946 if (NewInit.isInvalid()) {
3947 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00003948 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003949 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00003950 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00003951 }
3952 }
Mike Stump11289f42009-09-09 15:08:12 +00003953
Anders Carlsson70553942009-08-29 05:16:22 +00003954 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00003955 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00003956 /*FIXME: ColonLoc */
3957 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00003958 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003959 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00003960}
3961
John McCall59660882009-08-29 08:11:13 +00003962// TODO: this could be templated if the various decl types used the
3963// same method name.
3964static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3965 ClassTemplateDecl *Instance) {
3966 Pattern = Pattern->getCanonicalDecl();
3967
3968 do {
3969 Instance = Instance->getCanonicalDecl();
3970 if (Pattern == Instance) return true;
3971 Instance = Instance->getInstantiatedFromMemberTemplate();
3972 } while (Instance);
3973
3974 return false;
3975}
3976
Douglas Gregor14d1bf42009-09-28 06:34:35 +00003977static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3978 FunctionTemplateDecl *Instance) {
3979 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003980
Douglas Gregor14d1bf42009-09-28 06:34:35 +00003981 do {
3982 Instance = Instance->getCanonicalDecl();
3983 if (Pattern == Instance) return true;
3984 Instance = Instance->getInstantiatedFromMemberTemplate();
3985 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003986
Douglas Gregor14d1bf42009-09-28 06:34:35 +00003987 return false;
3988}
3989
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003990static bool
Douglas Gregor21610382009-10-29 00:04:11 +00003991isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3992 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003993 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00003994 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3995 do {
3996 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3997 Instance->getCanonicalDecl());
3998 if (Pattern == Instance)
3999 return true;
4000 Instance = Instance->getInstantiatedFromMember();
4001 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004002
Douglas Gregor21610382009-10-29 00:04:11 +00004003 return false;
4004}
4005
John McCall59660882009-08-29 08:11:13 +00004006static bool isInstantiationOf(CXXRecordDecl *Pattern,
4007 CXXRecordDecl *Instance) {
4008 Pattern = Pattern->getCanonicalDecl();
4009
4010 do {
4011 Instance = Instance->getCanonicalDecl();
4012 if (Pattern == Instance) return true;
4013 Instance = Instance->getInstantiatedFromMemberClass();
4014 } while (Instance);
4015
4016 return false;
4017}
4018
4019static bool isInstantiationOf(FunctionDecl *Pattern,
4020 FunctionDecl *Instance) {
4021 Pattern = Pattern->getCanonicalDecl();
4022
4023 do {
4024 Instance = Instance->getCanonicalDecl();
4025 if (Pattern == Instance) return true;
4026 Instance = Instance->getInstantiatedFromMemberFunction();
4027 } while (Instance);
4028
4029 return false;
4030}
4031
4032static bool isInstantiationOf(EnumDecl *Pattern,
4033 EnumDecl *Instance) {
4034 Pattern = Pattern->getCanonicalDecl();
4035
4036 do {
4037 Instance = Instance->getCanonicalDecl();
4038 if (Pattern == Instance) return true;
4039 Instance = Instance->getInstantiatedFromMemberEnum();
4040 } while (Instance);
4041
4042 return false;
4043}
4044
John McCallb96ec562009-12-04 22:46:56 +00004045static bool isInstantiationOf(UsingShadowDecl *Pattern,
4046 UsingShadowDecl *Instance,
4047 ASTContext &C) {
4048 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4049}
4050
4051static bool isInstantiationOf(UsingDecl *Pattern,
4052 UsingDecl *Instance,
4053 ASTContext &C) {
4054 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4055}
4056
John McCalle61f2ba2009-11-18 02:36:19 +00004057static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4058 UsingDecl *Instance,
4059 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004060 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCalle61f2ba2009-11-18 02:36:19 +00004061}
4062
4063static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004064 UsingDecl *Instance,
4065 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004066 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004067}
4068
John McCall59660882009-08-29 08:11:13 +00004069static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4070 VarDecl *Instance) {
4071 assert(Instance->isStaticDataMember());
4072
4073 Pattern = Pattern->getCanonicalDecl();
4074
4075 do {
4076 Instance = Instance->getCanonicalDecl();
4077 if (Pattern == Instance) return true;
4078 Instance = Instance->getInstantiatedFromStaticDataMember();
4079 } while (Instance);
4080
4081 return false;
4082}
4083
John McCallb96ec562009-12-04 22:46:56 +00004084// Other is the prospective instantiation
4085// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004086static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004087 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004088 if (UnresolvedUsingTypenameDecl *UUD
4089 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4090 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4091 return isInstantiationOf(UUD, UD, Ctx);
4092 }
4093 }
4094
4095 if (UnresolvedUsingValueDecl *UUD
4096 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004097 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4098 return isInstantiationOf(UUD, UD, Ctx);
4099 }
4100 }
Douglas Gregor51783312009-05-27 05:35:12 +00004101
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004102 return false;
4103 }
Mike Stump11289f42009-09-09 15:08:12 +00004104
John McCall59660882009-08-29 08:11:13 +00004105 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4106 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004107
John McCall59660882009-08-29 08:11:13 +00004108 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4109 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004110
John McCall59660882009-08-29 08:11:13 +00004111 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4112 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004113
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004114 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004115 if (Var->isStaticDataMember())
4116 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4117
4118 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4119 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004120
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004121 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4122 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4123
Douglas Gregor21610382009-10-29 00:04:11 +00004124 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4125 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4126 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4127 PartialSpec);
4128
Anders Carlsson5da84842009-09-01 04:26:58 +00004129 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4130 if (!Field->getDeclName()) {
4131 // This is an unnamed field.
Mike Stump11289f42009-09-09 15:08:12 +00004132 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlsson5da84842009-09-01 04:26:58 +00004133 cast<FieldDecl>(D);
4134 }
4135 }
Mike Stump11289f42009-09-09 15:08:12 +00004136
John McCallb96ec562009-12-04 22:46:56 +00004137 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4138 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4139
4140 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4141 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4142
Douglas Gregor51783312009-05-27 05:35:12 +00004143 return D->getDeclName() && isa<NamedDecl>(Other) &&
4144 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4145}
4146
4147template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004148static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004149 NamedDecl *D,
4150 ForwardIterator first,
4151 ForwardIterator last) {
4152 for (; first != last; ++first)
4153 if (isInstantiationOf(Ctx, D, *first))
4154 return cast<NamedDecl>(*first);
4155
4156 return 0;
4157}
4158
John McCallaa74a0c2009-08-28 07:59:38 +00004159/// \brief Finds the instantiation of the given declaration context
4160/// within the current instantiation.
4161///
4162/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004163DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004164 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004165 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004166 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00004167 return cast_or_null<DeclContext>(ID);
4168 } else return DC;
4169}
4170
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004171/// \brief Find the instantiation of the given declaration within the
4172/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004173///
4174/// This routine is intended to be used when \p D is a declaration
4175/// referenced from within a template, that needs to mapped into the
4176/// corresponding declaration within an instantiation. For example,
4177/// given:
4178///
4179/// \code
4180/// template<typename T>
4181/// struct X {
4182/// enum Kind {
4183/// KnownValue = sizeof(T)
4184/// };
4185///
4186/// bool getKind() const { return KnownValue; }
4187/// };
4188///
4189/// template struct X<int>;
4190/// \endcode
4191///
Serge Pavloved5fe902013-07-10 04:59:14 +00004192/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4193/// \p EnumConstantDecl for \p KnownValue (which refers to
4194/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4195/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4196/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004197NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00004198 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00004199 DeclContext *ParentDC = D->getDeclContext();
Faisal Vali2cba1332013-10-23 06:44:28 +00004200 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4201 // parameters (p below) can have their ParentDC set to the translation-unit
4202 // - thus we can not consistently check if the ParentDC of such a parameter
4203 // is Dependent or/and a FunctionOrMethod.
4204 // For e.g. this code, during Template argument deduction tries to
4205 // find an instantiated decl for (T y) when the ParentDC for y is
4206 // the translation unit.
4207 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4208 // float baz(float(*)()) { return 0.0; }
4209 // Foo(baz);
4210 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4211 // it gets here, always has a FunctionOrMethod as its ParentDC??
4212 // For now:
4213 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4214 // whose type is not instantiation dependent, do nothing to the decl
4215 // - otherwise find its instantiated decl.
4216 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4217 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4218 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00004219 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00004220 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00004221 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4222 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004223 // D is a local of some kind. Look into the map of local
4224 // declarations to their instantiations.
Chris Lattner50c3c132011-02-17 19:47:42 +00004225 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4226 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4227 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004228
Chris Lattnercab02a62011-02-17 20:34:02 +00004229 if (Found) {
4230 if (Decl *FD = Found->dyn_cast<Decl *>())
4231 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004232
Richard Smithb15fe3a2012-09-12 00:56:43 +00004233 int PackIdx = ArgumentPackSubstitutionIndex;
4234 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattnercab02a62011-02-17 20:34:02 +00004235 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4236 }
4237
Serge Pavlov7cd8f602013-07-15 06:14:07 +00004238 // If we're performing a partial substitution during template argument
4239 // deduction, we may not have values for template parameters yet. They
4240 // just map to themselves.
4241 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4242 isa<TemplateTemplateParmDecl>(D))
4243 return D;
4244
Serge Pavlov074a5182013-08-10 12:00:21 +00004245 if (D->isInvalidDecl())
4246 return 0;
4247
Chris Lattnercab02a62011-02-17 20:34:02 +00004248 // If we didn't find the decl, then we must have a label decl that hasn't
4249 // been found yet. Lazily instantiate it and return it now.
4250 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004251
Chris Lattnercab02a62011-02-17 20:34:02 +00004252 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4253 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004254
Chris Lattnercab02a62011-02-17 20:34:02 +00004255 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4256 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004257 }
Douglas Gregor51783312009-05-27 05:35:12 +00004258
Larisse Voufo39a1e502013-08-06 01:03:05 +00004259 // For variable template specializations, update those that are still
4260 // type-dependent.
4261 if (VarTemplateSpecializationDecl *VarSpec =
4262 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4263 bool InstantiationDependent = false;
4264 const TemplateArgumentListInfo &VarTemplateArgs =
4265 VarSpec->getTemplateArgsInfo();
4266 if (TemplateSpecializationType::anyDependentTemplateArguments(
4267 VarTemplateArgs, InstantiationDependent))
4268 D = cast<NamedDecl>(
4269 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4270 return D;
4271 }
4272
Douglas Gregor64621e62009-09-16 18:34:49 +00004273 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4274 if (!Record->isDependentContext())
4275 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004276
Douglas Gregor4109afa2011-11-07 17:43:18 +00004277 // Determine whether this record is the "templated" declaration describing
4278 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00004279 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00004280 if (ClassTemplate)
4281 ClassTemplate = ClassTemplate->getCanonicalDecl();
4282 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4283 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4284 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004285
Douglas Gregor4109afa2011-11-07 17:43:18 +00004286 // Walk the current context to find either the record or an instantiation of
4287 // it.
4288 DeclContext *DC = CurContext;
4289 while (!DC->isFileContext()) {
4290 // If we're performing substitution while we're inside the template
4291 // definition, we'll find our own context. We're done.
4292 if (DC->Equals(Record))
4293 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004294
Douglas Gregor4109afa2011-11-07 17:43:18 +00004295 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4296 // Check whether we're in the process of instantiating a class template
4297 // specialization of the template we're mapping.
4298 if (ClassTemplateSpecializationDecl *InstSpec
4299 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4300 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4301 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4302 return InstRecord;
4303 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004304
Douglas Gregor4109afa2011-11-07 17:43:18 +00004305 // Check whether we're in the process of instantiating a member class.
4306 if (isInstantiationOf(Record, InstRecord))
4307 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00004308 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004309
Douglas Gregor4109afa2011-11-07 17:43:18 +00004310 // Move to the outer template scope.
4311 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4312 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4313 DC = FD->getLexicalDeclContext();
4314 continue;
4315 }
John McCall59660882009-08-29 08:11:13 +00004316 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004317
Douglas Gregor4109afa2011-11-07 17:43:18 +00004318 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00004319 }
Douglas Gregord225fa02010-02-05 22:40:03 +00004320
Douglas Gregor64621e62009-09-16 18:34:49 +00004321 // Fall through to deal with other dependent record types (e.g.,
4322 // anonymous unions in class templates).
4323 }
John McCall59660882009-08-29 08:11:13 +00004324
Douglas Gregor64621e62009-09-16 18:34:49 +00004325 if (!ParentDC->isDependentContext())
4326 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004327
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004328 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004329 if (!ParentDC)
Douglas Gregor2ffd9652009-09-01 17:53:10 +00004330 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004331
Douglas Gregor51783312009-05-27 05:35:12 +00004332 if (ParentDC != D->getDeclContext()) {
4333 // We performed some kind of instantiation in the parent context,
4334 // so now we need to look into the instantiated parent context to
4335 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004336
John McCalle78aac42010-03-10 03:28:59 +00004337 // If our context used to be dependent, we may need to instantiate
4338 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00004339 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00004340 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004341 if (!Spec->isDependentContext()) {
4342 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00004343 const RecordType *Tag = T->getAs<RecordType>();
4344 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00004345 if (Tag->isBeingDefined())
4346 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00004347 if (!Tag->isBeingDefined() &&
4348 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4349 return 0;
Douglas Gregor25edf432010-11-05 23:22:45 +00004350
4351 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004352 }
4353 }
4354
Douglas Gregor51783312009-05-27 05:35:12 +00004355 NamedDecl *Result = 0;
4356 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004357 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00004358 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00004359 } else {
4360 // Since we don't have a name for the entity we're looking for,
4361 // our only option is to walk through all of the declarations to
4362 // find that name. This will occur in a few cases:
4363 //
4364 // - anonymous struct/union within a template
4365 // - unnamed class/struct/union/enum within a template
4366 //
4367 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00004368 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004369 ParentDC->decls_begin(),
4370 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00004371 }
Mike Stump11289f42009-09-09 15:08:12 +00004372
Douglas Gregor528ad932011-03-06 20:12:45 +00004373 if (!Result) {
4374 if (isa<UsingShadowDecl>(D)) {
4375 // UsingShadowDecls can instantiate to nothing because of using hiding.
4376 } else if (Diags.hasErrorOccurred()) {
4377 // We've already complained about something, so most likely this
4378 // declaration failed to instantiate. There's no point in complaining
4379 // further, since this is normal in invalid code.
4380 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004381 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00004382 // instantiated, and we haven't gotten around to instantiating this
4383 // member yet. This can happen when the code uses forward declarations
4384 // of member classes, and introduces ordering dependencies via
4385 // template instantiation.
4386 Diag(Loc, diag::err_member_not_yet_instantiated)
4387 << D->getDeclName()
4388 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4389 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00004390 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4391 // This enumeration constant was found when the template was defined,
4392 // but can't be found in the instantiation. This can happen if an
4393 // unscoped enumeration member is explicitly specialized.
4394 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4395 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4396 TemplateArgs));
4397 assert(Spec->getTemplateSpecializationKind() ==
4398 TSK_ExplicitSpecialization);
4399 Diag(Loc, diag::err_enumerator_does_not_exist)
4400 << D->getDeclName()
4401 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4402 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4403 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00004404 } else {
4405 // We should have found something, but didn't.
4406 llvm_unreachable("Unable to find instantiation of declaration!");
4407 }
4408 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004409
Douglas Gregor51783312009-05-27 05:35:12 +00004410 D = Result;
4411 }
4412
Douglas Gregor51783312009-05-27 05:35:12 +00004413 return D;
4414}
Douglas Gregor77b50e12009-06-22 23:06:13 +00004415
Mike Stump11289f42009-09-09 15:08:12 +00004416/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00004417/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00004418void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregore39f97c2011-07-28 19:49:54 +00004419 // Load pending instantiations from the external source.
4420 if (!LocalOnly && ExternalSource) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00004421 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregore39f97c2011-07-28 19:49:54 +00004422 ExternalSource->ReadPendingInstantiations(Pending);
4423 PendingInstantiations.insert(PendingInstantiations.begin(),
4424 Pending.begin(), Pending.end());
4425 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004426
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004427 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00004428 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004429 PendingImplicitInstantiation Inst;
4430
4431 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00004432 Inst = PendingInstantiations.front();
4433 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004434 } else {
4435 Inst = PendingLocalImplicitInstantiations.front();
4436 PendingLocalImplicitInstantiations.pop_front();
4437 }
Mike Stump11289f42009-09-09 15:08:12 +00004438
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004439 // Instantiate function definitions
4440 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallfaf5fb42010-08-26 23:41:50 +00004441 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4442 "instantiating function definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004443 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4444 TSK_ExplicitInstantiationDefinition;
4445 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4446 DefinitionRequired);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004447 continue;
4448 }
Mike Stump11289f42009-09-09 15:08:12 +00004449
Larisse Voufo39a1e502013-08-06 01:03:05 +00004450 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004451 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004452
4453 assert((Var->isStaticDataMember() ||
4454 isa<VarTemplateSpecializationDecl>(Var)) &&
4455 "Not a static data member, nor a variable template"
4456 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00004457
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004458 // Don't try to instantiate declarations if the most recent redeclaration
4459 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004460 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004461 continue;
4462
4463 // Check if the most recent declaration has changed the specialization kind
4464 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004465 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004466 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00004467 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004468 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004469 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004470 continue; // No longer need to instantiate this type.
4471 case TSK_ExplicitInstantiationDefinition:
4472 // We only need an instantiation if the pending instantiation *is* the
4473 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004474 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004475 case TSK_ImplicitInstantiation:
4476 break;
4477 }
4478
Larisse Voufo39a1e502013-08-06 01:03:05 +00004479 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4480 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004481 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4482 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004483
4484 // Instantiate static data member definitions or variable template
4485 // specializations.
4486 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4487 DefinitionRequired);
Douglas Gregor77b50e12009-06-22 23:06:13 +00004488 }
4489}
John McCallc62bb642010-03-24 05:22:00 +00004490
4491void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4492 const MultiLevelTemplateArgumentList &TemplateArgs) {
4493 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
4494 E = Pattern->ddiag_end(); I != E; ++I) {
4495 DependentDiagnostic *DD = *I;
4496
4497 switch (DD->getKind()) {
4498 case DependentDiagnostic::Access:
4499 HandleDependentAccessCheck(*DD, TemplateArgs);
4500 break;
4501 }
4502 }
4503}