1 //===--- 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 //===----------------------------------------------------------------------===/
12 #include "clang/Sema/SemaInternal.h"
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTMutationListener.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/DeclVisitor.h"
18 #include "clang/AST/DependentDiagnostic.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/Sema/Lookup.h"
23 #include "clang/Sema/PrettyDeclStackTrace.h"
24 #include "clang/Sema/Template.h"
25
26 using namespace clang;
27
isDeclWithinFunction(const Decl * D)28 static 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
SubstQualifier(const DeclaratorDecl * OldDecl,DeclaratorDecl * NewDecl)39 bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
40 DeclaratorDecl *NewDecl) {
41 if (!OldDecl->getQualifierLoc())
42 return false;
43
44 NestedNameSpecifierLoc NewQualifierLoc
45 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
46 TemplateArgs);
47
48 if (!NewQualifierLoc)
49 return true;
50
51 NewDecl->setQualifierInfo(NewQualifierLoc);
52 return false;
53 }
54
SubstQualifier(const TagDecl * OldDecl,TagDecl * NewDecl)55 bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
56 TagDecl *NewDecl) {
57 if (!OldDecl->getQualifierLoc())
58 return false;
59
60 NestedNameSpecifierLoc NewQualifierLoc
61 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
62 TemplateArgs);
63
64 if (!NewQualifierLoc)
65 return true;
66
67 NewDecl->setQualifierInfo(NewQualifierLoc);
68 return false;
69 }
70
71 // Include attribute instantiation code.
72 #include "clang/Sema/AttrTemplateInstantiate.inc"
73
instantiateDependentAlignedAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AlignedAttr * Aligned,Decl * New,bool IsPackExpansion)74 static 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.getAs<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
instantiateDependentAlignedAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const AlignedAttr * Aligned,Decl * New)94 static 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
instantiateDependentEnableIfAttr(Sema & S,const MultiLevelTemplateArgumentList & TemplateArgs,const EnableIfAttr * A,const Decl * Tmpl,Decl * New)132 static void instantiateDependentEnableIfAttr(
133 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
134 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
135 Expr *Cond = nullptr;
136 {
137 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
138 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
139 if (Result.isInvalid())
140 return;
141 Cond = Result.getAs<Expr>();
142 }
143 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
144 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
145 if (Converted.isInvalid())
146 return;
147 Cond = Converted.get();
148 }
149
150 SmallVector<PartialDiagnosticAt, 8> Diags;
151 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
152 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
153 Diags)) {
154 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
155 for (int I = 0, N = Diags.size(); I != N; ++I)
156 S.Diag(Diags[I].first, Diags[I].second);
157 return;
158 }
159
160 EnableIfAttr *EIA = new (S.getASTContext())
161 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
162 A->getMessage(),
163 A->getSpellingListIndex());
164 New->addAttr(EIA);
165 }
166
InstantiateAttrs(const MultiLevelTemplateArgumentList & TemplateArgs,const Decl * Tmpl,Decl * New,LateInstantiatedAttrVec * LateAttrs,LocalInstantiationScope * OuterMostScope)167 void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
168 const Decl *Tmpl, Decl *New,
169 LateInstantiatedAttrVec *LateAttrs,
170 LocalInstantiationScope *OuterMostScope) {
171 for (const auto *TmplAttr : Tmpl->attrs()) {
172 // FIXME: This should be generalized to more than just the AlignedAttr.
173 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
174 if (Aligned && Aligned->isAlignmentDependent()) {
175 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
176 continue;
177 }
178
179 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
180 if (EnableIf && EnableIf->getCond()->isValueDependent()) {
181 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
182 New);
183 continue;
184 }
185
186 assert(!TmplAttr->isPackExpansion());
187 if (TmplAttr->isLateParsed() && LateAttrs) {
188 // Late parsed attributes must be instantiated and attached after the
189 // enclosing class has been instantiated. See Sema::InstantiateClass.
190 LocalInstantiationScope *Saved = nullptr;
191 if (CurrentInstantiationScope)
192 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
193 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
194 } else {
195 // Allow 'this' within late-parsed attributes.
196 NamedDecl *ND = dyn_cast<NamedDecl>(New);
197 CXXRecordDecl *ThisContext =
198 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
199 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
200 ND && ND->isCXXInstanceMember());
201
202 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
203 *this, TemplateArgs);
204 if (NewAttr)
205 New->addAttr(NewAttr);
206 }
207 }
208 }
209
210 Decl *
VisitTranslationUnitDecl(TranslationUnitDecl * D)211 TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
212 llvm_unreachable("Translation units cannot be instantiated");
213 }
214
215 Decl *
VisitLabelDecl(LabelDecl * D)216 TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
217 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
218 D->getIdentifier());
219 Owner->addDecl(Inst);
220 return Inst;
221 }
222
223 Decl *
VisitNamespaceDecl(NamespaceDecl * D)224 TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
225 llvm_unreachable("Namespaces cannot be instantiated");
226 }
227
228 Decl *
VisitNamespaceAliasDecl(NamespaceAliasDecl * D)229 TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
230 NamespaceAliasDecl *Inst
231 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
232 D->getNamespaceLoc(),
233 D->getAliasLoc(),
234 D->getIdentifier(),
235 D->getQualifierLoc(),
236 D->getTargetNameLoc(),
237 D->getNamespace());
238 Owner->addDecl(Inst);
239 return Inst;
240 }
241
InstantiateTypedefNameDecl(TypedefNameDecl * D,bool IsTypeAlias)242 Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
243 bool IsTypeAlias) {
244 bool Invalid = false;
245 TypeSourceInfo *DI = D->getTypeSourceInfo();
246 if (DI->getType()->isInstantiationDependentType() ||
247 DI->getType()->isVariablyModifiedType()) {
248 DI = SemaRef.SubstType(DI, TemplateArgs,
249 D->getLocation(), D->getDeclName());
250 if (!DI) {
251 Invalid = true;
252 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
253 }
254 } else {
255 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
256 }
257
258 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
259 // libstdc++ relies upon this bug in its implementation of common_type.
260 // If we happen to be processing that implementation, fake up the g++ ?:
261 // semantics. See LWG issue 2141 for more information on the bug.
262 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
263 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
264 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
265 DT->isReferenceType() &&
266 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
267 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
268 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
269 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
270 // Fold it to the (non-reference) type which g++ would have produced.
271 DI = SemaRef.Context.getTrivialTypeSourceInfo(
272 DI->getType().getNonReferenceType());
273
274 // Create the new typedef
275 TypedefNameDecl *Typedef;
276 if (IsTypeAlias)
277 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
278 D->getLocation(), D->getIdentifier(), DI);
279 else
280 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
281 D->getLocation(), D->getIdentifier(), DI);
282 if (Invalid)
283 Typedef->setInvalidDecl();
284
285 // If the old typedef was the name for linkage purposes of an anonymous
286 // tag decl, re-establish that relationship for the new typedef.
287 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
288 TagDecl *oldTag = oldTagType->getDecl();
289 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
290 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
291 assert(!newTag->hasNameForLinkage());
292 newTag->setTypedefNameForAnonDecl(Typedef);
293 }
294 }
295
296 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
297 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
298 TemplateArgs);
299 if (!InstPrev)
300 return nullptr;
301
302 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
303
304 // If the typedef types are not identical, reject them.
305 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
306
307 Typedef->setPreviousDecl(InstPrevTypedef);
308 }
309
310 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
311
312 Typedef->setAccess(D->getAccess());
313
314 return Typedef;
315 }
316
VisitTypedefDecl(TypedefDecl * D)317 Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
318 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
319 Owner->addDecl(Typedef);
320 return Typedef;
321 }
322
VisitTypeAliasDecl(TypeAliasDecl * D)323 Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
324 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
325 Owner->addDecl(Typedef);
326 return Typedef;
327 }
328
329 Decl *
VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl * D)330 TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
331 // Create a local instantiation scope for this type alias template, which
332 // will contain the instantiations of the template parameters.
333 LocalInstantiationScope Scope(SemaRef);
334
335 TemplateParameterList *TempParams = D->getTemplateParameters();
336 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
337 if (!InstParams)
338 return nullptr;
339
340 TypeAliasDecl *Pattern = D->getTemplatedDecl();
341
342 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
343 if (Pattern->getPreviousDecl()) {
344 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
345 if (!Found.empty()) {
346 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
347 }
348 }
349
350 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
351 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
352 if (!AliasInst)
353 return nullptr;
354
355 TypeAliasTemplateDecl *Inst
356 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
357 D->getDeclName(), InstParams, AliasInst);
358 if (PrevAliasTemplate)
359 Inst->setPreviousDecl(PrevAliasTemplate);
360
361 Inst->setAccess(D->getAccess());
362
363 if (!PrevAliasTemplate)
364 Inst->setInstantiatedFromMemberTemplate(D);
365
366 Owner->addDecl(Inst);
367
368 return Inst;
369 }
370
VisitVarDecl(VarDecl * D)371 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
372 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
373 }
374
VisitVarDecl(VarDecl * D,bool InstantiatingVarTemplate)375 Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
376 bool InstantiatingVarTemplate) {
377
378 // If this is the variable for an anonymous struct or union,
379 // instantiate the anonymous struct/union type first.
380 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
381 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
382 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
383 return nullptr;
384
385 // Do substitution on the type of the declaration
386 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
387 TemplateArgs,
388 D->getTypeSpecStartLoc(),
389 D->getDeclName());
390 if (!DI)
391 return nullptr;
392
393 if (DI->getType()->isFunctionType()) {
394 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
395 << D->isStaticDataMember() << DI->getType();
396 return nullptr;
397 }
398
399 DeclContext *DC = Owner;
400 if (D->isLocalExternDecl())
401 SemaRef.adjustContextForLocalExternDecl(DC);
402
403 // Build the instantiated declaration.
404 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
405 D->getLocation(), D->getIdentifier(),
406 DI->getType(), DI, D->getStorageClass());
407
408 // In ARC, infer 'retaining' for variables of retainable type.
409 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
410 SemaRef.inferObjCARCLifetime(Var))
411 Var->setInvalidDecl();
412
413 // Substitute the nested name specifier, if any.
414 if (SubstQualifier(D, Var))
415 return nullptr;
416
417 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
418 StartingScope, InstantiatingVarTemplate);
419
420 if (D->isNRVOVariable()) {
421 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
422 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
423 Var->setNRVOVariable(true);
424 }
425
426 Var->setImplicit(D->isImplicit());
427
428 return Var;
429 }
430
VisitAccessSpecDecl(AccessSpecDecl * D)431 Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
432 AccessSpecDecl* AD
433 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
434 D->getAccessSpecifierLoc(), D->getColonLoc());
435 Owner->addHiddenDecl(AD);
436 return AD;
437 }
438
VisitFieldDecl(FieldDecl * D)439 Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
440 bool Invalid = false;
441 TypeSourceInfo *DI = D->getTypeSourceInfo();
442 if (DI->getType()->isInstantiationDependentType() ||
443 DI->getType()->isVariablyModifiedType()) {
444 DI = SemaRef.SubstType(DI, TemplateArgs,
445 D->getLocation(), D->getDeclName());
446 if (!DI) {
447 DI = D->getTypeSourceInfo();
448 Invalid = true;
449 } else if (DI->getType()->isFunctionType()) {
450 // C++ [temp.arg.type]p3:
451 // If a declaration acquires a function type through a type
452 // dependent on a template-parameter and this causes a
453 // declaration that does not use the syntactic form of a
454 // function declarator to have function type, the program is
455 // ill-formed.
456 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
457 << DI->getType();
458 Invalid = true;
459 }
460 } else {
461 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
462 }
463
464 Expr *BitWidth = D->getBitWidth();
465 if (Invalid)
466 BitWidth = nullptr;
467 else if (BitWidth) {
468 // The bit-width expression is a constant expression.
469 EnterExpressionEvaluationContext Unevaluated(SemaRef,
470 Sema::ConstantEvaluated);
471
472 ExprResult InstantiatedBitWidth
473 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
474 if (InstantiatedBitWidth.isInvalid()) {
475 Invalid = true;
476 BitWidth = nullptr;
477 } else
478 BitWidth = InstantiatedBitWidth.getAs<Expr>();
479 }
480
481 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
482 DI->getType(), DI,
483 cast<RecordDecl>(Owner),
484 D->getLocation(),
485 D->isMutable(),
486 BitWidth,
487 D->getInClassInitStyle(),
488 D->getInnerLocStart(),
489 D->getAccess(),
490 nullptr);
491 if (!Field) {
492 cast<Decl>(Owner)->setInvalidDecl();
493 return nullptr;
494 }
495
496 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
497
498 if (Field->hasAttrs())
499 SemaRef.CheckAlignasUnderalignment(Field);
500
501 if (Invalid)
502 Field->setInvalidDecl();
503
504 if (!Field->getDeclName()) {
505 // Keep track of where this decl came from.
506 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
507 }
508 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
509 if (Parent->isAnonymousStructOrUnion() &&
510 Parent->getRedeclContext()->isFunctionOrMethod())
511 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
512 }
513
514 Field->setImplicit(D->isImplicit());
515 Field->setAccess(D->getAccess());
516 Owner->addDecl(Field);
517
518 return Field;
519 }
520
VisitMSPropertyDecl(MSPropertyDecl * D)521 Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
522 bool Invalid = false;
523 TypeSourceInfo *DI = D->getTypeSourceInfo();
524
525 if (DI->getType()->isVariablyModifiedType()) {
526 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
527 << D;
528 Invalid = true;
529 } else if (DI->getType()->isInstantiationDependentType()) {
530 DI = SemaRef.SubstType(DI, TemplateArgs,
531 D->getLocation(), D->getDeclName());
532 if (!DI) {
533 DI = D->getTypeSourceInfo();
534 Invalid = true;
535 } else if (DI->getType()->isFunctionType()) {
536 // C++ [temp.arg.type]p3:
537 // If a declaration acquires a function type through a type
538 // dependent on a template-parameter and this causes a
539 // declaration that does not use the syntactic form of a
540 // function declarator to have function type, the program is
541 // ill-formed.
542 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
543 << DI->getType();
544 Invalid = true;
545 }
546 } else {
547 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
548 }
549
550 MSPropertyDecl *Property = MSPropertyDecl::Create(
551 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
552 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
553
554 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
555 StartingScope);
556
557 if (Invalid)
558 Property->setInvalidDecl();
559
560 Property->setAccess(D->getAccess());
561 Owner->addDecl(Property);
562
563 return Property;
564 }
565
VisitIndirectFieldDecl(IndirectFieldDecl * D)566 Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
567 NamedDecl **NamedChain =
568 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
569
570 int i = 0;
571 for (auto *PI : D->chain()) {
572 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
573 TemplateArgs);
574 if (!Next)
575 return nullptr;
576
577 NamedChain[i++] = Next;
578 }
579
580 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
581 IndirectFieldDecl* IndirectField
582 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
583 D->getIdentifier(), T,
584 NamedChain, D->getChainingSize());
585
586
587 IndirectField->setImplicit(D->isImplicit());
588 IndirectField->setAccess(D->getAccess());
589 Owner->addDecl(IndirectField);
590 return IndirectField;
591 }
592
VisitFriendDecl(FriendDecl * D)593 Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
594 // Handle friend type expressions by simply substituting template
595 // parameters into the pattern type and checking the result.
596 if (TypeSourceInfo *Ty = D->getFriendType()) {
597 TypeSourceInfo *InstTy;
598 // If this is an unsupported friend, don't bother substituting template
599 // arguments into it. The actual type referred to won't be used by any
600 // parts of Clang, and may not be valid for instantiating. Just use the
601 // same info for the instantiated friend.
602 if (D->isUnsupportedFriend()) {
603 InstTy = Ty;
604 } else {
605 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
606 D->getLocation(), DeclarationName());
607 }
608 if (!InstTy)
609 return nullptr;
610
611 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
612 D->getFriendLoc(), InstTy);
613 if (!FD)
614 return nullptr;
615
616 FD->setAccess(AS_public);
617 FD->setUnsupportedFriend(D->isUnsupportedFriend());
618 Owner->addDecl(FD);
619 return FD;
620 }
621
622 NamedDecl *ND = D->getFriendDecl();
623 assert(ND && "friend decl must be a decl or a type!");
624
625 // All of the Visit implementations for the various potential friend
626 // declarations have to be carefully written to work for friend
627 // objects, with the most important detail being that the target
628 // decl should almost certainly not be placed in Owner.
629 Decl *NewND = Visit(ND);
630 if (!NewND) return nullptr;
631
632 FriendDecl *FD =
633 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
634 cast<NamedDecl>(NewND), D->getFriendLoc());
635 FD->setAccess(AS_public);
636 FD->setUnsupportedFriend(D->isUnsupportedFriend());
637 Owner->addDecl(FD);
638 return FD;
639 }
640
VisitStaticAssertDecl(StaticAssertDecl * D)641 Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
642 Expr *AssertExpr = D->getAssertExpr();
643
644 // The expression in a static assertion is a constant expression.
645 EnterExpressionEvaluationContext Unevaluated(SemaRef,
646 Sema::ConstantEvaluated);
647
648 ExprResult InstantiatedAssertExpr
649 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
650 if (InstantiatedAssertExpr.isInvalid())
651 return nullptr;
652
653 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
654 InstantiatedAssertExpr.get(),
655 D->getMessage(),
656 D->getRParenLoc(),
657 D->isFailed());
658 }
659
VisitEnumDecl(EnumDecl * D)660 Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
661 EnumDecl *PrevDecl = nullptr;
662 if (D->getPreviousDecl()) {
663 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
664 D->getPreviousDecl(),
665 TemplateArgs);
666 if (!Prev) return nullptr;
667 PrevDecl = cast<EnumDecl>(Prev);
668 }
669
670 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
671 D->getLocation(), D->getIdentifier(),
672 PrevDecl, D->isScoped(),
673 D->isScopedUsingClassTag(), D->isFixed());
674 if (D->isFixed()) {
675 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
676 // If we have type source information for the underlying type, it means it
677 // has been explicitly set by the user. Perform substitution on it before
678 // moving on.
679 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
680 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
681 DeclarationName());
682 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
683 Enum->setIntegerType(SemaRef.Context.IntTy);
684 else
685 Enum->setIntegerTypeSourceInfo(NewTI);
686 } else {
687 assert(!D->getIntegerType()->isDependentType()
688 && "Dependent type without type source info");
689 Enum->setIntegerType(D->getIntegerType());
690 }
691 }
692
693 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
694
695 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
696 Enum->setAccess(D->getAccess());
697 // Forward the mangling number from the template to the instantiated decl.
698 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
699 if (SubstQualifier(D, Enum)) return nullptr;
700 Owner->addDecl(Enum);
701
702 EnumDecl *Def = D->getDefinition();
703 if (Def && Def != D) {
704 // If this is an out-of-line definition of an enum member template, check
705 // that the underlying types match in the instantiation of both
706 // declarations.
707 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
708 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
709 QualType DefnUnderlying =
710 SemaRef.SubstType(TI->getType(), TemplateArgs,
711 UnderlyingLoc, DeclarationName());
712 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
713 DefnUnderlying, Enum);
714 }
715 }
716
717 // C++11 [temp.inst]p1: The implicit instantiation of a class template
718 // specialization causes the implicit instantiation of the declarations, but
719 // not the definitions of scoped member enumerations.
720 //
721 // DR1484 clarifies that enumeration definitions inside of a template
722 // declaration aren't considered entities that can be separately instantiated
723 // from the rest of the entity they are declared inside of.
724 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
725 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
726 InstantiateEnumDefinition(Enum, Def);
727 }
728
729 return Enum;
730 }
731
InstantiateEnumDefinition(EnumDecl * Enum,EnumDecl * Pattern)732 void TemplateDeclInstantiator::InstantiateEnumDefinition(
733 EnumDecl *Enum, EnumDecl *Pattern) {
734 Enum->startDefinition();
735
736 // Update the location to refer to the definition.
737 Enum->setLocation(Pattern->getLocation());
738
739 SmallVector<Decl*, 4> Enumerators;
740
741 EnumConstantDecl *LastEnumConst = nullptr;
742 for (auto *EC : Pattern->enumerators()) {
743 // The specified value for the enumerator.
744 ExprResult Value((Expr *)nullptr);
745 if (Expr *UninstValue = EC->getInitExpr()) {
746 // The enumerator's value expression is a constant expression.
747 EnterExpressionEvaluationContext Unevaluated(SemaRef,
748 Sema::ConstantEvaluated);
749
750 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
751 }
752
753 // Drop the initial value and continue.
754 bool isInvalid = false;
755 if (Value.isInvalid()) {
756 Value = nullptr;
757 isInvalid = true;
758 }
759
760 EnumConstantDecl *EnumConst
761 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
762 EC->getLocation(), EC->getIdentifier(),
763 Value.get());
764
765 if (isInvalid) {
766 if (EnumConst)
767 EnumConst->setInvalidDecl();
768 Enum->setInvalidDecl();
769 }
770
771 if (EnumConst) {
772 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
773
774 EnumConst->setAccess(Enum->getAccess());
775 Enum->addDecl(EnumConst);
776 Enumerators.push_back(EnumConst);
777 LastEnumConst = EnumConst;
778
779 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
780 !Enum->isScoped()) {
781 // If the enumeration is within a function or method, record the enum
782 // constant as a local.
783 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
784 }
785 }
786 }
787
788 // FIXME: Fixup LBraceLoc
789 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
790 Enum->getRBraceLoc(), Enum,
791 Enumerators,
792 nullptr, nullptr);
793 }
794
VisitEnumConstantDecl(EnumConstantDecl * D)795 Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
796 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
797 }
798
VisitClassTemplateDecl(ClassTemplateDecl * D)799 Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
800 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
801
802 // Create a local instantiation scope for this class template, which
803 // will contain the instantiations of the template parameters.
804 LocalInstantiationScope Scope(SemaRef);
805 TemplateParameterList *TempParams = D->getTemplateParameters();
806 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
807 if (!InstParams)
808 return nullptr;
809
810 CXXRecordDecl *Pattern = D->getTemplatedDecl();
811
812 // Instantiate the qualifier. We have to do this first in case
813 // we're a friend declaration, because if we are then we need to put
814 // the new declaration in the appropriate context.
815 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
816 if (QualifierLoc) {
817 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
818 TemplateArgs);
819 if (!QualifierLoc)
820 return nullptr;
821 }
822
823 CXXRecordDecl *PrevDecl = nullptr;
824 ClassTemplateDecl *PrevClassTemplate = nullptr;
825
826 if (!isFriend && Pattern->getPreviousDecl()) {
827 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
828 if (!Found.empty()) {
829 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
830 if (PrevClassTemplate)
831 PrevDecl = PrevClassTemplate->getTemplatedDecl();
832 }
833 }
834
835 // If this isn't a friend, then it's a member template, in which
836 // case we just want to build the instantiation in the
837 // specialization. If it is a friend, we want to build it in
838 // the appropriate context.
839 DeclContext *DC = Owner;
840 if (isFriend) {
841 if (QualifierLoc) {
842 CXXScopeSpec SS;
843 SS.Adopt(QualifierLoc);
844 DC = SemaRef.computeDeclContext(SS);
845 if (!DC) return nullptr;
846 } else {
847 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
848 Pattern->getDeclContext(),
849 TemplateArgs);
850 }
851
852 // Look for a previous declaration of the template in the owning
853 // context.
854 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
855 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
856 SemaRef.LookupQualifiedName(R, DC);
857
858 if (R.isSingleResult()) {
859 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
860 if (PrevClassTemplate)
861 PrevDecl = PrevClassTemplate->getTemplatedDecl();
862 }
863
864 if (!PrevClassTemplate && QualifierLoc) {
865 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
866 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
867 << QualifierLoc.getSourceRange();
868 return nullptr;
869 }
870
871 bool AdoptedPreviousTemplateParams = false;
872 if (PrevClassTemplate) {
873 bool Complain = true;
874
875 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
876 // template for struct std::tr1::__detail::_Map_base, where the
877 // template parameters of the friend declaration don't match the
878 // template parameters of the original declaration. In this one
879 // case, we don't complain about the ill-formed friend
880 // declaration.
881 if (isFriend && Pattern->getIdentifier() &&
882 Pattern->getIdentifier()->isStr("_Map_base") &&
883 DC->isNamespace() &&
884 cast<NamespaceDecl>(DC)->getIdentifier() &&
885 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
886 DeclContext *DCParent = DC->getParent();
887 if (DCParent->isNamespace() &&
888 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
889 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
890 if (cast<Decl>(DCParent)->isInStdNamespace())
891 Complain = false;
892 }
893 }
894
895 TemplateParameterList *PrevParams
896 = PrevClassTemplate->getTemplateParameters();
897
898 // Make sure the parameter lists match.
899 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
900 Complain,
901 Sema::TPL_TemplateMatch)) {
902 if (Complain)
903 return nullptr;
904
905 AdoptedPreviousTemplateParams = true;
906 InstParams = PrevParams;
907 }
908
909 // Do some additional validation, then merge default arguments
910 // from the existing declarations.
911 if (!AdoptedPreviousTemplateParams &&
912 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
913 Sema::TPC_ClassTemplate))
914 return nullptr;
915 }
916 }
917
918 CXXRecordDecl *RecordInst
919 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
920 Pattern->getLocStart(), Pattern->getLocation(),
921 Pattern->getIdentifier(), PrevDecl,
922 /*DelayTypeCreation=*/true);
923
924 if (QualifierLoc)
925 RecordInst->setQualifierInfo(QualifierLoc);
926
927 ClassTemplateDecl *Inst
928 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
929 D->getIdentifier(), InstParams, RecordInst,
930 PrevClassTemplate);
931 RecordInst->setDescribedClassTemplate(Inst);
932
933 if (isFriend) {
934 if (PrevClassTemplate)
935 Inst->setAccess(PrevClassTemplate->getAccess());
936 else
937 Inst->setAccess(D->getAccess());
938
939 Inst->setObjectOfFriendDecl();
940 // TODO: do we want to track the instantiation progeny of this
941 // friend target decl?
942 } else {
943 Inst->setAccess(D->getAccess());
944 if (!PrevClassTemplate)
945 Inst->setInstantiatedFromMemberTemplate(D);
946 }
947
948 // Trigger creation of the type for the instantiation.
949 SemaRef.Context.getInjectedClassNameType(RecordInst,
950 Inst->getInjectedClassNameSpecialization());
951
952 // Finish handling of friends.
953 if (isFriend) {
954 DC->makeDeclVisibleInContext(Inst);
955 Inst->setLexicalDeclContext(Owner);
956 RecordInst->setLexicalDeclContext(Owner);
957 return Inst;
958 }
959
960 if (D->isOutOfLine()) {
961 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
962 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
963 }
964
965 Owner->addDecl(Inst);
966
967 if (!PrevClassTemplate) {
968 // Queue up any out-of-line partial specializations of this member
969 // class template; the client will force their instantiation once
970 // the enclosing class has been instantiated.
971 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
972 D->getPartialSpecializations(PartialSpecs);
973 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
974 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
975 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
976 }
977
978 return Inst;
979 }
980
981 Decl *
VisitClassTemplatePartialSpecializationDecl(ClassTemplatePartialSpecializationDecl * D)982 TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
983 ClassTemplatePartialSpecializationDecl *D) {
984 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
985
986 // Lookup the already-instantiated declaration in the instantiation
987 // of the class template and return that.
988 DeclContext::lookup_result Found
989 = Owner->lookup(ClassTemplate->getDeclName());
990 if (Found.empty())
991 return nullptr;
992
993 ClassTemplateDecl *InstClassTemplate
994 = dyn_cast<ClassTemplateDecl>(Found.front());
995 if (!InstClassTemplate)
996 return nullptr;
997
998 if (ClassTemplatePartialSpecializationDecl *Result
999 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1000 return Result;
1001
1002 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1003 }
1004
VisitVarTemplateDecl(VarTemplateDecl * D)1005 Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1006 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1007 "Only static data member templates are allowed.");
1008
1009 // Create a local instantiation scope for this variable template, which
1010 // will contain the instantiations of the template parameters.
1011 LocalInstantiationScope Scope(SemaRef);
1012 TemplateParameterList *TempParams = D->getTemplateParameters();
1013 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1014 if (!InstParams)
1015 return nullptr;
1016
1017 VarDecl *Pattern = D->getTemplatedDecl();
1018 VarTemplateDecl *PrevVarTemplate = nullptr;
1019
1020 if (Pattern->getPreviousDecl()) {
1021 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1022 if (!Found.empty())
1023 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1024 }
1025
1026 VarDecl *VarInst =
1027 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1028 /*InstantiatingVarTemplate=*/true));
1029
1030 DeclContext *DC = Owner;
1031
1032 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1033 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1034 VarInst);
1035 VarInst->setDescribedVarTemplate(Inst);
1036 Inst->setPreviousDecl(PrevVarTemplate);
1037
1038 Inst->setAccess(D->getAccess());
1039 if (!PrevVarTemplate)
1040 Inst->setInstantiatedFromMemberTemplate(D);
1041
1042 if (D->isOutOfLine()) {
1043 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1044 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1045 }
1046
1047 Owner->addDecl(Inst);
1048
1049 if (!PrevVarTemplate) {
1050 // Queue up any out-of-line partial specializations of this member
1051 // variable template; the client will force their instantiation once
1052 // the enclosing class has been instantiated.
1053 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1054 D->getPartialSpecializations(PartialSpecs);
1055 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1056 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1057 OutOfLineVarPartialSpecs.push_back(
1058 std::make_pair(Inst, PartialSpecs[I]));
1059 }
1060
1061 return Inst;
1062 }
1063
VisitVarTemplatePartialSpecializationDecl(VarTemplatePartialSpecializationDecl * D)1064 Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1065 VarTemplatePartialSpecializationDecl *D) {
1066 assert(D->isStaticDataMember() &&
1067 "Only static data member templates are allowed.");
1068
1069 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1070
1071 // Lookup the already-instantiated declaration and return that.
1072 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1073 assert(!Found.empty() && "Instantiation found nothing?");
1074
1075 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1076 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1077
1078 if (VarTemplatePartialSpecializationDecl *Result =
1079 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1080 return Result;
1081
1082 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1083 }
1084
1085 Decl *
VisitFunctionTemplateDecl(FunctionTemplateDecl * D)1086 TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1087 // Create a local instantiation scope for this function template, which
1088 // will contain the instantiations of the template parameters and then get
1089 // merged with the local instantiation scope for the function template
1090 // itself.
1091 LocalInstantiationScope Scope(SemaRef);
1092
1093 TemplateParameterList *TempParams = D->getTemplateParameters();
1094 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1095 if (!InstParams)
1096 return nullptr;
1097
1098 FunctionDecl *Instantiated = nullptr;
1099 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1100 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1101 InstParams));
1102 else
1103 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1104 D->getTemplatedDecl(),
1105 InstParams));
1106
1107 if (!Instantiated)
1108 return nullptr;
1109
1110 // Link the instantiated function template declaration to the function
1111 // template from which it was instantiated.
1112 FunctionTemplateDecl *InstTemplate
1113 = Instantiated->getDescribedFunctionTemplate();
1114 InstTemplate->setAccess(D->getAccess());
1115 assert(InstTemplate &&
1116 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
1117
1118 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1119
1120 // Link the instantiation back to the pattern *unless* this is a
1121 // non-definition friend declaration.
1122 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1123 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1124 InstTemplate->setInstantiatedFromMemberTemplate(D);
1125
1126 // Make declarations visible in the appropriate context.
1127 if (!isFriend) {
1128 Owner->addDecl(InstTemplate);
1129 } else if (InstTemplate->getDeclContext()->isRecord() &&
1130 !D->getPreviousDecl()) {
1131 SemaRef.CheckFriendAccess(InstTemplate);
1132 }
1133
1134 return InstTemplate;
1135 }
1136
VisitCXXRecordDecl(CXXRecordDecl * D)1137 Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1138 CXXRecordDecl *PrevDecl = nullptr;
1139 if (D->isInjectedClassName())
1140 PrevDecl = cast<CXXRecordDecl>(Owner);
1141 else if (D->getPreviousDecl()) {
1142 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1143 D->getPreviousDecl(),
1144 TemplateArgs);
1145 if (!Prev) return nullptr;
1146 PrevDecl = cast<CXXRecordDecl>(Prev);
1147 }
1148
1149 CXXRecordDecl *Record
1150 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1151 D->getLocStart(), D->getLocation(),
1152 D->getIdentifier(), PrevDecl);
1153
1154 // Substitute the nested name specifier, if any.
1155 if (SubstQualifier(D, Record))
1156 return nullptr;
1157
1158 Record->setImplicit(D->isImplicit());
1159 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1160 // the tag decls introduced by friend class declarations don't have an access
1161 // specifier. Remove once this area of the code gets sorted out.
1162 if (D->getAccess() != AS_none)
1163 Record->setAccess(D->getAccess());
1164 if (!D->isInjectedClassName())
1165 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1166
1167 // If the original function was part of a friend declaration,
1168 // inherit its namespace state.
1169 if (D->getFriendObjectKind())
1170 Record->setObjectOfFriendDecl();
1171
1172 // Make sure that anonymous structs and unions are recorded.
1173 if (D->isAnonymousStructOrUnion())
1174 Record->setAnonymousStructOrUnion(true);
1175
1176 if (D->isLocalClass())
1177 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1178
1179 // Forward the mangling number from the template to the instantiated decl.
1180 SemaRef.Context.setManglingNumber(Record,
1181 SemaRef.Context.getManglingNumber(D));
1182
1183 Owner->addDecl(Record);
1184
1185 // DR1484 clarifies that the members of a local class are instantiated as part
1186 // of the instantiation of their enclosing entity.
1187 if (D->isCompleteDefinition() && D->isLocalClass()) {
1188 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1189 TSK_ImplicitInstantiation,
1190 /*Complain=*/true);
1191 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1192 TSK_ImplicitInstantiation);
1193 }
1194 return Record;
1195 }
1196
1197 /// \brief Adjust the given function type for an instantiation of the
1198 /// given declaration, to cope with modifications to the function's type that
1199 /// aren't reflected in the type-source information.
1200 ///
1201 /// \param D The declaration we're instantiating.
1202 /// \param TInfo The already-instantiated type.
adjustFunctionTypeForInstantiation(ASTContext & Context,FunctionDecl * D,TypeSourceInfo * TInfo)1203 static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1204 FunctionDecl *D,
1205 TypeSourceInfo *TInfo) {
1206 const FunctionProtoType *OrigFunc
1207 = D->getType()->castAs<FunctionProtoType>();
1208 const FunctionProtoType *NewFunc
1209 = TInfo->getType()->castAs<FunctionProtoType>();
1210 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1211 return TInfo->getType();
1212
1213 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1214 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1215 return Context.getFunctionType(NewFunc->getReturnType(),
1216 NewFunc->getParamTypes(), NewEPI);
1217 }
1218
1219 /// Normal class members are of more specific types and therefore
1220 /// don't make it here. This function serves two purposes:
1221 /// 1) instantiating function templates
1222 /// 2) substituting friend declarations
VisitFunctionDecl(FunctionDecl * D,TemplateParameterList * TemplateParams)1223 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
1224 TemplateParameterList *TemplateParams) {
1225 // Check whether there is already a function template specialization for
1226 // this declaration.
1227 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1228 if (FunctionTemplate && !TemplateParams) {
1229 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1230
1231 void *InsertPos = nullptr;
1232 FunctionDecl *SpecFunc
1233 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1234
1235 // If we already have a function template specialization, return it.
1236 if (SpecFunc)
1237 return SpecFunc;
1238 }
1239
1240 bool isFriend;
1241 if (FunctionTemplate)
1242 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1243 else
1244 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1245
1246 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1247 Owner->isFunctionOrMethod() ||
1248 !(isa<Decl>(Owner) &&
1249 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1250 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1251
1252 SmallVector<ParmVarDecl *, 4> Params;
1253 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1254 if (!TInfo)
1255 return nullptr;
1256 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1257
1258 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1259 if (QualifierLoc) {
1260 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1261 TemplateArgs);
1262 if (!QualifierLoc)
1263 return nullptr;
1264 }
1265
1266 // If we're instantiating a local function declaration, put the result
1267 // in the enclosing namespace; otherwise we need to find the instantiated
1268 // context.
1269 DeclContext *DC;
1270 if (D->isLocalExternDecl()) {
1271 DC = Owner;
1272 SemaRef.adjustContextForLocalExternDecl(DC);
1273 } else if (isFriend && QualifierLoc) {
1274 CXXScopeSpec SS;
1275 SS.Adopt(QualifierLoc);
1276 DC = SemaRef.computeDeclContext(SS);
1277 if (!DC) return nullptr;
1278 } else {
1279 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1280 TemplateArgs);
1281 }
1282
1283 FunctionDecl *Function =
1284 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1285 D->getNameInfo(), T, TInfo,
1286 D->getCanonicalDecl()->getStorageClass(),
1287 D->isInlineSpecified(), D->hasWrittenPrototype(),
1288 D->isConstexpr());
1289 Function->setRangeEnd(D->getSourceRange().getEnd());
1290
1291 if (D->isInlined())
1292 Function->setImplicitlyInline();
1293
1294 if (QualifierLoc)
1295 Function->setQualifierInfo(QualifierLoc);
1296
1297 if (D->isLocalExternDecl())
1298 Function->setLocalExternDecl();
1299
1300 DeclContext *LexicalDC = Owner;
1301 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
1302 assert(D->getDeclContext()->isFileContext());
1303 LexicalDC = D->getDeclContext();
1304 }
1305
1306 Function->setLexicalDeclContext(LexicalDC);
1307
1308 // Attach the parameters
1309 for (unsigned P = 0; P < Params.size(); ++P)
1310 if (Params[P])
1311 Params[P]->setOwningFunction(Function);
1312 Function->setParams(Params);
1313
1314 SourceLocation InstantiateAtPOI;
1315 if (TemplateParams) {
1316 // Our resulting instantiation is actually a function template, since we
1317 // are substituting only the outer template parameters. For example, given
1318 //
1319 // template<typename T>
1320 // struct X {
1321 // template<typename U> friend void f(T, U);
1322 // };
1323 //
1324 // X<int> x;
1325 //
1326 // We are instantiating the friend function template "f" within X<int>,
1327 // which means substituting int for T, but leaving "f" as a friend function
1328 // template.
1329 // Build the function template itself.
1330 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
1331 Function->getLocation(),
1332 Function->getDeclName(),
1333 TemplateParams, Function);
1334 Function->setDescribedFunctionTemplate(FunctionTemplate);
1335
1336 FunctionTemplate->setLexicalDeclContext(LexicalDC);
1337
1338 if (isFriend && D->isThisDeclarationADefinition()) {
1339 // TODO: should we remember this connection regardless of whether
1340 // the friend declaration provided a body?
1341 FunctionTemplate->setInstantiatedFromMemberTemplate(
1342 D->getDescribedFunctionTemplate());
1343 }
1344 } else if (FunctionTemplate) {
1345 // Record this function template specialization.
1346 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1347 Function->setFunctionTemplateSpecialization(FunctionTemplate,
1348 TemplateArgumentList::CreateCopy(SemaRef.Context,
1349 Innermost.begin(),
1350 Innermost.size()),
1351 /*InsertPos=*/nullptr);
1352 } else if (isFriend) {
1353 // Note, we need this connection even if the friend doesn't have a body.
1354 // Its body may exist but not have been attached yet due to deferred
1355 // parsing.
1356 // FIXME: It might be cleaner to set this when attaching the body to the
1357 // friend function declaration, however that would require finding all the
1358 // instantiations and modifying them.
1359 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1360 }
1361
1362 if (InitFunctionInstantiation(Function, D))
1363 Function->setInvalidDecl();
1364
1365 bool isExplicitSpecialization = false;
1366
1367 LookupResult Previous(
1368 SemaRef, Function->getDeclName(), SourceLocation(),
1369 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1370 : Sema::LookupOrdinaryName,
1371 Sema::ForRedeclaration);
1372
1373 if (DependentFunctionTemplateSpecializationInfo *Info
1374 = D->getDependentSpecializationInfo()) {
1375 assert(isFriend && "non-friend has dependent specialization info?");
1376
1377 // This needs to be set now for future sanity.
1378 Function->setObjectOfFriendDecl();
1379
1380 // Instantiate the explicit template arguments.
1381 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1382 Info->getRAngleLoc());
1383 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1384 ExplicitArgs, TemplateArgs))
1385 return nullptr;
1386
1387 // Map the candidate templates to their instantiations.
1388 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1389 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1390 Info->getTemplate(I),
1391 TemplateArgs);
1392 if (!Temp) return nullptr;
1393
1394 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1395 }
1396
1397 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1398 &ExplicitArgs,
1399 Previous))
1400 Function->setInvalidDecl();
1401
1402 isExplicitSpecialization = true;
1403
1404 } else if (TemplateParams || !FunctionTemplate) {
1405 // Look only into the namespace where the friend would be declared to
1406 // find a previous declaration. This is the innermost enclosing namespace,
1407 // as described in ActOnFriendFunctionDecl.
1408 SemaRef.LookupQualifiedName(Previous, DC);
1409
1410 // In C++, the previous declaration we find might be a tag type
1411 // (class or enum). In this case, the new declaration will hide the
1412 // tag type. Note that this does does not apply if we're declaring a
1413 // typedef (C++ [dcl.typedef]p4).
1414 if (Previous.isSingleTagDecl())
1415 Previous.clear();
1416 }
1417
1418 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
1419 isExplicitSpecialization);
1420
1421 NamedDecl *PrincipalDecl = (TemplateParams
1422 ? cast<NamedDecl>(FunctionTemplate)
1423 : Function);
1424
1425 // If the original function was part of a friend declaration,
1426 // inherit its namespace state and add it to the owner.
1427 if (isFriend) {
1428 PrincipalDecl->setObjectOfFriendDecl();
1429 DC->makeDeclVisibleInContext(PrincipalDecl);
1430
1431 bool QueuedInstantiation = false;
1432
1433 // C++11 [temp.friend]p4 (DR329):
1434 // When a function is defined in a friend function declaration in a class
1435 // template, the function is instantiated when the function is odr-used.
1436 // The same restrictions on multiple declarations and definitions that
1437 // apply to non-template function declarations and definitions also apply
1438 // to these implicit definitions.
1439 if (D->isThisDeclarationADefinition()) {
1440 // Check for a function body.
1441 const FunctionDecl *Definition = nullptr;
1442 if (Function->isDefined(Definition) &&
1443 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1444 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1445 << Function->getDeclName();
1446 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1447 }
1448 // Check for redefinitions due to other instantiations of this or
1449 // a similar friend function.
1450 else for (auto R : Function->redecls()) {
1451 if (R == Function)
1452 continue;
1453
1454 // If some prior declaration of this function has been used, we need
1455 // to instantiate its definition.
1456 if (!QueuedInstantiation && R->isUsed(false)) {
1457 if (MemberSpecializationInfo *MSInfo =
1458 Function->getMemberSpecializationInfo()) {
1459 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1460 SourceLocation Loc = R->getLocation(); // FIXME
1461 MSInfo->setPointOfInstantiation(Loc);
1462 SemaRef.PendingLocalImplicitInstantiations.push_back(
1463 std::make_pair(Function, Loc));
1464 QueuedInstantiation = true;
1465 }
1466 }
1467 }
1468
1469 // If some prior declaration of this function was a friend with an
1470 // uninstantiated definition, reject it.
1471 if (R->getFriendObjectKind()) {
1472 if (const FunctionDecl *RPattern =
1473 R->getTemplateInstantiationPattern()) {
1474 if (RPattern->isDefined(RPattern)) {
1475 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1476 << Function->getDeclName();
1477 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
1478 break;
1479 }
1480 }
1481 }
1482 }
1483 }
1484 }
1485
1486 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1487 DC->makeDeclVisibleInContext(PrincipalDecl);
1488
1489 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1490 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1491 PrincipalDecl->setNonMemberOperator();
1492
1493 assert(!D->isDefaulted() && "only methods should be defaulted");
1494 return Function;
1495 }
1496
1497 Decl *
VisitCXXMethodDecl(CXXMethodDecl * D,TemplateParameterList * TemplateParams,bool IsClassScopeSpecialization)1498 TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1499 TemplateParameterList *TemplateParams,
1500 bool IsClassScopeSpecialization) {
1501 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1502 if (FunctionTemplate && !TemplateParams) {
1503 // We are creating a function template specialization from a function
1504 // template. Check whether there is already a function template
1505 // specialization for this particular set of template arguments.
1506 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1507
1508 void *InsertPos = nullptr;
1509 FunctionDecl *SpecFunc
1510 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1511
1512 // If we already have a function template specialization, return it.
1513 if (SpecFunc)
1514 return SpecFunc;
1515 }
1516
1517 bool isFriend;
1518 if (FunctionTemplate)
1519 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1520 else
1521 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1522
1523 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1524 !(isa<Decl>(Owner) &&
1525 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1526 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1527
1528 // Instantiate enclosing template arguments for friends.
1529 SmallVector<TemplateParameterList *, 4> TempParamLists;
1530 unsigned NumTempParamLists = 0;
1531 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1532 TempParamLists.set_size(NumTempParamLists);
1533 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1534 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1535 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1536 if (!InstParams)
1537 return nullptr;
1538 TempParamLists[I] = InstParams;
1539 }
1540 }
1541
1542 SmallVector<ParmVarDecl *, 4> Params;
1543 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1544 if (!TInfo)
1545 return nullptr;
1546 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1547
1548 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1549 if (QualifierLoc) {
1550 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1551 TemplateArgs);
1552 if (!QualifierLoc)
1553 return nullptr;
1554 }
1555
1556 DeclContext *DC = Owner;
1557 if (isFriend) {
1558 if (QualifierLoc) {
1559 CXXScopeSpec SS;
1560 SS.Adopt(QualifierLoc);
1561 DC = SemaRef.computeDeclContext(SS);
1562
1563 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1564 return nullptr;
1565 } else {
1566 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1567 D->getDeclContext(),
1568 TemplateArgs);
1569 }
1570 if (!DC) return nullptr;
1571 }
1572
1573 // Build the instantiated method declaration.
1574 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1575 CXXMethodDecl *Method = nullptr;
1576
1577 SourceLocation StartLoc = D->getInnerLocStart();
1578 DeclarationNameInfo NameInfo
1579 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1580 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1581 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1582 StartLoc, NameInfo, T, TInfo,
1583 Constructor->isExplicit(),
1584 Constructor->isInlineSpecified(),
1585 false, Constructor->isConstexpr());
1586
1587 // Claim that the instantiation of a constructor or constructor template
1588 // inherits the same constructor that the template does.
1589 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1590 Constructor->getInheritedConstructor())) {
1591 // If we're instantiating a specialization of a function template, our
1592 // "inherited constructor" will actually itself be a function template.
1593 // Instantiate a declaration of it, too.
1594 if (FunctionTemplate) {
1595 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1596 !Inh->getParent()->isDependentContext() &&
1597 "inheriting constructor template in dependent context?");
1598 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1599 Inh);
1600 if (Inst.isInvalid())
1601 return nullptr;
1602 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1603 LocalInstantiationScope LocalScope(SemaRef);
1604
1605 // Use the same template arguments that we deduced for the inheriting
1606 // constructor. There's no way they could be deduced differently.
1607 MultiLevelTemplateArgumentList InheritedArgs;
1608 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1609 Inh = cast_or_null<CXXConstructorDecl>(
1610 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1611 if (!Inh)
1612 return nullptr;
1613 }
1614 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
1615 }
1616 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1617 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1618 StartLoc, NameInfo, T, TInfo,
1619 Destructor->isInlineSpecified(),
1620 false);
1621 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1622 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1623 StartLoc, NameInfo, T, TInfo,
1624 Conversion->isInlineSpecified(),
1625 Conversion->isExplicit(),
1626 Conversion->isConstexpr(),
1627 Conversion->getLocEnd());
1628 } else {
1629 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1630 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1631 StartLoc, NameInfo, T, TInfo,
1632 SC, D->isInlineSpecified(),
1633 D->isConstexpr(), D->getLocEnd());
1634 }
1635
1636 if (D->isInlined())
1637 Method->setImplicitlyInline();
1638
1639 if (QualifierLoc)
1640 Method->setQualifierInfo(QualifierLoc);
1641
1642 if (TemplateParams) {
1643 // Our resulting instantiation is actually a function template, since we
1644 // are substituting only the outer template parameters. For example, given
1645 //
1646 // template<typename T>
1647 // struct X {
1648 // template<typename U> void f(T, U);
1649 // };
1650 //
1651 // X<int> x;
1652 //
1653 // We are instantiating the member template "f" within X<int>, which means
1654 // substituting int for T, but leaving "f" as a member function template.
1655 // Build the function template itself.
1656 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1657 Method->getLocation(),
1658 Method->getDeclName(),
1659 TemplateParams, Method);
1660 if (isFriend) {
1661 FunctionTemplate->setLexicalDeclContext(Owner);
1662 FunctionTemplate->setObjectOfFriendDecl();
1663 } else if (D->isOutOfLine())
1664 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1665 Method->setDescribedFunctionTemplate(FunctionTemplate);
1666 } else if (FunctionTemplate) {
1667 // Record this function template specialization.
1668 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1669 Method->setFunctionTemplateSpecialization(FunctionTemplate,
1670 TemplateArgumentList::CreateCopy(SemaRef.Context,
1671 Innermost.begin(),
1672 Innermost.size()),
1673 /*InsertPos=*/nullptr);
1674 } else if (!isFriend) {
1675 // Record that this is an instantiation of a member function.
1676 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
1677 }
1678
1679 // If we are instantiating a member function defined
1680 // out-of-line, the instantiation will have the same lexical
1681 // context (which will be a namespace scope) as the template.
1682 if (isFriend) {
1683 if (NumTempParamLists)
1684 Method->setTemplateParameterListsInfo(SemaRef.Context,
1685 NumTempParamLists,
1686 TempParamLists.data());
1687
1688 Method->setLexicalDeclContext(Owner);
1689 Method->setObjectOfFriendDecl();
1690 } else if (D->isOutOfLine())
1691 Method->setLexicalDeclContext(D->getLexicalDeclContext());
1692
1693 // Attach the parameters
1694 for (unsigned P = 0; P < Params.size(); ++P)
1695 Params[P]->setOwningFunction(Method);
1696 Method->setParams(Params);
1697
1698 if (InitMethodInstantiation(Method, D))
1699 Method->setInvalidDecl();
1700
1701 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1702 Sema::ForRedeclaration);
1703
1704 if (!FunctionTemplate || TemplateParams || isFriend) {
1705 SemaRef.LookupQualifiedName(Previous, Record);
1706
1707 // In C++, the previous declaration we find might be a tag type
1708 // (class or enum). In this case, the new declaration will hide the
1709 // tag type. Note that this does does not apply if we're declaring a
1710 // typedef (C++ [dcl.typedef]p4).
1711 if (Previous.isSingleTagDecl())
1712 Previous.clear();
1713 }
1714
1715 if (!IsClassScopeSpecialization)
1716 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
1717
1718 if (D->isPure())
1719 SemaRef.CheckPureMethod(Method, SourceRange());
1720
1721 // Propagate access. For a non-friend declaration, the access is
1722 // whatever we're propagating from. For a friend, it should be the
1723 // previous declaration we just found.
1724 if (isFriend && Method->getPreviousDecl())
1725 Method->setAccess(Method->getPreviousDecl()->getAccess());
1726 else
1727 Method->setAccess(D->getAccess());
1728 if (FunctionTemplate)
1729 FunctionTemplate->setAccess(Method->getAccess());
1730
1731 SemaRef.CheckOverrideControl(Method);
1732
1733 // If a function is defined as defaulted or deleted, mark it as such now.
1734 if (D->isExplicitlyDefaulted())
1735 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1736 if (D->isDeletedAsWritten())
1737 SemaRef.SetDeclDeleted(Method, Method->getLocation());
1738
1739 // If there's a function template, let our caller handle it.
1740 if (FunctionTemplate) {
1741 // do nothing
1742
1743 // Don't hide a (potentially) valid declaration with an invalid one.
1744 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1745 // do nothing
1746
1747 // Otherwise, check access to friends and make them visible.
1748 } else if (isFriend) {
1749 // We only need to re-check access for methods which we didn't
1750 // manage to match during parsing.
1751 if (!D->getPreviousDecl())
1752 SemaRef.CheckFriendAccess(Method);
1753
1754 Record->makeDeclVisibleInContext(Method);
1755
1756 // Otherwise, add the declaration. We don't need to do this for
1757 // class-scope specializations because we'll have matched them with
1758 // the appropriate template.
1759 } else if (!IsClassScopeSpecialization) {
1760 Owner->addDecl(Method);
1761 }
1762
1763 return Method;
1764 }
1765
VisitCXXConstructorDecl(CXXConstructorDecl * D)1766 Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1767 return VisitCXXMethodDecl(D);
1768 }
1769
VisitCXXDestructorDecl(CXXDestructorDecl * D)1770 Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1771 return VisitCXXMethodDecl(D);
1772 }
1773
VisitCXXConversionDecl(CXXConversionDecl * D)1774 Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
1775 return VisitCXXMethodDecl(D);
1776 }
1777
VisitParmVarDecl(ParmVarDecl * D)1778 Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
1779 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1780 /*ExpectParameterPack=*/ false);
1781 }
1782
VisitTemplateTypeParmDecl(TemplateTypeParmDecl * D)1783 Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1784 TemplateTypeParmDecl *D) {
1785 // TODO: don't always clone when decls are refcounted.
1786 assert(D->getTypeForDecl()->isTemplateTypeParmType());
1787
1788 TemplateTypeParmDecl *Inst =
1789 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1790 D->getLocStart(), D->getLocation(),
1791 D->getDepth() - TemplateArgs.getNumLevels(),
1792 D->getIndex(), D->getIdentifier(),
1793 D->wasDeclaredWithTypename(),
1794 D->isParameterPack());
1795 Inst->setAccess(AS_public);
1796
1797 if (D->hasDefaultArgument()) {
1798 TypeSourceInfo *InstantiatedDefaultArg =
1799 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1800 D->getDefaultArgumentLoc(), D->getDeclName());
1801 if (InstantiatedDefaultArg)
1802 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1803 }
1804
1805 // Introduce this template parameter's instantiation into the instantiation
1806 // scope.
1807 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1808
1809 return Inst;
1810 }
1811
VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)1812 Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1813 NonTypeTemplateParmDecl *D) {
1814 // Substitute into the type of the non-type template parameter.
1815 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1816 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1817 SmallVector<QualType, 4> ExpandedParameterPackTypes;
1818 bool IsExpandedParameterPack = false;
1819 TypeSourceInfo *DI;
1820 QualType T;
1821 bool Invalid = false;
1822
1823 if (D->isExpandedParameterPack()) {
1824 // The non-type template parameter pack is an already-expanded pack
1825 // expansion of types. Substitute into each of the expanded types.
1826 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1827 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1828 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1829 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1830 TemplateArgs,
1831 D->getLocation(),
1832 D->getDeclName());
1833 if (!NewDI)
1834 return nullptr;
1835
1836 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1837 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1838 D->getLocation());
1839 if (NewT.isNull())
1840 return nullptr;
1841 ExpandedParameterPackTypes.push_back(NewT);
1842 }
1843
1844 IsExpandedParameterPack = true;
1845 DI = D->getTypeSourceInfo();
1846 T = DI->getType();
1847 } else if (D->isPackExpansion()) {
1848 // The non-type template parameter pack's type is a pack expansion of types.
1849 // Determine whether we need to expand this parameter pack into separate
1850 // types.
1851 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
1852 TypeLoc Pattern = Expansion.getPatternLoc();
1853 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1854 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1855
1856 // Determine whether the set of unexpanded parameter packs can and should
1857 // be expanded.
1858 bool Expand = true;
1859 bool RetainExpansion = false;
1860 Optional<unsigned> OrigNumExpansions
1861 = Expansion.getTypePtr()->getNumExpansions();
1862 Optional<unsigned> NumExpansions = OrigNumExpansions;
1863 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1864 Pattern.getSourceRange(),
1865 Unexpanded,
1866 TemplateArgs,
1867 Expand, RetainExpansion,
1868 NumExpansions))
1869 return nullptr;
1870
1871 if (Expand) {
1872 for (unsigned I = 0; I != *NumExpansions; ++I) {
1873 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1874 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1875 D->getLocation(),
1876 D->getDeclName());
1877 if (!NewDI)
1878 return nullptr;
1879
1880 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1881 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1882 NewDI->getType(),
1883 D->getLocation());
1884 if (NewT.isNull())
1885 return nullptr;
1886 ExpandedParameterPackTypes.push_back(NewT);
1887 }
1888
1889 // Note that we have an expanded parameter pack. The "type" of this
1890 // expanded parameter pack is the original expansion type, but callers
1891 // will end up using the expanded parameter pack types for type-checking.
1892 IsExpandedParameterPack = true;
1893 DI = D->getTypeSourceInfo();
1894 T = DI->getType();
1895 } else {
1896 // We cannot fully expand the pack expansion now, so substitute into the
1897 // pattern and create a new pack expansion type.
1898 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1899 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1900 D->getLocation(),
1901 D->getDeclName());
1902 if (!NewPattern)
1903 return nullptr;
1904
1905 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1906 NumExpansions);
1907 if (!DI)
1908 return nullptr;
1909
1910 T = DI->getType();
1911 }
1912 } else {
1913 // Simple case: substitution into a parameter that is not a parameter pack.
1914 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1915 D->getLocation(), D->getDeclName());
1916 if (!DI)
1917 return nullptr;
1918
1919 // Check that this type is acceptable for a non-type template parameter.
1920 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1921 D->getLocation());
1922 if (T.isNull()) {
1923 T = SemaRef.Context.IntTy;
1924 Invalid = true;
1925 }
1926 }
1927
1928 NonTypeTemplateParmDecl *Param;
1929 if (IsExpandedParameterPack)
1930 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1931 D->getInnerLocStart(),
1932 D->getLocation(),
1933 D->getDepth() - TemplateArgs.getNumLevels(),
1934 D->getPosition(),
1935 D->getIdentifier(), T,
1936 DI,
1937 ExpandedParameterPackTypes.data(),
1938 ExpandedParameterPackTypes.size(),
1939 ExpandedParameterPackTypesAsWritten.data());
1940 else
1941 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
1942 D->getInnerLocStart(),
1943 D->getLocation(),
1944 D->getDepth() - TemplateArgs.getNumLevels(),
1945 D->getPosition(),
1946 D->getIdentifier(), T,
1947 D->isParameterPack(), DI);
1948
1949 Param->setAccess(AS_public);
1950 if (Invalid)
1951 Param->setInvalidDecl();
1952
1953 if (D->hasDefaultArgument()) {
1954 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1955 if (!Value.isInvalid())
1956 Param->setDefaultArgument(Value.get(), false);
1957 }
1958
1959 // Introduce this template parameter's instantiation into the instantiation
1960 // scope.
1961 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1962 return Param;
1963 }
1964
collectUnexpandedParameterPacks(Sema & S,TemplateParameterList * Params,SmallVectorImpl<UnexpandedParameterPack> & Unexpanded)1965 static void collectUnexpandedParameterPacks(
1966 Sema &S,
1967 TemplateParameterList *Params,
1968 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1969 for (TemplateParameterList::const_iterator I = Params->begin(),
1970 E = Params->end(); I != E; ++I) {
1971 if ((*I)->isTemplateParameterPack())
1972 continue;
1973 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1974 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1975 Unexpanded);
1976 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1977 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1978 Unexpanded);
1979 }
1980 }
1981
1982 Decl *
VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl * D)1983 TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1984 TemplateTemplateParmDecl *D) {
1985 // Instantiate the template parameter list of the template template parameter.
1986 TemplateParameterList *TempParams = D->getTemplateParameters();
1987 TemplateParameterList *InstParams;
1988 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1989
1990 bool IsExpandedParameterPack = false;
1991
1992 if (D->isExpandedParameterPack()) {
1993 // The template template parameter pack is an already-expanded pack
1994 // expansion of template parameters. Substitute into each of the expanded
1995 // parameters.
1996 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1997 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1998 I != N; ++I) {
1999 LocalInstantiationScope Scope(SemaRef);
2000 TemplateParameterList *Expansion =
2001 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2002 if (!Expansion)
2003 return nullptr;
2004 ExpandedParams.push_back(Expansion);
2005 }
2006
2007 IsExpandedParameterPack = true;
2008 InstParams = TempParams;
2009 } else if (D->isPackExpansion()) {
2010 // The template template parameter pack expands to a pack of template
2011 // template parameters. Determine whether we need to expand this parameter
2012 // pack into separate parameters.
2013 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2014 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2015 Unexpanded);
2016
2017 // Determine whether the set of unexpanded parameter packs can and should
2018 // be expanded.
2019 bool Expand = true;
2020 bool RetainExpansion = false;
2021 Optional<unsigned> NumExpansions;
2022 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2023 TempParams->getSourceRange(),
2024 Unexpanded,
2025 TemplateArgs,
2026 Expand, RetainExpansion,
2027 NumExpansions))
2028 return nullptr;
2029
2030 if (Expand) {
2031 for (unsigned I = 0; I != *NumExpansions; ++I) {
2032 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2033 LocalInstantiationScope Scope(SemaRef);
2034 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2035 if (!Expansion)
2036 return nullptr;
2037 ExpandedParams.push_back(Expansion);
2038 }
2039
2040 // Note that we have an expanded parameter pack. The "type" of this
2041 // expanded parameter pack is the original expansion type, but callers
2042 // will end up using the expanded parameter pack types for type-checking.
2043 IsExpandedParameterPack = true;
2044 InstParams = TempParams;
2045 } else {
2046 // We cannot fully expand the pack expansion now, so just substitute
2047 // into the pattern.
2048 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2049
2050 LocalInstantiationScope Scope(SemaRef);
2051 InstParams = SubstTemplateParams(TempParams);
2052 if (!InstParams)
2053 return nullptr;
2054 }
2055 } else {
2056 // Perform the actual substitution of template parameters within a new,
2057 // local instantiation scope.
2058 LocalInstantiationScope Scope(SemaRef);
2059 InstParams = SubstTemplateParams(TempParams);
2060 if (!InstParams)
2061 return nullptr;
2062 }
2063
2064 // Build the template template parameter.
2065 TemplateTemplateParmDecl *Param;
2066 if (IsExpandedParameterPack)
2067 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2068 D->getLocation(),
2069 D->getDepth() - TemplateArgs.getNumLevels(),
2070 D->getPosition(),
2071 D->getIdentifier(), InstParams,
2072 ExpandedParams);
2073 else
2074 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2075 D->getLocation(),
2076 D->getDepth() - TemplateArgs.getNumLevels(),
2077 D->getPosition(),
2078 D->isParameterPack(),
2079 D->getIdentifier(), InstParams);
2080 if (D->hasDefaultArgument()) {
2081 NestedNameSpecifierLoc QualifierLoc =
2082 D->getDefaultArgument().getTemplateQualifierLoc();
2083 QualifierLoc =
2084 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2085 TemplateName TName = SemaRef.SubstTemplateName(
2086 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2087 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2088 if (!TName.isNull())
2089 Param->setDefaultArgument(
2090 TemplateArgumentLoc(TemplateArgument(TName),
2091 D->getDefaultArgument().getTemplateQualifierLoc(),
2092 D->getDefaultArgument().getTemplateNameLoc()),
2093 false);
2094 }
2095 Param->setAccess(AS_public);
2096
2097 // Introduce this template parameter's instantiation into the instantiation
2098 // scope.
2099 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2100
2101 return Param;
2102 }
2103
VisitUsingDirectiveDecl(UsingDirectiveDecl * D)2104 Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2105 // Using directives are never dependent (and never contain any types or
2106 // expressions), so they require no explicit instantiation work.
2107
2108 UsingDirectiveDecl *Inst
2109 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2110 D->getNamespaceKeyLocation(),
2111 D->getQualifierLoc(),
2112 D->getIdentLocation(),
2113 D->getNominatedNamespace(),
2114 D->getCommonAncestor());
2115
2116 // Add the using directive to its declaration context
2117 // only if this is not a function or method.
2118 if (!Owner->isFunctionOrMethod())
2119 Owner->addDecl(Inst);
2120
2121 return Inst;
2122 }
2123
VisitUsingDecl(UsingDecl * D)2124 Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2125
2126 // The nested name specifier may be dependent, for example
2127 // template <typename T> struct t {
2128 // struct s1 { T f1(); };
2129 // struct s2 : s1 { using s1::f1; };
2130 // };
2131 // template struct t<int>;
2132 // Here, in using s1::f1, s1 refers to t<T>::s1;
2133 // we need to substitute for t<int>::s1.
2134 NestedNameSpecifierLoc QualifierLoc
2135 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2136 TemplateArgs);
2137 if (!QualifierLoc)
2138 return nullptr;
2139
2140 // The name info is non-dependent, so no transformation
2141 // is required.
2142 DeclarationNameInfo NameInfo = D->getNameInfo();
2143
2144 // We only need to do redeclaration lookups if we're in a class
2145 // scope (in fact, it's not really even possible in non-class
2146 // scopes).
2147 bool CheckRedeclaration = Owner->isRecord();
2148
2149 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2150 Sema::ForRedeclaration);
2151
2152 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2153 D->getUsingLoc(),
2154 QualifierLoc,
2155 NameInfo,
2156 D->hasTypename());
2157
2158 CXXScopeSpec SS;
2159 SS.Adopt(QualifierLoc);
2160 if (CheckRedeclaration) {
2161 Prev.setHideTags(false);
2162 SemaRef.LookupQualifiedName(Prev, Owner);
2163
2164 // Check for invalid redeclarations.
2165 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2166 D->hasTypename(), SS,
2167 D->getLocation(), Prev))
2168 NewUD->setInvalidDecl();
2169
2170 }
2171
2172 if (!NewUD->isInvalidDecl() &&
2173 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
2174 D->getLocation()))
2175 NewUD->setInvalidDecl();
2176
2177 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2178 NewUD->setAccess(D->getAccess());
2179 Owner->addDecl(NewUD);
2180
2181 // Don't process the shadow decls for an invalid decl.
2182 if (NewUD->isInvalidDecl())
2183 return NewUD;
2184
2185 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2186 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2187 return NewUD;
2188 }
2189
2190 bool isFunctionScope = Owner->isFunctionOrMethod();
2191
2192 // Process the shadow decls.
2193 for (auto *Shadow : D->shadows()) {
2194 NamedDecl *InstTarget =
2195 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2196 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
2197 if (!InstTarget)
2198 return nullptr;
2199
2200 UsingShadowDecl *PrevDecl = nullptr;
2201 if (CheckRedeclaration) {
2202 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2203 continue;
2204 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2205 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2206 Shadow->getLocation(), OldPrev, TemplateArgs));
2207 }
2208
2209 UsingShadowDecl *InstShadow =
2210 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2211 PrevDecl);
2212 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2213
2214 if (isFunctionScope)
2215 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2216 }
2217
2218 return NewUD;
2219 }
2220
VisitUsingShadowDecl(UsingShadowDecl * D)2221 Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2222 // Ignore these; we handle them in bulk when processing the UsingDecl.
2223 return nullptr;
2224 }
2225
2226 Decl * TemplateDeclInstantiator
VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl * D)2227 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
2228 NestedNameSpecifierLoc QualifierLoc
2229 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2230 TemplateArgs);
2231 if (!QualifierLoc)
2232 return nullptr;
2233
2234 CXXScopeSpec SS;
2235 SS.Adopt(QualifierLoc);
2236
2237 // Since NameInfo refers to a typename, it cannot be a C++ special name.
2238 // Hence, no transformation is required for it.
2239 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
2240 NamedDecl *UD =
2241 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2242 D->getUsingLoc(), SS, NameInfo, nullptr,
2243 /*instantiation*/ true,
2244 /*typename*/ true, D->getTypenameLoc());
2245 if (UD)
2246 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2247
2248 return UD;
2249 }
2250
2251 Decl * TemplateDeclInstantiator
VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl * D)2252 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
2253 NestedNameSpecifierLoc QualifierLoc
2254 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2255 if (!QualifierLoc)
2256 return nullptr;
2257
2258 CXXScopeSpec SS;
2259 SS.Adopt(QualifierLoc);
2260
2261 DeclarationNameInfo NameInfo
2262 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2263
2264 NamedDecl *UD =
2265 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2266 D->getUsingLoc(), SS, NameInfo, nullptr,
2267 /*instantiation*/ true,
2268 /*typename*/ false, SourceLocation());
2269 if (UD)
2270 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2271
2272 return UD;
2273 }
2274
2275
VisitClassScopeFunctionSpecializationDecl(ClassScopeFunctionSpecializationDecl * Decl)2276 Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2277 ClassScopeFunctionSpecializationDecl *Decl) {
2278 CXXMethodDecl *OldFD = Decl->getSpecialization();
2279 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2280 nullptr, true));
2281
2282 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2283 Sema::ForRedeclaration);
2284
2285 TemplateArgumentListInfo TemplateArgs;
2286 TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
2287 if (Decl->hasExplicitTemplateArgs()) {
2288 TemplateArgs = Decl->templateArgs();
2289 TemplateArgsPtr = &TemplateArgs;
2290 }
2291
2292 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2293 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2294 Previous)) {
2295 NewFD->setInvalidDecl();
2296 return NewFD;
2297 }
2298
2299 // Associate the specialization with the pattern.
2300 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2301 assert(Specialization && "Class scope Specialization is null");
2302 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2303
2304 return NewFD;
2305 }
2306
VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl * D)2307 Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2308 OMPThreadPrivateDecl *D) {
2309 SmallVector<Expr *, 5> Vars;
2310 for (auto *I : D->varlists()) {
2311 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2312 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
2313 Vars.push_back(Var);
2314 }
2315
2316 OMPThreadPrivateDecl *TD =
2317 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2318
2319 TD->setAccess(AS_public);
2320 Owner->addDecl(TD);
2321
2322 return TD;
2323 }
2324
VisitFunctionDecl(FunctionDecl * D)2325 Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2326 return VisitFunctionDecl(D, nullptr);
2327 }
2328
VisitCXXMethodDecl(CXXMethodDecl * D)2329 Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2330 return VisitCXXMethodDecl(D, nullptr);
2331 }
2332
VisitRecordDecl(RecordDecl * D)2333 Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2334 llvm_unreachable("There are only CXXRecordDecls in C++");
2335 }
2336
2337 Decl *
VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl * D)2338 TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2339 ClassTemplateSpecializationDecl *D) {
2340 // As a MS extension, we permit class-scope explicit specialization
2341 // of member class templates.
2342 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2343 assert(ClassTemplate->getDeclContext()->isRecord() &&
2344 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2345 "can only instantiate an explicit specialization "
2346 "for a member class template");
2347
2348 // Lookup the already-instantiated declaration in the instantiation
2349 // of the class template. FIXME: Diagnose or assert if this fails?
2350 DeclContext::lookup_result Found
2351 = Owner->lookup(ClassTemplate->getDeclName());
2352 if (Found.empty())
2353 return nullptr;
2354 ClassTemplateDecl *InstClassTemplate
2355 = dyn_cast<ClassTemplateDecl>(Found.front());
2356 if (!InstClassTemplate)
2357 return nullptr;
2358
2359 // Substitute into the template arguments of the class template explicit
2360 // specialization.
2361 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2362 castAs<TemplateSpecializationTypeLoc>();
2363 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2364 Loc.getRAngleLoc());
2365 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2366 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2367 ArgLocs.push_back(Loc.getArgLoc(I));
2368 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2369 InstTemplateArgs, TemplateArgs))
2370 return nullptr;
2371
2372 // Check that the template argument list is well-formed for this
2373 // class template.
2374 SmallVector<TemplateArgument, 4> Converted;
2375 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2376 D->getLocation(),
2377 InstTemplateArgs,
2378 false,
2379 Converted))
2380 return nullptr;
2381
2382 // Figure out where to insert this class template explicit specialization
2383 // in the member template's set of class template explicit specializations.
2384 void *InsertPos = nullptr;
2385 ClassTemplateSpecializationDecl *PrevDecl =
2386 InstClassTemplate->findSpecialization(Converted, InsertPos);
2387
2388 // Check whether we've already seen a conflicting instantiation of this
2389 // declaration (for instance, if there was a prior implicit instantiation).
2390 bool Ignored;
2391 if (PrevDecl &&
2392 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2393 D->getSpecializationKind(),
2394 PrevDecl,
2395 PrevDecl->getSpecializationKind(),
2396 PrevDecl->getPointOfInstantiation(),
2397 Ignored))
2398 return nullptr;
2399
2400 // If PrevDecl was a definition and D is also a definition, diagnose.
2401 // This happens in cases like:
2402 //
2403 // template<typename T, typename U>
2404 // struct Outer {
2405 // template<typename X> struct Inner;
2406 // template<> struct Inner<T> {};
2407 // template<> struct Inner<U> {};
2408 // };
2409 //
2410 // Outer<int, int> outer; // error: the explicit specializations of Inner
2411 // // have the same signature.
2412 if (PrevDecl && PrevDecl->getDefinition() &&
2413 D->isThisDeclarationADefinition()) {
2414 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2415 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2416 diag::note_previous_definition);
2417 return nullptr;
2418 }
2419
2420 // Create the class template partial specialization declaration.
2421 ClassTemplateSpecializationDecl *InstD
2422 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2423 D->getTagKind(),
2424 Owner,
2425 D->getLocStart(),
2426 D->getLocation(),
2427 InstClassTemplate,
2428 Converted.data(),
2429 Converted.size(),
2430 PrevDecl);
2431
2432 // Add this partial specialization to the set of class template partial
2433 // specializations.
2434 if (!PrevDecl)
2435 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2436
2437 // Substitute the nested name specifier, if any.
2438 if (SubstQualifier(D, InstD))
2439 return nullptr;
2440
2441 // Build the canonical type that describes the converted template
2442 // arguments of the class template explicit specialization.
2443 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2444 TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2445 SemaRef.Context.getRecordType(InstD));
2446
2447 // Build the fully-sugared type for this class template
2448 // specialization as the user wrote in the specialization
2449 // itself. This means that we'll pretty-print the type retrieved
2450 // from the specialization's declaration the way that the user
2451 // actually wrote the specialization, rather than formatting the
2452 // name based on the "canonical" representation used to store the
2453 // template arguments in the specialization.
2454 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2455 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2456 CanonType);
2457
2458 InstD->setAccess(D->getAccess());
2459 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2460 InstD->setSpecializationKind(D->getSpecializationKind());
2461 InstD->setTypeAsWritten(WrittenTy);
2462 InstD->setExternLoc(D->getExternLoc());
2463 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2464
2465 Owner->addDecl(InstD);
2466
2467 // Instantiate the members of the class-scope explicit specialization eagerly.
2468 // We don't have support for lazy instantiation of an explicit specialization
2469 // yet, and MSVC eagerly instantiates in this case.
2470 if (D->isThisDeclarationADefinition() &&
2471 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2472 TSK_ImplicitInstantiation,
2473 /*Complain=*/true))
2474 return nullptr;
2475
2476 return InstD;
2477 }
2478
VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl * D)2479 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2480 VarTemplateSpecializationDecl *D) {
2481
2482 TemplateArgumentListInfo VarTemplateArgsInfo;
2483 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2484 assert(VarTemplate &&
2485 "A template specialization without specialized template?");
2486
2487 // Substitute the current template arguments.
2488 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2489 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2490 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2491
2492 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2493 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2494 return nullptr;
2495
2496 // Check that the template argument list is well-formed for this template.
2497 SmallVector<TemplateArgument, 4> Converted;
2498 if (SemaRef.CheckTemplateArgumentList(
2499 VarTemplate, VarTemplate->getLocStart(),
2500 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2501 Converted))
2502 return nullptr;
2503
2504 // Find the variable template specialization declaration that
2505 // corresponds to these arguments.
2506 void *InsertPos = nullptr;
2507 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2508 Converted, InsertPos))
2509 // If we already have a variable template specialization, return it.
2510 return VarSpec;
2511
2512 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2513 VarTemplateArgsInfo, Converted);
2514 }
2515
VisitVarTemplateSpecializationDecl(VarTemplateDecl * VarTemplate,VarDecl * D,void * InsertPos,const TemplateArgumentListInfo & TemplateArgsInfo,ArrayRef<TemplateArgument> Converted)2516 Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2517 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2518 const TemplateArgumentListInfo &TemplateArgsInfo,
2519 ArrayRef<TemplateArgument> Converted) {
2520
2521 // If this is the variable for an anonymous struct or union,
2522 // instantiate the anonymous struct/union type first.
2523 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2524 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2525 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2526 return nullptr;
2527
2528 // Do substitution on the type of the declaration
2529 TypeSourceInfo *DI =
2530 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2531 D->getTypeSpecStartLoc(), D->getDeclName());
2532 if (!DI)
2533 return nullptr;
2534
2535 if (DI->getType()->isFunctionType()) {
2536 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2537 << D->isStaticDataMember() << DI->getType();
2538 return nullptr;
2539 }
2540
2541 // Build the instantiated declaration
2542 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2543 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2544 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2545 Converted.size());
2546 Var->setTemplateArgsInfo(TemplateArgsInfo);
2547 if (InsertPos)
2548 VarTemplate->AddSpecialization(Var, InsertPos);
2549
2550 // Substitute the nested name specifier, if any.
2551 if (SubstQualifier(D, Var))
2552 return nullptr;
2553
2554 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2555 Owner, StartingScope);
2556
2557 return Var;
2558 }
2559
VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl * D)2560 Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2561 llvm_unreachable("@defs is not supported in Objective-C++");
2562 }
2563
VisitFriendTemplateDecl(FriendTemplateDecl * D)2564 Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2565 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2566 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2567 DiagnosticsEngine::Error,
2568 "cannot instantiate %0 yet");
2569 SemaRef.Diag(D->getLocation(), DiagID)
2570 << D->getDeclKindName();
2571
2572 return nullptr;
2573 }
2574
VisitDecl(Decl * D)2575 Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2576 llvm_unreachable("Unexpected decl");
2577 }
2578
SubstDecl(Decl * D,DeclContext * Owner,const MultiLevelTemplateArgumentList & TemplateArgs)2579 Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
2580 const MultiLevelTemplateArgumentList &TemplateArgs) {
2581 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
2582 if (D->isInvalidDecl())
2583 return nullptr;
2584
2585 return Instantiator.Visit(D);
2586 }
2587
2588 /// \brief Instantiates a nested template parameter list in the current
2589 /// instantiation context.
2590 ///
2591 /// \param L The parameter list to instantiate
2592 ///
2593 /// \returns NULL if there was an error
2594 TemplateParameterList *
SubstTemplateParams(TemplateParameterList * L)2595 TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
2596 // Get errors for all the parameters before bailing out.
2597 bool Invalid = false;
2598
2599 unsigned N = L->size();
2600 typedef SmallVector<NamedDecl *, 8> ParamVector;
2601 ParamVector Params;
2602 Params.reserve(N);
2603 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2604 PI != PE; ++PI) {
2605 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
2606 Params.push_back(D);
2607 Invalid = Invalid || !D || D->isInvalidDecl();
2608 }
2609
2610 // Clean up if we had an error.
2611 if (Invalid)
2612 return nullptr;
2613
2614 TemplateParameterList *InstL
2615 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2616 L->getLAngleLoc(), &Params.front(), N,
2617 L->getRAngleLoc());
2618 return InstL;
2619 }
2620
2621 /// \brief Instantiate the declaration of a class template partial
2622 /// specialization.
2623 ///
2624 /// \param ClassTemplate the (instantiated) class template that is partially
2625 // specialized by the instantiation of \p PartialSpec.
2626 ///
2627 /// \param PartialSpec the (uninstantiated) class template partial
2628 /// specialization that we are instantiating.
2629 ///
2630 /// \returns The instantiated partial specialization, if successful; otherwise,
2631 /// NULL to indicate an error.
2632 ClassTemplatePartialSpecializationDecl *
InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl * ClassTemplate,ClassTemplatePartialSpecializationDecl * PartialSpec)2633 TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2634 ClassTemplateDecl *ClassTemplate,
2635 ClassTemplatePartialSpecializationDecl *PartialSpec) {
2636 // Create a local instantiation scope for this class template partial
2637 // specialization, which will contain the instantiations of the template
2638 // parameters.
2639 LocalInstantiationScope Scope(SemaRef);
2640
2641 // Substitute into the template parameters of the class template partial
2642 // specialization.
2643 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2644 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2645 if (!InstParams)
2646 return nullptr;
2647
2648 // Substitute into the template arguments of the class template partial
2649 // specialization.
2650 const ASTTemplateArgumentListInfo *TemplArgInfo
2651 = PartialSpec->getTemplateArgsAsWritten();
2652 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2653 TemplArgInfo->RAngleLoc);
2654 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2655 TemplArgInfo->NumTemplateArgs,
2656 InstTemplateArgs, TemplateArgs))
2657 return nullptr;
2658
2659 // Check that the template argument list is well-formed for this
2660 // class template.
2661 SmallVector<TemplateArgument, 4> Converted;
2662 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
2663 PartialSpec->getLocation(),
2664 InstTemplateArgs,
2665 false,
2666 Converted))
2667 return nullptr;
2668
2669 // Figure out where to insert this class template partial specialization
2670 // in the member template's set of class template partial specializations.
2671 void *InsertPos = nullptr;
2672 ClassTemplateSpecializationDecl *PrevDecl
2673 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
2674
2675 // Build the canonical type that describes the converted template
2676 // arguments of the class template partial specialization.
2677 QualType CanonType
2678 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
2679 Converted.data(),
2680 Converted.size());
2681
2682 // Build the fully-sugared type for this class template
2683 // specialization as the user wrote in the specialization
2684 // itself. This means that we'll pretty-print the type retrieved
2685 // from the specialization's declaration the way that the user
2686 // actually wrote the specialization, rather than formatting the
2687 // name based on the "canonical" representation used to store the
2688 // template arguments in the specialization.
2689 TypeSourceInfo *WrittenTy
2690 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2691 TemplateName(ClassTemplate),
2692 PartialSpec->getLocation(),
2693 InstTemplateArgs,
2694 CanonType);
2695
2696 if (PrevDecl) {
2697 // We've already seen a partial specialization with the same template
2698 // parameters and template arguments. This can happen, for example, when
2699 // substituting the outer template arguments ends up causing two
2700 // class template partial specializations of a member class template
2701 // to have identical forms, e.g.,
2702 //
2703 // template<typename T, typename U>
2704 // struct Outer {
2705 // template<typename X, typename Y> struct Inner;
2706 // template<typename Y> struct Inner<T, Y>;
2707 // template<typename Y> struct Inner<U, Y>;
2708 // };
2709 //
2710 // Outer<int, int> outer; // error: the partial specializations of Inner
2711 // // have the same signature.
2712 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
2713 << WrittenTy->getType();
2714 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2715 << SemaRef.Context.getTypeDeclType(PrevDecl);
2716 return nullptr;
2717 }
2718
2719
2720 // Create the class template partial specialization declaration.
2721 ClassTemplatePartialSpecializationDecl *InstPartialSpec
2722 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
2723 PartialSpec->getTagKind(),
2724 Owner,
2725 PartialSpec->getLocStart(),
2726 PartialSpec->getLocation(),
2727 InstParams,
2728 ClassTemplate,
2729 Converted.data(),
2730 Converted.size(),
2731 InstTemplateArgs,
2732 CanonType,
2733 nullptr);
2734 // Substitute the nested name specifier, if any.
2735 if (SubstQualifier(PartialSpec, InstPartialSpec))
2736 return nullptr;
2737
2738 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2739 InstPartialSpec->setTypeAsWritten(WrittenTy);
2740
2741 // Add this partial specialization to the set of class template partial
2742 // specializations.
2743 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
2744 /*InsertPos=*/nullptr);
2745 return InstPartialSpec;
2746 }
2747
2748 /// \brief Instantiate the declaration of a variable template partial
2749 /// specialization.
2750 ///
2751 /// \param VarTemplate the (instantiated) variable template that is partially
2752 /// specialized by the instantiation of \p PartialSpec.
2753 ///
2754 /// \param PartialSpec the (uninstantiated) variable template partial
2755 /// specialization that we are instantiating.
2756 ///
2757 /// \returns The instantiated partial specialization, if successful; otherwise,
2758 /// NULL to indicate an error.
2759 VarTemplatePartialSpecializationDecl *
InstantiateVarTemplatePartialSpecialization(VarTemplateDecl * VarTemplate,VarTemplatePartialSpecializationDecl * PartialSpec)2760 TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2761 VarTemplateDecl *VarTemplate,
2762 VarTemplatePartialSpecializationDecl *PartialSpec) {
2763 // Create a local instantiation scope for this variable template partial
2764 // specialization, which will contain the instantiations of the template
2765 // parameters.
2766 LocalInstantiationScope Scope(SemaRef);
2767
2768 // Substitute into the template parameters of the variable template partial
2769 // specialization.
2770 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2771 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2772 if (!InstParams)
2773 return nullptr;
2774
2775 // Substitute into the template arguments of the variable template partial
2776 // specialization.
2777 const ASTTemplateArgumentListInfo *TemplArgInfo
2778 = PartialSpec->getTemplateArgsAsWritten();
2779 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2780 TemplArgInfo->RAngleLoc);
2781 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2782 TemplArgInfo->NumTemplateArgs,
2783 InstTemplateArgs, TemplateArgs))
2784 return nullptr;
2785
2786 // Check that the template argument list is well-formed for this
2787 // class template.
2788 SmallVector<TemplateArgument, 4> Converted;
2789 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2790 InstTemplateArgs, false, Converted))
2791 return nullptr;
2792
2793 // Figure out where to insert this variable template partial specialization
2794 // in the member template's set of variable template partial specializations.
2795 void *InsertPos = nullptr;
2796 VarTemplateSpecializationDecl *PrevDecl =
2797 VarTemplate->findPartialSpecialization(Converted, InsertPos);
2798
2799 // Build the canonical type that describes the converted template
2800 // arguments of the variable template partial specialization.
2801 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2802 TemplateName(VarTemplate), Converted.data(), Converted.size());
2803
2804 // Build the fully-sugared type for this variable template
2805 // specialization as the user wrote in the specialization
2806 // itself. This means that we'll pretty-print the type retrieved
2807 // from the specialization's declaration the way that the user
2808 // actually wrote the specialization, rather than formatting the
2809 // name based on the "canonical" representation used to store the
2810 // template arguments in the specialization.
2811 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2812 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2813 CanonType);
2814
2815 if (PrevDecl) {
2816 // We've already seen a partial specialization with the same template
2817 // parameters and template arguments. This can happen, for example, when
2818 // substituting the outer template arguments ends up causing two
2819 // variable template partial specializations of a member variable template
2820 // to have identical forms, e.g.,
2821 //
2822 // template<typename T, typename U>
2823 // struct Outer {
2824 // template<typename X, typename Y> pair<X,Y> p;
2825 // template<typename Y> pair<T, Y> p;
2826 // template<typename Y> pair<U, Y> p;
2827 // };
2828 //
2829 // Outer<int, int> outer; // error: the partial specializations of Inner
2830 // // have the same signature.
2831 SemaRef.Diag(PartialSpec->getLocation(),
2832 diag::err_var_partial_spec_redeclared)
2833 << WrittenTy->getType();
2834 SemaRef.Diag(PrevDecl->getLocation(),
2835 diag::note_var_prev_partial_spec_here);
2836 return nullptr;
2837 }
2838
2839 // Do substitution on the type of the declaration
2840 TypeSourceInfo *DI = SemaRef.SubstType(
2841 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2842 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2843 if (!DI)
2844 return nullptr;
2845
2846 if (DI->getType()->isFunctionType()) {
2847 SemaRef.Diag(PartialSpec->getLocation(),
2848 diag::err_variable_instantiates_to_function)
2849 << PartialSpec->isStaticDataMember() << DI->getType();
2850 return nullptr;
2851 }
2852
2853 // Create the variable template partial specialization declaration.
2854 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2855 VarTemplatePartialSpecializationDecl::Create(
2856 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2857 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2858 DI, PartialSpec->getStorageClass(), Converted.data(),
2859 Converted.size(), InstTemplateArgs);
2860
2861 // Substitute the nested name specifier, if any.
2862 if (SubstQualifier(PartialSpec, InstPartialSpec))
2863 return nullptr;
2864
2865 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2866 InstPartialSpec->setTypeAsWritten(WrittenTy);
2867
2868 // Add this partial specialization to the set of variable template partial
2869 // specializations. The instantiation of the initializer is not necessary.
2870 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
2871
2872 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
2873 LateAttrs, Owner, StartingScope);
2874
2875 return InstPartialSpec;
2876 }
2877
2878 TypeSourceInfo*
SubstFunctionType(FunctionDecl * D,SmallVectorImpl<ParmVarDecl * > & Params)2879 TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
2880 SmallVectorImpl<ParmVarDecl *> &Params) {
2881 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2882 assert(OldTInfo && "substituting function without type source info");
2883 assert(Params.empty() && "parameter vector is non-empty at start");
2884
2885 CXXRecordDecl *ThisContext = nullptr;
2886 unsigned ThisTypeQuals = 0;
2887 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2888 ThisContext = cast<CXXRecordDecl>(Owner);
2889 ThisTypeQuals = Method->getTypeQualifiers();
2890 }
2891
2892 TypeSourceInfo *NewTInfo
2893 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2894 D->getTypeSpecStartLoc(),
2895 D->getDeclName(),
2896 ThisContext, ThisTypeQuals);
2897 if (!NewTInfo)
2898 return nullptr;
2899
2900 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2901 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2902 if (NewTInfo != OldTInfo) {
2903 // Get parameters from the new type info.
2904 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
2905 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
2906 unsigned NewIdx = 0;
2907 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
2908 OldIdx != NumOldParams; ++OldIdx) {
2909 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
2910 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2911
2912 Optional<unsigned> NumArgumentsInExpansion;
2913 if (OldParam->isParameterPack())
2914 NumArgumentsInExpansion =
2915 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2916 TemplateArgs);
2917 if (!NumArgumentsInExpansion) {
2918 // Simple case: normal parameter, or a parameter pack that's
2919 // instantiated to a (still-dependent) parameter pack.
2920 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
2921 Params.push_back(NewParam);
2922 Scope->InstantiatedLocal(OldParam, NewParam);
2923 } else {
2924 // Parameter pack expansion: make the instantiation an argument pack.
2925 Scope->MakeInstantiatedLocalArgPack(OldParam);
2926 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
2927 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
2928 Params.push_back(NewParam);
2929 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2930 }
2931 }
2932 }
2933 } else {
2934 // The function type itself was not dependent and therefore no
2935 // substitution occurred. However, we still need to instantiate
2936 // the function parameters themselves.
2937 const FunctionProtoType *OldProto =
2938 cast<FunctionProtoType>(OldProtoLoc.getType());
2939 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
2940 ++i) {
2941 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
2942 if (!OldParam) {
2943 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2944 D, D->getLocation(), OldProto->getParamType(i)));
2945 continue;
2946 }
2947
2948 ParmVarDecl *Parm =
2949 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
2950 if (!Parm)
2951 return nullptr;
2952 Params.push_back(Parm);
2953 }
2954 }
2955 } else {
2956 // If the type of this function, after ignoring parentheses, is not
2957 // *directly* a function type, then we're instantiating a function that
2958 // was declared via a typedef or with attributes, e.g.,
2959 //
2960 // typedef int functype(int, int);
2961 // functype func;
2962 // int __cdecl meth(int, int);
2963 //
2964 // In this case, we'll just go instantiate the ParmVarDecls that we
2965 // synthesized in the method declaration.
2966 SmallVector<QualType, 4> ParamTypes;
2967 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2968 D->getNumParams(), TemplateArgs, ParamTypes,
2969 &Params))
2970 return nullptr;
2971 }
2972
2973 return NewTInfo;
2974 }
2975
2976 /// Introduce the instantiated function parameters into the local
2977 /// instantiation scope, and set the parameter names to those used
2978 /// in the template.
addInstantiatedParametersToScope(Sema & S,FunctionDecl * Function,const FunctionDecl * PatternDecl,LocalInstantiationScope & Scope,const MultiLevelTemplateArgumentList & TemplateArgs)2979 static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2980 const FunctionDecl *PatternDecl,
2981 LocalInstantiationScope &Scope,
2982 const MultiLevelTemplateArgumentList &TemplateArgs) {
2983 unsigned FParamIdx = 0;
2984 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2985 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2986 if (!PatternParam->isParameterPack()) {
2987 // Simple case: not a parameter pack.
2988 assert(FParamIdx < Function->getNumParams());
2989 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2990 // If the parameter's type is not dependent, update it to match the type
2991 // in the pattern. They can differ in top-level cv-qualifiers, and we want
2992 // the pattern's type here. If the type is dependent, they can't differ,
2993 // per core issue 1668.
2994 // FIXME: Updating the type to work around this is at best fragile.
2995 if (!PatternDecl->getType()->isDependentType())
2996 FunctionParam->setType(PatternParam->getType());
2997
2998 FunctionParam->setDeclName(PatternParam->getDeclName());
2999 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3000 ++FParamIdx;
3001 continue;
3002 }
3003
3004 // Expand the parameter pack.
3005 Scope.MakeInstantiatedLocalArgPack(PatternParam);
3006 Optional<unsigned> NumArgumentsInExpansion
3007 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3008 assert(NumArgumentsInExpansion &&
3009 "should only be called when all template arguments are known");
3010 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3011 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3012 if (!PatternDecl->getType()->isDependentType())
3013 FunctionParam->setType(PatternParam->getType());
3014
3015 FunctionParam->setDeclName(PatternParam->getDeclName());
3016 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3017 ++FParamIdx;
3018 }
3019 }
3020 }
3021
InstantiateExceptionSpec(Sema & SemaRef,FunctionDecl * New,const FunctionProtoType * Proto,const MultiLevelTemplateArgumentList & TemplateArgs)3022 static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
3023 const FunctionProtoType *Proto,
3024 const MultiLevelTemplateArgumentList &TemplateArgs) {
3025 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
3026
3027 // C++11 [expr.prim.general]p3:
3028 // If a declaration declares a member function or member function
3029 // template of a class X, the expression this is a prvalue of type
3030 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3031 // and the end of the function-definition, member-declarator, or
3032 // declarator.
3033 CXXRecordDecl *ThisContext = nullptr;
3034 unsigned ThisTypeQuals = 0;
3035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
3036 ThisContext = Method->getParent();
3037 ThisTypeQuals = Method->getTypeQualifiers();
3038 }
3039 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
3040 SemaRef.getLangOpts().CPlusPlus11);
3041
3042 // The function has an exception specification or a "noreturn"
3043 // attribute. Substitute into each of the exception types.
3044 SmallVector<QualType, 4> Exceptions;
3045 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
3046 // FIXME: Poor location information!
3047 if (const PackExpansionType *PackExpansion
3048 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
3049 // We have a pack expansion. Instantiate it.
3050 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3051 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
3052 Unexpanded);
3053 assert(!Unexpanded.empty() &&
3054 "Pack expansion without parameter packs?");
3055
3056 bool Expand = false;
3057 bool RetainExpansion = false;
3058 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
3059 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
3060 SourceRange(),
3061 Unexpanded,
3062 TemplateArgs,
3063 Expand,
3064 RetainExpansion,
3065 NumExpansions))
3066 break;
3067
3068 if (!Expand) {
3069 // We can't expand this pack expansion into separate arguments yet;
3070 // just substitute into the pattern and create a new pack expansion
3071 // type.
3072 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3073 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3074 TemplateArgs,
3075 New->getLocation(), New->getDeclName());
3076 if (T.isNull())
3077 break;
3078
3079 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
3080 Exceptions.push_back(T);
3081 continue;
3082 }
3083
3084 // Substitute into the pack expansion pattern for each template
3085 bool Invalid = false;
3086 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
3087 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
3088
3089 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3090 TemplateArgs,
3091 New->getLocation(), New->getDeclName());
3092 if (T.isNull()) {
3093 Invalid = true;
3094 break;
3095 }
3096
3097 Exceptions.push_back(T);
3098 }
3099
3100 if (Invalid)
3101 break;
3102
3103 continue;
3104 }
3105
3106 QualType T
3107 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
3108 New->getLocation(), New->getDeclName());
3109 if (T.isNull() ||
3110 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
3111 continue;
3112
3113 Exceptions.push_back(T);
3114 }
3115 Expr *NoexceptExpr = nullptr;
3116 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
3117 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3118 Sema::ConstantEvaluated);
3119 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
3120 if (E.isUsable())
3121 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
3122
3123 if (E.isUsable()) {
3124 NoexceptExpr = E.get();
3125 if (!NoexceptExpr->isTypeDependent() &&
3126 !NoexceptExpr->isValueDependent())
3127 NoexceptExpr
3128 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
3129 nullptr, diag::err_noexcept_needs_constant_expression,
3130 /*AllowFold*/ false).get();
3131 }
3132 }
3133
3134 FunctionProtoType::ExtProtoInfo EPI;
3135 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
3136 EPI.NumExceptions = Exceptions.size();
3137 EPI.Exceptions = Exceptions.data();
3138 EPI.NoexceptExpr = NoexceptExpr;
3139
3140 SemaRef.UpdateExceptionSpec(New, EPI);
3141 }
3142
InstantiateExceptionSpec(SourceLocation PointOfInstantiation,FunctionDecl * Decl)3143 void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3144 FunctionDecl *Decl) {
3145 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3146 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3147 return;
3148
3149 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3150 InstantiatingTemplate::ExceptionSpecification());
3151 if (Inst.isInvalid()) {
3152 // We hit the instantiation depth limit. Clear the exception specification
3153 // so that our callers don't have to cope with EST_Uninstantiated.
3154 FunctionProtoType::ExtProtoInfo EPI;
3155 EPI.ExceptionSpecType = EST_None;
3156 UpdateExceptionSpec(Decl, EPI);
3157 return;
3158 }
3159
3160 // Enter the scope of this instantiation. We don't use
3161 // PushDeclContext because we don't have a scope.
3162 Sema::ContextRAII savedContext(*this, Decl);
3163 LocalInstantiationScope Scope(*this);
3164
3165 MultiLevelTemplateArgumentList TemplateArgs =
3166 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3167
3168 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3169 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
3170
3171 ::InstantiateExceptionSpec(*this, Decl,
3172 Template->getType()->castAs<FunctionProtoType>(),
3173 TemplateArgs);
3174 }
3175
3176 /// \brief Initializes the common fields of an instantiation function
3177 /// declaration (New) from the corresponding fields of its template (Tmpl).
3178 ///
3179 /// \returns true if there was an error
3180 bool
InitFunctionInstantiation(FunctionDecl * New,FunctionDecl * Tmpl)3181 TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3182 FunctionDecl *Tmpl) {
3183 if (Tmpl->isDeleted())
3184 New->setDeletedAsWritten();
3185
3186 // Forward the mangling number from the template to the instantiated decl.
3187 SemaRef.Context.setManglingNumber(New,
3188 SemaRef.Context.getManglingNumber(Tmpl));
3189
3190 // If we are performing substituting explicitly-specified template arguments
3191 // or deduced template arguments into a function template and we reach this
3192 // point, we are now past the point where SFINAE applies and have committed
3193 // to keeping the new function template specialization. We therefore
3194 // convert the active template instantiation for the function template
3195 // into a template instantiation for this specific function template
3196 // specialization, which is not a SFINAE context, so that we diagnose any
3197 // further errors in the declaration itself.
3198 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3199 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3200 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3201 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3202 if (FunctionTemplateDecl *FunTmpl
3203 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3204 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
3205 "Deduction from the wrong function template?");
3206 (void) FunTmpl;
3207 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3208 ActiveInst.Entity = New;
3209 }
3210 }
3211
3212 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3213 assert(Proto && "Function template without prototype?");
3214
3215 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3216 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3217
3218 // DR1330: In C++11, defer instantiation of a non-trivial
3219 // exception specification.
3220 if (SemaRef.getLangOpts().CPlusPlus11 &&
3221 EPI.ExceptionSpecType != EST_None &&
3222 EPI.ExceptionSpecType != EST_DynamicNone &&
3223 EPI.ExceptionSpecType != EST_BasicNoexcept) {
3224 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3225 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3226 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
3227 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3228 if (EPI.ExceptionSpecType == EST_Unevaluated)
3229 NewEST = EST_Unevaluated;
3230
3231 // Mark the function has having an uninstantiated exception specification.
3232 const FunctionProtoType *NewProto
3233 = New->getType()->getAs<FunctionProtoType>();
3234 assert(NewProto && "Template instantiation without function prototype?");
3235 EPI = NewProto->getExtProtoInfo();
3236 EPI.ExceptionSpecType = NewEST;
3237 EPI.ExceptionSpecDecl = New;
3238 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
3239 New->setType(SemaRef.Context.getFunctionType(
3240 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3241 } else {
3242 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3243 }
3244 }
3245
3246 // Get the definition. Leaves the variable unchanged if undefined.
3247 const FunctionDecl *Definition = Tmpl;
3248 Tmpl->isDefined(Definition);
3249
3250 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3251 LateAttrs, StartingScope);
3252
3253 return false;
3254 }
3255
3256 /// \brief Initializes common fields of an instantiated method
3257 /// declaration (New) from the corresponding fields of its template
3258 /// (Tmpl).
3259 ///
3260 /// \returns true if there was an error
3261 bool
InitMethodInstantiation(CXXMethodDecl * New,CXXMethodDecl * Tmpl)3262 TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3263 CXXMethodDecl *Tmpl) {
3264 if (InitFunctionInstantiation(New, Tmpl))
3265 return true;
3266
3267 New->setAccess(Tmpl->getAccess());
3268 if (Tmpl->isVirtualAsWritten())
3269 New->setVirtualAsWritten(true);
3270
3271 // FIXME: New needs a pointer to Tmpl
3272 return false;
3273 }
3274
3275 /// \brief Instantiate the definition of the given function from its
3276 /// template.
3277 ///
3278 /// \param PointOfInstantiation the point at which the instantiation was
3279 /// required. Note that this is not precisely a "point of instantiation"
3280 /// for the function, but it's close.
3281 ///
3282 /// \param Function the already-instantiated declaration of a
3283 /// function template specialization or member function of a class template
3284 /// specialization.
3285 ///
3286 /// \param Recursive if true, recursively instantiates any functions that
3287 /// are required by this instantiation.
3288 ///
3289 /// \param DefinitionRequired if true, then we are performing an explicit
3290 /// instantiation where the body of the function is required. Complain if
3291 /// there is no such body.
InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,FunctionDecl * Function,bool Recursive,bool DefinitionRequired)3292 void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3293 FunctionDecl *Function,
3294 bool Recursive,
3295 bool DefinitionRequired) {
3296 if (Function->isInvalidDecl() || Function->isDefined())
3297 return;
3298
3299 // Never instantiate an explicit specialization except if it is a class scope
3300 // explicit specialization.
3301 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3302 !Function->getClassScopeSpecializationPattern())
3303 return;
3304
3305 // Find the function body that we'll be substituting.
3306 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3307 assert(PatternDecl && "instantiating a non-template");
3308
3309 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3310 assert(PatternDecl && "template definition is not a template");
3311 if (!Pattern) {
3312 // Try to find a defaulted definition
3313 PatternDecl->isDefined(PatternDecl);
3314 }
3315 assert(PatternDecl && "template definition is not a template");
3316
3317 // Postpone late parsed template instantiations.
3318 if (PatternDecl->isLateTemplateParsed() &&
3319 !LateTemplateParser) {
3320 PendingInstantiations.push_back(
3321 std::make_pair(Function, PointOfInstantiation));
3322 return;
3323 }
3324
3325 // Call the LateTemplateParser callback if there is a need to late parse
3326 // a templated function definition.
3327 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3328 LateTemplateParser) {
3329 // FIXME: Optimize to allow individual templates to be deserialized.
3330 if (PatternDecl->isFromASTFile())
3331 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3332
3333 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3334 assert(LPT && "missing LateParsedTemplate");
3335 LateTemplateParser(OpaqueParser, *LPT);
3336 Pattern = PatternDecl->getBody(PatternDecl);
3337 }
3338
3339 if (!Pattern && !PatternDecl->isDefaulted()) {
3340 if (DefinitionRequired) {
3341 if (Function->getPrimaryTemplate())
3342 Diag(PointOfInstantiation,
3343 diag::err_explicit_instantiation_undefined_func_template)
3344 << Function->getPrimaryTemplate();
3345 else
3346 Diag(PointOfInstantiation,
3347 diag::err_explicit_instantiation_undefined_member)
3348 << 1 << Function->getDeclName() << Function->getDeclContext();
3349
3350 if (PatternDecl)
3351 Diag(PatternDecl->getLocation(),
3352 diag::note_explicit_instantiation_here);
3353 Function->setInvalidDecl();
3354 } else if (Function->getTemplateSpecializationKind()
3355 == TSK_ExplicitInstantiationDefinition) {
3356 PendingInstantiations.push_back(
3357 std::make_pair(Function, PointOfInstantiation));
3358 }
3359
3360 return;
3361 }
3362
3363 // C++1y [temp.explicit]p10:
3364 // Except for inline functions, declarations with types deduced from their
3365 // initializer or return value, and class template specializations, other
3366 // explicit instantiation declarations have the effect of suppressing the
3367 // implicit instantiation of the entity to which they refer.
3368 if (Function->getTemplateSpecializationKind() ==
3369 TSK_ExplicitInstantiationDeclaration &&
3370 !PatternDecl->isInlined() &&
3371 !PatternDecl->getReturnType()->getContainedAutoType())
3372 return;
3373
3374 if (PatternDecl->isInlined()) {
3375 // Function, and all later redeclarations of it (from imported modules,
3376 // for instance), are now implicitly inline.
3377 for (auto *D = Function->getMostRecentDecl(); /**/;
3378 D = D->getPreviousDecl()) {
3379 D->setImplicitlyInline();
3380 if (D == Function)
3381 break;
3382 }
3383 }
3384
3385 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3386 if (Inst.isInvalid())
3387 return;
3388
3389 // Copy the inner loc start from the pattern.
3390 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3391
3392 // If we're performing recursive template instantiation, create our own
3393 // queue of pending implicit instantiations that we will instantiate later,
3394 // while we're still within our own instantiation context.
3395 SmallVector<VTableUse, 16> SavedVTableUses;
3396 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3397 SavePendingLocalImplicitInstantiationsRAII
3398 SavedPendingLocalImplicitInstantiations(*this);
3399 if (Recursive) {
3400 VTableUses.swap(SavedVTableUses);
3401 PendingInstantiations.swap(SavedPendingInstantiations);
3402 }
3403
3404 EnterExpressionEvaluationContext EvalContext(*this,
3405 Sema::PotentiallyEvaluated);
3406
3407 // Introduce a new scope where local variable instantiations will be
3408 // recorded, unless we're actually a member function within a local
3409 // class, in which case we need to merge our results with the parent
3410 // scope (of the enclosing function).
3411 bool MergeWithParentScope = false;
3412 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3413 MergeWithParentScope = Rec->isLocalClass();
3414
3415 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3416
3417 if (PatternDecl->isDefaulted())
3418 SetDeclDefaulted(Function, PatternDecl->getLocation());
3419 else {
3420 ActOnStartOfFunctionDef(nullptr, Function);
3421
3422 // Enter the scope of this instantiation. We don't use
3423 // PushDeclContext because we don't have a scope.
3424 Sema::ContextRAII savedContext(*this, Function);
3425
3426 MultiLevelTemplateArgumentList TemplateArgs =
3427 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3428
3429 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3430 TemplateArgs);
3431
3432 // If this is a constructor, instantiate the member initializers.
3433 if (const CXXConstructorDecl *Ctor =
3434 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3435 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3436 TemplateArgs);
3437 }
3438
3439 // Instantiate the function body.
3440 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3441
3442 if (Body.isInvalid())
3443 Function->setInvalidDecl();
3444
3445 ActOnFinishFunctionBody(Function, Body.get(),
3446 /*IsInstantiation=*/true);
3447
3448 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3449
3450 if (auto *Listener = getASTMutationListener())
3451 Listener->FunctionDefinitionInstantiated(Function);
3452
3453 savedContext.pop();
3454 }
3455
3456 DeclGroupRef DG(Function);
3457 Consumer.HandleTopLevelDecl(DG);
3458
3459 // This class may have local implicit instantiations that need to be
3460 // instantiation within this scope.
3461 PerformPendingInstantiations(/*LocalOnly=*/true);
3462 Scope.Exit();
3463
3464 if (Recursive) {
3465 // Define any pending vtables.
3466 DefineUsedVTables();
3467
3468 // Instantiate any pending implicit instantiations found during the
3469 // instantiation of this template.
3470 PerformPendingInstantiations();
3471
3472 // Restore the set of pending vtables.
3473 assert(VTableUses.empty() &&
3474 "VTableUses should be empty before it is discarded.");
3475 VTableUses.swap(SavedVTableUses);
3476
3477 // Restore the set of pending implicit instantiations.
3478 assert(PendingInstantiations.empty() &&
3479 "PendingInstantiations should be empty before it is discarded.");
3480 PendingInstantiations.swap(SavedPendingInstantiations);
3481 }
3482 }
3483
BuildVarTemplateInstantiation(VarTemplateDecl * VarTemplate,VarDecl * FromVar,const TemplateArgumentList & TemplateArgList,const TemplateArgumentListInfo & TemplateArgsInfo,SmallVectorImpl<TemplateArgument> & Converted,SourceLocation PointOfInstantiation,void * InsertPos,LateInstantiatedAttrVec * LateAttrs,LocalInstantiationScope * StartingScope)3484 VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3485 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3486 const TemplateArgumentList &TemplateArgList,
3487 const TemplateArgumentListInfo &TemplateArgsInfo,
3488 SmallVectorImpl<TemplateArgument> &Converted,
3489 SourceLocation PointOfInstantiation, void *InsertPos,
3490 LateInstantiatedAttrVec *LateAttrs,
3491 LocalInstantiationScope *StartingScope) {
3492 if (FromVar->isInvalidDecl())
3493 return nullptr;
3494
3495 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3496 if (Inst.isInvalid())
3497 return nullptr;
3498
3499 MultiLevelTemplateArgumentList TemplateArgLists;
3500 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3501
3502 // Instantiate the first declaration of the variable template: for a partial
3503 // specialization of a static data member template, the first declaration may
3504 // or may not be the declaration in the class; if it's in the class, we want
3505 // to instantiate a member in the class (a declaration), and if it's outside,
3506 // we want to instantiate a definition.
3507 //
3508 // If we're instantiating an explicitly-specialized member template or member
3509 // partial specialization, don't do this. The member specialization completely
3510 // replaces the original declaration in this case.
3511 bool IsMemberSpec = false;
3512 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3513 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3514 IsMemberSpec = PartialSpec->isMemberSpecialization();
3515 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3516 IsMemberSpec = FromTemplate->isMemberSpecialization();
3517 if (!IsMemberSpec)
3518 FromVar = FromVar->getFirstDecl();
3519
3520 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3521 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3522 MultiLevelList);
3523
3524 // TODO: Set LateAttrs and StartingScope ...
3525
3526 return cast_or_null<VarTemplateSpecializationDecl>(
3527 Instantiator.VisitVarTemplateSpecializationDecl(
3528 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3529 }
3530
3531 /// \brief Instantiates a variable template specialization by completing it
3532 /// with appropriate type information and initializer.
CompleteVarTemplateSpecializationDecl(VarTemplateSpecializationDecl * VarSpec,VarDecl * PatternDecl,const MultiLevelTemplateArgumentList & TemplateArgs)3533 VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3534 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3535 const MultiLevelTemplateArgumentList &TemplateArgs) {
3536
3537 // Do substitution on the type of the declaration
3538 TypeSourceInfo *DI =
3539 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
3540 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3541 if (!DI)
3542 return nullptr;
3543
3544 // Update the type of this variable template specialization.
3545 VarSpec->setType(DI->getType());
3546
3547 // Instantiate the initializer.
3548 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3549
3550 return VarSpec;
3551 }
3552
3553 /// BuildVariableInstantiation - Used after a new variable has been created.
3554 /// Sets basic variable data and decides whether to postpone the
3555 /// variable instantiation.
BuildVariableInstantiation(VarDecl * NewVar,VarDecl * OldVar,const MultiLevelTemplateArgumentList & TemplateArgs,LateInstantiatedAttrVec * LateAttrs,DeclContext * Owner,LocalInstantiationScope * StartingScope,bool InstantiatingVarTemplate)3556 void Sema::BuildVariableInstantiation(
3557 VarDecl *NewVar, VarDecl *OldVar,
3558 const MultiLevelTemplateArgumentList &TemplateArgs,
3559 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3560 LocalInstantiationScope *StartingScope,
3561 bool InstantiatingVarTemplate) {
3562
3563 // If we are instantiating a local extern declaration, the
3564 // instantiation belongs lexically to the containing function.
3565 // If we are instantiating a static data member defined
3566 // out-of-line, the instantiation will have the same lexical
3567 // context (which will be a namespace scope) as the template.
3568 if (OldVar->isLocalExternDecl()) {
3569 NewVar->setLocalExternDecl();
3570 NewVar->setLexicalDeclContext(Owner);
3571 } else if (OldVar->isOutOfLine())
3572 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3573 NewVar->setTSCSpec(OldVar->getTSCSpec());
3574 NewVar->setInitStyle(OldVar->getInitStyle());
3575 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3576 NewVar->setConstexpr(OldVar->isConstexpr());
3577 NewVar->setInitCapture(OldVar->isInitCapture());
3578 NewVar->setPreviousDeclInSameBlockScope(
3579 OldVar->isPreviousDeclInSameBlockScope());
3580 NewVar->setAccess(OldVar->getAccess());
3581
3582 if (!OldVar->isStaticDataMember()) {
3583 if (OldVar->isUsed(false))
3584 NewVar->setIsUsed();
3585 NewVar->setReferenced(OldVar->isReferenced());
3586 }
3587
3588 // See if the old variable had a type-specifier that defined an anonymous tag.
3589 // If it did, mark the new variable as being the declarator for the new
3590 // anonymous tag.
3591 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3592 TagDecl *OldTag = OldTagType->getDecl();
3593 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3594 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3595 assert(!NewTag->hasNameForLinkage() &&
3596 !NewTag->hasDeclaratorForAnonDecl());
3597 NewTag->setDeclaratorForAnonDecl(NewVar);
3598 }
3599 }
3600
3601 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3602
3603 LookupResult Previous(
3604 *this, NewVar->getDeclName(), NewVar->getLocation(),
3605 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3606 : Sema::LookupOrdinaryName,
3607 Sema::ForRedeclaration);
3608
3609 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3610 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3611 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
3612 // We have a previous declaration. Use that one, so we merge with the
3613 // right type.
3614 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3615 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3616 Previous.addDecl(NewPrev);
3617 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3618 OldVar->hasLinkage())
3619 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3620 CheckVariableDeclaration(NewVar, Previous);
3621
3622 if (!InstantiatingVarTemplate) {
3623 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3624 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
3625 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3626 }
3627
3628 if (!OldVar->isOutOfLine()) {
3629 if (NewVar->getDeclContext()->isFunctionOrMethod())
3630 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3631 }
3632
3633 // Link instantiations of static data members back to the template from
3634 // which they were instantiated.
3635 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
3636 NewVar->setInstantiationOfStaticDataMember(OldVar,
3637 TSK_ImplicitInstantiation);
3638
3639 // Forward the mangling number from the template to the instantiated decl.
3640 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
3641 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
3642
3643 // Delay instantiation of the initializer for variable templates until a
3644 // definition of the variable is needed. We need it right away if the type
3645 // contains 'auto'.
3646 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3647 !InstantiatingVarTemplate) ||
3648 NewVar->getType()->isUndeducedType())
3649 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3650
3651 // Diagnose unused local variables with dependent types, where the diagnostic
3652 // will have been deferred.
3653 if (!NewVar->isInvalidDecl() &&
3654 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3655 OldVar->getType()->isDependentType())
3656 DiagnoseUnusedDecl(NewVar);
3657 }
3658
3659 /// \brief Instantiate the initializer of a variable.
InstantiateVariableInitializer(VarDecl * Var,VarDecl * OldVar,const MultiLevelTemplateArgumentList & TemplateArgs)3660 void Sema::InstantiateVariableInitializer(
3661 VarDecl *Var, VarDecl *OldVar,
3662 const MultiLevelTemplateArgumentList &TemplateArgs) {
3663
3664 if (Var->getAnyInitializer())
3665 // We already have an initializer in the class.
3666 return;
3667
3668 if (OldVar->getInit()) {
3669 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3670 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3671 else
3672 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3673
3674 // Instantiate the initializer.
3675 ExprResult Init =
3676 SubstInitializer(OldVar->getInit(), TemplateArgs,
3677 OldVar->getInitStyle() == VarDecl::CallInit);
3678 if (!Init.isInvalid()) {
3679 bool TypeMayContainAuto = true;
3680 Expr *InitExpr = Init.get();
3681
3682 if (Var->hasAttr<DLLImportAttr>() && InitExpr &&
3683 !InitExpr->isConstantInitializer(getASTContext(), false)) {
3684 // Do not dynamically initialize dllimport variables.
3685 } else if (InitExpr) {
3686 bool DirectInit = OldVar->isDirectInit();
3687 AddInitializerToDecl(Var, InitExpr, DirectInit, TypeMayContainAuto);
3688 } else
3689 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3690 } else {
3691 // FIXME: Not too happy about invalidating the declaration
3692 // because of a bogus initializer.
3693 Var->setInvalidDecl();
3694 }
3695
3696 PopExpressionEvaluationContext();
3697 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3698 !Var->isCXXForRangeDecl())
3699 ActOnUninitializedDecl(Var, false);
3700 }
3701
3702 /// \brief Instantiate the definition of the given variable from its
3703 /// template.
3704 ///
3705 /// \param PointOfInstantiation the point at which the instantiation was
3706 /// required. Note that this is not precisely a "point of instantiation"
3707 /// for the function, but it's close.
3708 ///
3709 /// \param Var the already-instantiated declaration of a static member
3710 /// variable of a class template specialization.
3711 ///
3712 /// \param Recursive if true, recursively instantiates any functions that
3713 /// are required by this instantiation.
3714 ///
3715 /// \param DefinitionRequired if true, then we are performing an explicit
3716 /// instantiation where an out-of-line definition of the member variable
3717 /// is required. Complain if there is no such definition.
InstantiateStaticDataMemberDefinition(SourceLocation PointOfInstantiation,VarDecl * Var,bool Recursive,bool DefinitionRequired)3718 void Sema::InstantiateStaticDataMemberDefinition(
3719 SourceLocation PointOfInstantiation,
3720 VarDecl *Var,
3721 bool Recursive,
3722 bool DefinitionRequired) {
3723 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3724 DefinitionRequired);
3725 }
3726
InstantiateVariableDefinition(SourceLocation PointOfInstantiation,VarDecl * Var,bool Recursive,bool DefinitionRequired)3727 void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3728 VarDecl *Var, bool Recursive,
3729 bool DefinitionRequired) {
3730 if (Var->isInvalidDecl())
3731 return;
3732
3733 VarTemplateSpecializationDecl *VarSpec =
3734 dyn_cast<VarTemplateSpecializationDecl>(Var);
3735 VarDecl *PatternDecl = nullptr, *Def = nullptr;
3736 MultiLevelTemplateArgumentList TemplateArgs =
3737 getTemplateInstantiationArgs(Var);
3738
3739 if (VarSpec) {
3740 // If this is a variable template specialization, make sure that it is
3741 // non-dependent, then find its instantiation pattern.
3742 bool InstantiationDependent = false;
3743 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3744 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3745 "Only instantiate variable template specializations that are "
3746 "not type-dependent");
3747 (void)InstantiationDependent;
3748
3749 // Find the variable initialization that we'll be substituting. If the
3750 // pattern was instantiated from a member template, look back further to
3751 // find the real pattern.
3752 assert(VarSpec->getSpecializedTemplate() &&
3753 "Specialization without specialized template?");
3754 llvm::PointerUnion<VarTemplateDecl *,
3755 VarTemplatePartialSpecializationDecl *> PatternPtr =
3756 VarSpec->getSpecializedTemplateOrPartial();
3757 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
3758 VarTemplatePartialSpecializationDecl *Tmpl =
3759 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3760 while (VarTemplatePartialSpecializationDecl *From =
3761 Tmpl->getInstantiatedFromMember()) {
3762 if (Tmpl->isMemberSpecialization())
3763 break;
3764
3765 Tmpl = From;
3766 }
3767 PatternDecl = Tmpl;
3768 } else {
3769 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3770 while (VarTemplateDecl *From =
3771 Tmpl->getInstantiatedFromMemberTemplate()) {
3772 if (Tmpl->isMemberSpecialization())
3773 break;
3774
3775 Tmpl = From;
3776 }
3777 PatternDecl = Tmpl->getTemplatedDecl();
3778 }
3779
3780 // If this is a static data member template, there might be an
3781 // uninstantiated initializer on the declaration. If so, instantiate
3782 // it now.
3783 if (PatternDecl->isStaticDataMember() &&
3784 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
3785 !Var->hasInit()) {
3786 // FIXME: Factor out the duplicated instantiation context setup/tear down
3787 // code here.
3788 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3789 if (Inst.isInvalid())
3790 return;
3791
3792 // If we're performing recursive template instantiation, create our own
3793 // queue of pending implicit instantiations that we will instantiate
3794 // later, while we're still within our own instantiation context.
3795 SmallVector<VTableUse, 16> SavedVTableUses;
3796 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3797 if (Recursive) {
3798 VTableUses.swap(SavedVTableUses);
3799 PendingInstantiations.swap(SavedPendingInstantiations);
3800 }
3801
3802 LocalInstantiationScope Local(*this);
3803
3804 // Enter the scope of this instantiation. We don't use
3805 // PushDeclContext because we don't have a scope.
3806 ContextRAII PreviousContext(*this, Var->getDeclContext());
3807 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3808 PreviousContext.pop();
3809
3810 // FIXME: Need to inform the ASTConsumer that we instantiated the
3811 // initializer?
3812
3813 // This variable may have local implicit instantiations that need to be
3814 // instantiated within this scope.
3815 PerformPendingInstantiations(/*LocalOnly=*/true);
3816
3817 Local.Exit();
3818
3819 if (Recursive) {
3820 // Define any newly required vtables.
3821 DefineUsedVTables();
3822
3823 // Instantiate any pending implicit instantiations found during the
3824 // instantiation of this template.
3825 PerformPendingInstantiations();
3826
3827 // Restore the set of pending vtables.
3828 assert(VTableUses.empty() &&
3829 "VTableUses should be empty before it is discarded.");
3830 VTableUses.swap(SavedVTableUses);
3831
3832 // Restore the set of pending implicit instantiations.
3833 assert(PendingInstantiations.empty() &&
3834 "PendingInstantiations should be empty before it is discarded.");
3835 PendingInstantiations.swap(SavedPendingInstantiations);
3836 }
3837 }
3838
3839 // Find actual definition
3840 Def = PatternDecl->getDefinition(getASTContext());
3841 } else {
3842 // If this is a static data member, find its out-of-line definition.
3843 assert(Var->isStaticDataMember() && "not a static data member?");
3844 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3845
3846 assert(PatternDecl && "data member was not instantiated from a template?");
3847 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3848 Def = PatternDecl->getOutOfLineDefinition();
3849 }
3850
3851 // If we don't have a definition of the variable template, we won't perform
3852 // any instantiation. Rather, we rely on the user to instantiate this
3853 // definition (or provide a specialization for it) in another translation
3854 // unit.
3855 if (!Def) {
3856 if (DefinitionRequired) {
3857 if (VarSpec)
3858 Diag(PointOfInstantiation,
3859 diag::err_explicit_instantiation_undefined_var_template) << Var;
3860 else
3861 Diag(PointOfInstantiation,
3862 diag::err_explicit_instantiation_undefined_member)
3863 << 2 << Var->getDeclName() << Var->getDeclContext();
3864 Diag(PatternDecl->getLocation(),
3865 diag::note_explicit_instantiation_here);
3866 if (VarSpec)
3867 Var->setInvalidDecl();
3868 } else if (Var->getTemplateSpecializationKind()
3869 == TSK_ExplicitInstantiationDefinition) {
3870 PendingInstantiations.push_back(
3871 std::make_pair(Var, PointOfInstantiation));
3872 }
3873
3874 return;
3875 }
3876
3877 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3878
3879 // Never instantiate an explicit specialization.
3880 if (TSK == TSK_ExplicitSpecialization)
3881 return;
3882
3883 // C++11 [temp.explicit]p10:
3884 // Except for inline functions, [...] explicit instantiation declarations
3885 // have the effect of suppressing the implicit instantiation of the entity
3886 // to which they refer.
3887 if (TSK == TSK_ExplicitInstantiationDeclaration)
3888 return;
3889
3890 // Make sure to pass the instantiated variable to the consumer at the end.
3891 struct PassToConsumerRAII {
3892 ASTConsumer &Consumer;
3893 VarDecl *Var;
3894
3895 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3896 : Consumer(Consumer), Var(Var) { }
3897
3898 ~PassToConsumerRAII() {
3899 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3900 }
3901 } PassToConsumerRAII(Consumer, Var);
3902
3903 // If we already have a definition, we're done.
3904 if (VarDecl *Def = Var->getDefinition()) {
3905 // We may be explicitly instantiating something we've already implicitly
3906 // instantiated.
3907 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3908 PointOfInstantiation);
3909 return;
3910 }
3911
3912 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3913 if (Inst.isInvalid())
3914 return;
3915
3916 // If we're performing recursive template instantiation, create our own
3917 // queue of pending implicit instantiations that we will instantiate later,
3918 // while we're still within our own instantiation context.
3919 SmallVector<VTableUse, 16> SavedVTableUses;
3920 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3921 SavePendingLocalImplicitInstantiationsRAII
3922 SavedPendingLocalImplicitInstantiations(*this);
3923 if (Recursive) {
3924 VTableUses.swap(SavedVTableUses);
3925 PendingInstantiations.swap(SavedPendingInstantiations);
3926 }
3927
3928 // Enter the scope of this instantiation. We don't use
3929 // PushDeclContext because we don't have a scope.
3930 ContextRAII PreviousContext(*this, Var->getDeclContext());
3931 LocalInstantiationScope Local(*this);
3932
3933 VarDecl *OldVar = Var;
3934 if (!VarSpec)
3935 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3936 TemplateArgs));
3937 else if (Var->isStaticDataMember() &&
3938 Var->getLexicalDeclContext()->isRecord()) {
3939 // We need to instantiate the definition of a static data member template,
3940 // and all we have is the in-class declaration of it. Instantiate a separate
3941 // declaration of the definition.
3942 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3943 TemplateArgs);
3944 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3945 VarSpec->getSpecializedTemplate(), Def, nullptr,
3946 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3947 if (Var) {
3948 llvm::PointerUnion<VarTemplateDecl *,
3949 VarTemplatePartialSpecializationDecl *> PatternPtr =
3950 VarSpec->getSpecializedTemplateOrPartial();
3951 if (VarTemplatePartialSpecializationDecl *Partial =
3952 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3953 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3954 Partial, &VarSpec->getTemplateInstantiationArgs());
3955
3956 // Merge the definition with the declaration.
3957 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3958 LookupOrdinaryName, ForRedeclaration);
3959 R.addDecl(OldVar);
3960 MergeVarDecl(Var, R);
3961
3962 // Attach the initializer.
3963 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3964 }
3965 } else
3966 // Complete the existing variable's definition with an appropriately
3967 // substituted type and initializer.
3968 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
3969
3970 PreviousContext.pop();
3971
3972 if (Var) {
3973 PassToConsumerRAII.Var = Var;
3974 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3975 OldVar->getPointOfInstantiation());
3976 }
3977
3978 // This variable may have local implicit instantiations that need to be
3979 // instantiated within this scope.
3980 PerformPendingInstantiations(/*LocalOnly=*/true);
3981
3982 Local.Exit();
3983
3984 if (Recursive) {
3985 // Define any newly required vtables.
3986 DefineUsedVTables();
3987
3988 // Instantiate any pending implicit instantiations found during the
3989 // instantiation of this template.
3990 PerformPendingInstantiations();
3991
3992 // Restore the set of pending vtables.
3993 assert(VTableUses.empty() &&
3994 "VTableUses should be empty before it is discarded.");
3995 VTableUses.swap(SavedVTableUses);
3996
3997 // Restore the set of pending implicit instantiations.
3998 assert(PendingInstantiations.empty() &&
3999 "PendingInstantiations should be empty before it is discarded.");
4000 PendingInstantiations.swap(SavedPendingInstantiations);
4001 }
4002 }
4003
4004 void
InstantiateMemInitializers(CXXConstructorDecl * New,const CXXConstructorDecl * Tmpl,const MultiLevelTemplateArgumentList & TemplateArgs)4005 Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4006 const CXXConstructorDecl *Tmpl,
4007 const MultiLevelTemplateArgumentList &TemplateArgs) {
4008
4009 SmallVector<CXXCtorInitializer*, 4> NewInits;
4010 bool AnyErrors = Tmpl->isInvalidDecl();
4011
4012 // Instantiate all the initializers.
4013 for (const auto *Init : Tmpl->inits()) {
4014 // Only instantiate written initializers, let Sema re-construct implicit
4015 // ones.
4016 if (!Init->isWritten())
4017 continue;
4018
4019 SourceLocation EllipsisLoc;
4020
4021 if (Init->isPackExpansion()) {
4022 // This is a pack expansion. We should expand it now.
4023 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4024 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4025 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4026 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4027 bool ShouldExpand = false;
4028 bool RetainExpansion = false;
4029 Optional<unsigned> NumExpansions;
4030 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4031 BaseTL.getSourceRange(),
4032 Unexpanded,
4033 TemplateArgs, ShouldExpand,
4034 RetainExpansion,
4035 NumExpansions)) {
4036 AnyErrors = true;
4037 New->setInvalidDecl();
4038 continue;
4039 }
4040 assert(ShouldExpand && "Partial instantiation of base initializer?");
4041
4042 // Loop over all of the arguments in the argument pack(s),
4043 for (unsigned I = 0; I != *NumExpansions; ++I) {
4044 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4045
4046 // Instantiate the initializer.
4047 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4048 /*CXXDirectInit=*/true);
4049 if (TempInit.isInvalid()) {
4050 AnyErrors = true;
4051 break;
4052 }
4053
4054 // Instantiate the base type.
4055 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4056 TemplateArgs,
4057 Init->getSourceLocation(),
4058 New->getDeclName());
4059 if (!BaseTInfo) {
4060 AnyErrors = true;
4061 break;
4062 }
4063
4064 // Build the initializer.
4065 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4066 BaseTInfo, TempInit.get(),
4067 New->getParent(),
4068 SourceLocation());
4069 if (NewInit.isInvalid()) {
4070 AnyErrors = true;
4071 break;
4072 }
4073
4074 NewInits.push_back(NewInit.get());
4075 }
4076
4077 continue;
4078 }
4079
4080 // Instantiate the initializer.
4081 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4082 /*CXXDirectInit=*/true);
4083 if (TempInit.isInvalid()) {
4084 AnyErrors = true;
4085 continue;
4086 }
4087
4088 MemInitResult NewInit;
4089 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4090 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4091 TemplateArgs,
4092 Init->getSourceLocation(),
4093 New->getDeclName());
4094 if (!TInfo) {
4095 AnyErrors = true;
4096 New->setInvalidDecl();
4097 continue;
4098 }
4099
4100 if (Init->isBaseInitializer())
4101 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4102 New->getParent(), EllipsisLoc);
4103 else
4104 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4105 cast<CXXRecordDecl>(CurContext->getParent()));
4106 } else if (Init->isMemberInitializer()) {
4107 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4108 Init->getMemberLocation(),
4109 Init->getMember(),
4110 TemplateArgs));
4111 if (!Member) {
4112 AnyErrors = true;
4113 New->setInvalidDecl();
4114 continue;
4115 }
4116
4117 NewInit = BuildMemberInitializer(Member, TempInit.get(),
4118 Init->getSourceLocation());
4119 } else if (Init->isIndirectMemberInitializer()) {
4120 IndirectFieldDecl *IndirectMember =
4121 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4122 Init->getMemberLocation(),
4123 Init->getIndirectMember(), TemplateArgs));
4124
4125 if (!IndirectMember) {
4126 AnyErrors = true;
4127 New->setInvalidDecl();
4128 continue;
4129 }
4130
4131 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4132 Init->getSourceLocation());
4133 }
4134
4135 if (NewInit.isInvalid()) {
4136 AnyErrors = true;
4137 New->setInvalidDecl();
4138 } else {
4139 NewInits.push_back(NewInit.get());
4140 }
4141 }
4142
4143 // Assign all the initializers to the new constructor.
4144 ActOnMemInitializers(New,
4145 /*FIXME: ColonLoc */
4146 SourceLocation(),
4147 NewInits,
4148 AnyErrors);
4149 }
4150
4151 // TODO: this could be templated if the various decl types used the
4152 // same method name.
isInstantiationOf(ClassTemplateDecl * Pattern,ClassTemplateDecl * Instance)4153 static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4154 ClassTemplateDecl *Instance) {
4155 Pattern = Pattern->getCanonicalDecl();
4156
4157 do {
4158 Instance = Instance->getCanonicalDecl();
4159 if (Pattern == Instance) return true;
4160 Instance = Instance->getInstantiatedFromMemberTemplate();
4161 } while (Instance);
4162
4163 return false;
4164 }
4165
isInstantiationOf(FunctionTemplateDecl * Pattern,FunctionTemplateDecl * Instance)4166 static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4167 FunctionTemplateDecl *Instance) {
4168 Pattern = Pattern->getCanonicalDecl();
4169
4170 do {
4171 Instance = Instance->getCanonicalDecl();
4172 if (Pattern == Instance) return true;
4173 Instance = Instance->getInstantiatedFromMemberTemplate();
4174 } while (Instance);
4175
4176 return false;
4177 }
4178
4179 static bool
isInstantiationOf(ClassTemplatePartialSpecializationDecl * Pattern,ClassTemplatePartialSpecializationDecl * Instance)4180 isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4181 ClassTemplatePartialSpecializationDecl *Instance) {
4182 Pattern
4183 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4184 do {
4185 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4186 Instance->getCanonicalDecl());
4187 if (Pattern == Instance)
4188 return true;
4189 Instance = Instance->getInstantiatedFromMember();
4190 } while (Instance);
4191
4192 return false;
4193 }
4194
isInstantiationOf(CXXRecordDecl * Pattern,CXXRecordDecl * Instance)4195 static bool isInstantiationOf(CXXRecordDecl *Pattern,
4196 CXXRecordDecl *Instance) {
4197 Pattern = Pattern->getCanonicalDecl();
4198
4199 do {
4200 Instance = Instance->getCanonicalDecl();
4201 if (Pattern == Instance) return true;
4202 Instance = Instance->getInstantiatedFromMemberClass();
4203 } while (Instance);
4204
4205 return false;
4206 }
4207
isInstantiationOf(FunctionDecl * Pattern,FunctionDecl * Instance)4208 static bool isInstantiationOf(FunctionDecl *Pattern,
4209 FunctionDecl *Instance) {
4210 Pattern = Pattern->getCanonicalDecl();
4211
4212 do {
4213 Instance = Instance->getCanonicalDecl();
4214 if (Pattern == Instance) return true;
4215 Instance = Instance->getInstantiatedFromMemberFunction();
4216 } while (Instance);
4217
4218 return false;
4219 }
4220
isInstantiationOf(EnumDecl * Pattern,EnumDecl * Instance)4221 static bool isInstantiationOf(EnumDecl *Pattern,
4222 EnumDecl *Instance) {
4223 Pattern = Pattern->getCanonicalDecl();
4224
4225 do {
4226 Instance = Instance->getCanonicalDecl();
4227 if (Pattern == Instance) return true;
4228 Instance = Instance->getInstantiatedFromMemberEnum();
4229 } while (Instance);
4230
4231 return false;
4232 }
4233
isInstantiationOf(UsingShadowDecl * Pattern,UsingShadowDecl * Instance,ASTContext & C)4234 static bool isInstantiationOf(UsingShadowDecl *Pattern,
4235 UsingShadowDecl *Instance,
4236 ASTContext &C) {
4237 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4238 }
4239
isInstantiationOf(UsingDecl * Pattern,UsingDecl * Instance,ASTContext & C)4240 static bool isInstantiationOf(UsingDecl *Pattern,
4241 UsingDecl *Instance,
4242 ASTContext &C) {
4243 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4244 }
4245
isInstantiationOf(UnresolvedUsingValueDecl * Pattern,UsingDecl * Instance,ASTContext & C)4246 static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4247 UsingDecl *Instance,
4248 ASTContext &C) {
4249 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4250 }
4251
isInstantiationOf(UnresolvedUsingTypenameDecl * Pattern,UsingDecl * Instance,ASTContext & C)4252 static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
4253 UsingDecl *Instance,
4254 ASTContext &C) {
4255 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4256 }
4257
isInstantiationOfStaticDataMember(VarDecl * Pattern,VarDecl * Instance)4258 static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4259 VarDecl *Instance) {
4260 assert(Instance->isStaticDataMember());
4261
4262 Pattern = Pattern->getCanonicalDecl();
4263
4264 do {
4265 Instance = Instance->getCanonicalDecl();
4266 if (Pattern == Instance) return true;
4267 Instance = Instance->getInstantiatedFromStaticDataMember();
4268 } while (Instance);
4269
4270 return false;
4271 }
4272
4273 // Other is the prospective instantiation
4274 // D is the prospective pattern
isInstantiationOf(ASTContext & Ctx,NamedDecl * D,Decl * Other)4275 static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4276 if (D->getKind() != Other->getKind()) {
4277 if (UnresolvedUsingTypenameDecl *UUD
4278 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4279 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4280 return isInstantiationOf(UUD, UD, Ctx);
4281 }
4282 }
4283
4284 if (UnresolvedUsingValueDecl *UUD
4285 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
4286 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4287 return isInstantiationOf(UUD, UD, Ctx);
4288 }
4289 }
4290
4291 return false;
4292 }
4293
4294 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4295 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4296
4297 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4298 return isInstantiationOf(cast<FunctionDecl>(D), Function);
4299
4300 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4301 return isInstantiationOf(cast<EnumDecl>(D), Enum);
4302
4303 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
4304 if (Var->isStaticDataMember())
4305 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4306
4307 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4308 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4309
4310 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4311 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4312
4313 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4314 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4315 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4316 PartialSpec);
4317
4318 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4319 if (!Field->getDeclName()) {
4320 // This is an unnamed field.
4321 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
4322 cast<FieldDecl>(D);
4323 }
4324 }
4325
4326 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4327 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4328
4329 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4330 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4331
4332 return D->getDeclName() && isa<NamedDecl>(Other) &&
4333 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4334 }
4335
4336 template<typename ForwardIterator>
findInstantiationOf(ASTContext & Ctx,NamedDecl * D,ForwardIterator first,ForwardIterator last)4337 static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4338 NamedDecl *D,
4339 ForwardIterator first,
4340 ForwardIterator last) {
4341 for (; first != last; ++first)
4342 if (isInstantiationOf(Ctx, D, *first))
4343 return cast<NamedDecl>(*first);
4344
4345 return nullptr;
4346 }
4347
4348 /// \brief Finds the instantiation of the given declaration context
4349 /// within the current instantiation.
4350 ///
4351 /// \returns NULL if there was an error
FindInstantiatedContext(SourceLocation Loc,DeclContext * DC,const MultiLevelTemplateArgumentList & TemplateArgs)4352 DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4353 const MultiLevelTemplateArgumentList &TemplateArgs) {
4354 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4355 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
4356 return cast_or_null<DeclContext>(ID);
4357 } else return DC;
4358 }
4359
4360 /// \brief Find the instantiation of the given declaration within the
4361 /// current instantiation.
4362 ///
4363 /// This routine is intended to be used when \p D is a declaration
4364 /// referenced from within a template, that needs to mapped into the
4365 /// corresponding declaration within an instantiation. For example,
4366 /// given:
4367 ///
4368 /// \code
4369 /// template<typename T>
4370 /// struct X {
4371 /// enum Kind {
4372 /// KnownValue = sizeof(T)
4373 /// };
4374 ///
4375 /// bool getKind() const { return KnownValue; }
4376 /// };
4377 ///
4378 /// template struct X<int>;
4379 /// \endcode
4380 ///
4381 /// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4382 /// \p EnumConstantDecl for \p KnownValue (which refers to
4383 /// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4384 /// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4385 /// this mapping from within the instantiation of <tt>X<int></tt>.
FindInstantiatedDecl(SourceLocation Loc,NamedDecl * D,const MultiLevelTemplateArgumentList & TemplateArgs)4386 NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4387 const MultiLevelTemplateArgumentList &TemplateArgs) {
4388 DeclContext *ParentDC = D->getDeclContext();
4389 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4390 // parameters (p below) can have their ParentDC set to the translation-unit
4391 // - thus we can not consistently check if the ParentDC of such a parameter
4392 // is Dependent or/and a FunctionOrMethod.
4393 // For e.g. this code, during Template argument deduction tries to
4394 // find an instantiated decl for (T y) when the ParentDC for y is
4395 // the translation unit.
4396 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4397 // float baz(float(*)()) { return 0.0; }
4398 // Foo(baz);
4399 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4400 // it gets here, always has a FunctionOrMethod as its ParentDC??
4401 // For now:
4402 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4403 // whose type is not instantiation dependent, do nothing to the decl
4404 // - otherwise find its instantiated decl.
4405 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4406 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4407 return D;
4408 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4409 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4410 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4411 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4412 // D is a local of some kind. Look into the map of local
4413 // declarations to their instantiations.
4414 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4415 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4416 = CurrentInstantiationScope->findInstantiationOf(D);
4417
4418 if (Found) {
4419 if (Decl *FD = Found->dyn_cast<Decl *>())
4420 return cast<NamedDecl>(FD);
4421
4422 int PackIdx = ArgumentPackSubstitutionIndex;
4423 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
4424 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4425 }
4426
4427 // If we're performing a partial substitution during template argument
4428 // deduction, we may not have values for template parameters yet. They
4429 // just map to themselves.
4430 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4431 isa<TemplateTemplateParmDecl>(D))
4432 return D;
4433
4434 if (D->isInvalidDecl())
4435 return nullptr;
4436
4437 // If we didn't find the decl, then we must have a label decl that hasn't
4438 // been found yet. Lazily instantiate it and return it now.
4439 assert(isa<LabelDecl>(D));
4440
4441 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4442 assert(Inst && "Failed to instantiate label??");
4443
4444 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4445 return cast<LabelDecl>(Inst);
4446 }
4447
4448 // For variable template specializations, update those that are still
4449 // type-dependent.
4450 if (VarTemplateSpecializationDecl *VarSpec =
4451 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4452 bool InstantiationDependent = false;
4453 const TemplateArgumentListInfo &VarTemplateArgs =
4454 VarSpec->getTemplateArgsInfo();
4455 if (TemplateSpecializationType::anyDependentTemplateArguments(
4456 VarTemplateArgs, InstantiationDependent))
4457 D = cast<NamedDecl>(
4458 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4459 return D;
4460 }
4461
4462 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4463 if (!Record->isDependentContext())
4464 return D;
4465
4466 // Determine whether this record is the "templated" declaration describing
4467 // a class template or class template partial specialization.
4468 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4469 if (ClassTemplate)
4470 ClassTemplate = ClassTemplate->getCanonicalDecl();
4471 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4472 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4473 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4474
4475 // Walk the current context to find either the record or an instantiation of
4476 // it.
4477 DeclContext *DC = CurContext;
4478 while (!DC->isFileContext()) {
4479 // If we're performing substitution while we're inside the template
4480 // definition, we'll find our own context. We're done.
4481 if (DC->Equals(Record))
4482 return Record;
4483
4484 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4485 // Check whether we're in the process of instantiating a class template
4486 // specialization of the template we're mapping.
4487 if (ClassTemplateSpecializationDecl *InstSpec
4488 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4489 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4490 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4491 return InstRecord;
4492 }
4493
4494 // Check whether we're in the process of instantiating a member class.
4495 if (isInstantiationOf(Record, InstRecord))
4496 return InstRecord;
4497 }
4498
4499 // Move to the outer template scope.
4500 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4501 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4502 DC = FD->getLexicalDeclContext();
4503 continue;
4504 }
4505 }
4506
4507 DC = DC->getParent();
4508 }
4509
4510 // Fall through to deal with other dependent record types (e.g.,
4511 // anonymous unions in class templates).
4512 }
4513
4514 if (!ParentDC->isDependentContext())
4515 return D;
4516
4517 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
4518 if (!ParentDC)
4519 return nullptr;
4520
4521 if (ParentDC != D->getDeclContext()) {
4522 // We performed some kind of instantiation in the parent context,
4523 // so now we need to look into the instantiated parent context to
4524 // find the instantiation of the declaration D.
4525
4526 // If our context used to be dependent, we may need to instantiate
4527 // it before performing lookup into that context.
4528 bool IsBeingInstantiated = false;
4529 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
4530 if (!Spec->isDependentContext()) {
4531 QualType T = Context.getTypeDeclType(Spec);
4532 const RecordType *Tag = T->getAs<RecordType>();
4533 assert(Tag && "type of non-dependent record is not a RecordType");
4534 if (Tag->isBeingDefined())
4535 IsBeingInstantiated = true;
4536 if (!Tag->isBeingDefined() &&
4537 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4538 return nullptr;
4539
4540 ParentDC = Tag->getDecl();
4541 }
4542 }
4543
4544 NamedDecl *Result = nullptr;
4545 if (D->getDeclName()) {
4546 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
4547 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
4548 } else {
4549 // Since we don't have a name for the entity we're looking for,
4550 // our only option is to walk through all of the declarations to
4551 // find that name. This will occur in a few cases:
4552 //
4553 // - anonymous struct/union within a template
4554 // - unnamed class/struct/union/enum within a template
4555 //
4556 // FIXME: Find a better way to find these instantiations!
4557 Result = findInstantiationOf(Context, D,
4558 ParentDC->decls_begin(),
4559 ParentDC->decls_end());
4560 }
4561
4562 if (!Result) {
4563 if (isa<UsingShadowDecl>(D)) {
4564 // UsingShadowDecls can instantiate to nothing because of using hiding.
4565 } else if (Diags.hasErrorOccurred()) {
4566 // We've already complained about something, so most likely this
4567 // declaration failed to instantiate. There's no point in complaining
4568 // further, since this is normal in invalid code.
4569 } else if (IsBeingInstantiated) {
4570 // The class in which this member exists is currently being
4571 // instantiated, and we haven't gotten around to instantiating this
4572 // member yet. This can happen when the code uses forward declarations
4573 // of member classes, and introduces ordering dependencies via
4574 // template instantiation.
4575 Diag(Loc, diag::err_member_not_yet_instantiated)
4576 << D->getDeclName()
4577 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4578 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
4579 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4580 // This enumeration constant was found when the template was defined,
4581 // but can't be found in the instantiation. This can happen if an
4582 // unscoped enumeration member is explicitly specialized.
4583 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4584 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4585 TemplateArgs));
4586 assert(Spec->getTemplateSpecializationKind() ==
4587 TSK_ExplicitSpecialization);
4588 Diag(Loc, diag::err_enumerator_does_not_exist)
4589 << D->getDeclName()
4590 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4591 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4592 << Context.getTypeDeclType(Spec);
4593 } else {
4594 // We should have found something, but didn't.
4595 llvm_unreachable("Unable to find instantiation of declaration!");
4596 }
4597 }
4598
4599 D = Result;
4600 }
4601
4602 return D;
4603 }
4604
4605 /// \brief Performs template instantiation for all implicit template
4606 /// instantiations we have seen until this point.
PerformPendingInstantiations(bool LocalOnly)4607 void Sema::PerformPendingInstantiations(bool LocalOnly) {
4608 while (!PendingLocalImplicitInstantiations.empty() ||
4609 (!LocalOnly && !PendingInstantiations.empty())) {
4610 PendingImplicitInstantiation Inst;
4611
4612 if (PendingLocalImplicitInstantiations.empty()) {
4613 Inst = PendingInstantiations.front();
4614 PendingInstantiations.pop_front();
4615 } else {
4616 Inst = PendingLocalImplicitInstantiations.front();
4617 PendingLocalImplicitInstantiations.pop_front();
4618 }
4619
4620 // Instantiate function definitions
4621 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
4622 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4623 "instantiating function definition");
4624 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4625 TSK_ExplicitInstantiationDefinition;
4626 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4627 DefinitionRequired);
4628 continue;
4629 }
4630
4631 // Instantiate variable definitions
4632 VarDecl *Var = cast<VarDecl>(Inst.first);
4633
4634 assert((Var->isStaticDataMember() ||
4635 isa<VarTemplateSpecializationDecl>(Var)) &&
4636 "Not a static data member, nor a variable template"
4637 " specialization?");
4638
4639 // Don't try to instantiate declarations if the most recent redeclaration
4640 // is invalid.
4641 if (Var->getMostRecentDecl()->isInvalidDecl())
4642 continue;
4643
4644 // Check if the most recent declaration has changed the specialization kind
4645 // and removed the need for implicit instantiation.
4646 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
4647 case TSK_Undeclared:
4648 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
4649 case TSK_ExplicitInstantiationDeclaration:
4650 case TSK_ExplicitSpecialization:
4651 continue; // No longer need to instantiate this type.
4652 case TSK_ExplicitInstantiationDefinition:
4653 // We only need an instantiation if the pending instantiation *is* the
4654 // explicit instantiation.
4655 if (Var != Var->getMostRecentDecl()) continue;
4656 case TSK_ImplicitInstantiation:
4657 break;
4658 }
4659
4660 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4661 "instantiating variable definition");
4662 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4663 TSK_ExplicitInstantiationDefinition;
4664
4665 // Instantiate static data member definitions or variable template
4666 // specializations.
4667 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4668 DefinitionRequired);
4669 }
4670 }
4671
PerformDependentDiagnostics(const DeclContext * Pattern,const MultiLevelTemplateArgumentList & TemplateArgs)4672 void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4673 const MultiLevelTemplateArgumentList &TemplateArgs) {
4674 for (auto DD : Pattern->ddiags()) {
4675 switch (DD->getKind()) {
4676 case DependentDiagnostic::Access:
4677 HandleDependentAccessCheck(*DD, TemplateArgs);
4678 break;
4679 }
4680 }
4681 }
4682