1 | //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/ |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | //===----------------------------------------------------------------------===/ |
7 | // |
8 | // This file implements C++ template instantiation for declarations. |
9 | // |
10 | //===----------------------------------------------------------------------===/ |
11 | |
12 | #include "TreeTransform.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/PrettyDeclStackTrace.h" |
22 | #include "clang/AST/TypeLoc.h" |
23 | #include "clang/Basic/SourceManager.h" |
24 | #include "clang/Basic/TargetInfo.h" |
25 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
26 | #include "clang/Sema/Initialization.h" |
27 | #include "clang/Sema/Lookup.h" |
28 | #include "clang/Sema/ScopeInfo.h" |
29 | #include "clang/Sema/SemaAMDGPU.h" |
30 | #include "clang/Sema/SemaCUDA.h" |
31 | #include "clang/Sema/SemaInternal.h" |
32 | #include "clang/Sema/SemaObjC.h" |
33 | #include "clang/Sema/SemaOpenMP.h" |
34 | #include "clang/Sema/SemaSwift.h" |
35 | #include "clang/Sema/Template.h" |
36 | #include "clang/Sema/TemplateInstCallback.h" |
37 | #include "llvm/Support/TimeProfiler.h" |
38 | #include <optional> |
39 | |
40 | using namespace clang; |
41 | |
42 | static bool isDeclWithinFunction(const Decl *D) { |
43 | const DeclContext *DC = D->getDeclContext(); |
44 | if (DC->isFunctionOrMethod()) |
45 | return true; |
46 | |
47 | if (DC->isRecord()) |
48 | return cast<CXXRecordDecl>(Val: DC)->isLocalClass(); |
49 | |
50 | return false; |
51 | } |
52 | |
53 | template<typename DeclT> |
54 | static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl, |
55 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
56 | if (!OldDecl->getQualifierLoc()) |
57 | return false; |
58 | |
59 | assert((NewDecl->getFriendObjectKind() || |
60 | !OldDecl->getLexicalDeclContext()->isDependentContext()) && |
61 | "non-friend with qualified name defined in dependent context" ); |
62 | Sema::ContextRAII SavedContext( |
63 | SemaRef, |
64 | const_cast<DeclContext *>(NewDecl->getFriendObjectKind() |
65 | ? NewDecl->getLexicalDeclContext() |
66 | : OldDecl->getLexicalDeclContext())); |
67 | |
68 | NestedNameSpecifierLoc NewQualifierLoc |
69 | = SemaRef.SubstNestedNameSpecifierLoc(NNS: OldDecl->getQualifierLoc(), |
70 | TemplateArgs); |
71 | |
72 | if (!NewQualifierLoc) |
73 | return true; |
74 | |
75 | NewDecl->setQualifierInfo(NewQualifierLoc); |
76 | return false; |
77 | } |
78 | |
79 | bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, |
80 | DeclaratorDecl *NewDecl) { |
81 | return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs); |
82 | } |
83 | |
84 | bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, |
85 | TagDecl *NewDecl) { |
86 | return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs); |
87 | } |
88 | |
89 | // Include attribute instantiation code. |
90 | #include "clang/Sema/AttrTemplateInstantiate.inc" |
91 | |
92 | static void instantiateDependentAlignedAttr( |
93 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
94 | const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) { |
95 | if (Aligned->isAlignmentExpr()) { |
96 | // The alignment expression is a constant expression. |
97 | EnterExpressionEvaluationContext Unevaluated( |
98 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
99 | ExprResult Result = S.SubstExpr(E: Aligned->getAlignmentExpr(), TemplateArgs); |
100 | if (!Result.isInvalid()) |
101 | S.AddAlignedAttr(D: New, CI: *Aligned, E: Result.getAs<Expr>(), IsPackExpansion); |
102 | } else { |
103 | if (TypeSourceInfo *Result = |
104 | S.SubstType(T: Aligned->getAlignmentType(), TemplateArgs, |
105 | Loc: Aligned->getLocation(), Entity: DeclarationName())) { |
106 | if (!S.CheckAlignasTypeArgument(KWName: Aligned->getSpelling(), TInfo: Result, |
107 | OpLoc: Aligned->getLocation(), |
108 | R: Result->getTypeLoc().getSourceRange())) |
109 | S.AddAlignedAttr(D: New, CI: *Aligned, T: Result, IsPackExpansion); |
110 | } |
111 | } |
112 | } |
113 | |
114 | static void instantiateDependentAlignedAttr( |
115 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
116 | const AlignedAttr *Aligned, Decl *New) { |
117 | if (!Aligned->isPackExpansion()) { |
118 | instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, IsPackExpansion: false); |
119 | return; |
120 | } |
121 | |
122 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
123 | if (Aligned->isAlignmentExpr()) |
124 | S.collectUnexpandedParameterPacks(E: Aligned->getAlignmentExpr(), |
125 | Unexpanded); |
126 | else |
127 | S.collectUnexpandedParameterPacks(TL: Aligned->getAlignmentType()->getTypeLoc(), |
128 | Unexpanded); |
129 | assert(!Unexpanded.empty() && "Pack expansion without parameter packs?" ); |
130 | |
131 | // Determine whether we can expand this attribute pack yet. |
132 | bool Expand = true, RetainExpansion = false; |
133 | std::optional<unsigned> NumExpansions; |
134 | // FIXME: Use the actual location of the ellipsis. |
135 | SourceLocation EllipsisLoc = Aligned->getLocation(); |
136 | if (S.CheckParameterPacksForExpansion(EllipsisLoc, PatternRange: Aligned->getRange(), |
137 | Unexpanded, TemplateArgs, ShouldExpand&: Expand, |
138 | RetainExpansion, NumExpansions)) |
139 | return; |
140 | |
141 | if (!Expand) { |
142 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1); |
143 | instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, IsPackExpansion: true); |
144 | } else { |
145 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
146 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I); |
147 | instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, IsPackExpansion: false); |
148 | } |
149 | } |
150 | } |
151 | |
152 | static void instantiateDependentAssumeAlignedAttr( |
153 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
154 | const AssumeAlignedAttr *Aligned, Decl *New) { |
155 | // The alignment expression is a constant expression. |
156 | EnterExpressionEvaluationContext Unevaluated( |
157 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
158 | |
159 | Expr *E, *OE = nullptr; |
160 | ExprResult Result = S.SubstExpr(E: Aligned->getAlignment(), TemplateArgs); |
161 | if (Result.isInvalid()) |
162 | return; |
163 | E = Result.getAs<Expr>(); |
164 | |
165 | if (Aligned->getOffset()) { |
166 | Result = S.SubstExpr(E: Aligned->getOffset(), TemplateArgs); |
167 | if (Result.isInvalid()) |
168 | return; |
169 | OE = Result.getAs<Expr>(); |
170 | } |
171 | |
172 | S.AddAssumeAlignedAttr(D: New, CI: *Aligned, E, OE); |
173 | } |
174 | |
175 | static void instantiateDependentAlignValueAttr( |
176 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
177 | const AlignValueAttr *Aligned, Decl *New) { |
178 | // The alignment expression is a constant expression. |
179 | EnterExpressionEvaluationContext Unevaluated( |
180 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
181 | ExprResult Result = S.SubstExpr(E: Aligned->getAlignment(), TemplateArgs); |
182 | if (!Result.isInvalid()) |
183 | S.AddAlignValueAttr(D: New, CI: *Aligned, E: Result.getAs<Expr>()); |
184 | } |
185 | |
186 | static void instantiateDependentAllocAlignAttr( |
187 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
188 | const AllocAlignAttr *Align, Decl *New) { |
189 | Expr *Param = IntegerLiteral::Create( |
190 | C: S.getASTContext(), |
191 | V: llvm::APInt(64, Align->getParamIndex().getSourceIndex()), |
192 | type: S.getASTContext().UnsignedLongLongTy, l: Align->getLocation()); |
193 | S.AddAllocAlignAttr(D: New, CI: *Align, ParamExpr: Param); |
194 | } |
195 | |
196 | static void instantiateDependentAnnotationAttr( |
197 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
198 | const AnnotateAttr *Attr, Decl *New) { |
199 | EnterExpressionEvaluationContext Unevaluated( |
200 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
201 | |
202 | // If the attribute has delayed arguments it will have to instantiate those |
203 | // and handle them as new arguments for the attribute. |
204 | bool HasDelayedArgs = Attr->delayedArgs_size(); |
205 | |
206 | ArrayRef<Expr *> ArgsToInstantiate = |
207 | HasDelayedArgs |
208 | ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()} |
209 | : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()}; |
210 | |
211 | SmallVector<Expr *, 4> Args; |
212 | if (S.SubstExprs(Exprs: ArgsToInstantiate, |
213 | /*IsCall=*/false, TemplateArgs, Outputs&: Args)) |
214 | return; |
215 | |
216 | StringRef Str = Attr->getAnnotation(); |
217 | if (HasDelayedArgs) { |
218 | if (Args.size() < 1) { |
219 | S.Diag(Loc: Attr->getLoc(), DiagID: diag::err_attribute_too_few_arguments) |
220 | << Attr << 1; |
221 | return; |
222 | } |
223 | |
224 | if (!S.checkStringLiteralArgumentAttr(CI: *Attr, E: Args[0], Str)) |
225 | return; |
226 | |
227 | llvm::SmallVector<Expr *, 4> ActualArgs; |
228 | ActualArgs.insert(I: ActualArgs.begin(), From: Args.begin() + 1, To: Args.end()); |
229 | std::swap(LHS&: Args, RHS&: ActualArgs); |
230 | } |
231 | S.AddAnnotationAttr(D: New, CI: *Attr, Annot: Str, Args); |
232 | } |
233 | |
234 | static Expr *instantiateDependentFunctionAttrCondition( |
235 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
236 | const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) { |
237 | Expr *Cond = nullptr; |
238 | { |
239 | Sema::ContextRAII SwitchContext(S, New); |
240 | EnterExpressionEvaluationContext Unevaluated( |
241 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
242 | ExprResult Result = S.SubstExpr(E: OldCond, TemplateArgs); |
243 | if (Result.isInvalid()) |
244 | return nullptr; |
245 | Cond = Result.getAs<Expr>(); |
246 | } |
247 | if (!Cond->isTypeDependent()) { |
248 | ExprResult Converted = S.PerformContextuallyConvertToBool(From: Cond); |
249 | if (Converted.isInvalid()) |
250 | return nullptr; |
251 | Cond = Converted.get(); |
252 | } |
253 | |
254 | SmallVector<PartialDiagnosticAt, 8> Diags; |
255 | if (OldCond->isValueDependent() && !Cond->isValueDependent() && |
256 | !Expr::isPotentialConstantExprUnevaluated(E: Cond, FD: New, Diags)) { |
257 | S.Diag(Loc: A->getLocation(), DiagID: diag::err_attr_cond_never_constant_expr) << A; |
258 | for (const auto &P : Diags) |
259 | S.Diag(Loc: P.first, PD: P.second); |
260 | return nullptr; |
261 | } |
262 | return Cond; |
263 | } |
264 | |
265 | static void instantiateDependentEnableIfAttr( |
266 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
267 | const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) { |
268 | Expr *Cond = instantiateDependentFunctionAttrCondition( |
269 | S, TemplateArgs, A: EIA, OldCond: EIA->getCond(), Tmpl, New); |
270 | |
271 | if (Cond) |
272 | New->addAttr(A: new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA, |
273 | Cond, EIA->getMessage())); |
274 | } |
275 | |
276 | static void instantiateDependentDiagnoseIfAttr( |
277 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
278 | const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) { |
279 | Expr *Cond = instantiateDependentFunctionAttrCondition( |
280 | S, TemplateArgs, A: DIA, OldCond: DIA->getCond(), Tmpl, New); |
281 | |
282 | if (Cond) |
283 | New->addAttr(A: new (S.getASTContext()) DiagnoseIfAttr( |
284 | S.getASTContext(), *DIA, Cond, DIA->getMessage(), |
285 | DIA->getDiagnosticType(), DIA->getArgDependent(), New)); |
286 | } |
287 | |
288 | // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using |
289 | // template A as the base and arguments from TemplateArgs. |
290 | static void instantiateDependentCUDALaunchBoundsAttr( |
291 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
292 | const CUDALaunchBoundsAttr &Attr, Decl *New) { |
293 | // The alignment expression is a constant expression. |
294 | EnterExpressionEvaluationContext Unevaluated( |
295 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
296 | |
297 | ExprResult Result = S.SubstExpr(E: Attr.getMaxThreads(), TemplateArgs); |
298 | if (Result.isInvalid()) |
299 | return; |
300 | Expr *MaxThreads = Result.getAs<Expr>(); |
301 | |
302 | Expr *MinBlocks = nullptr; |
303 | if (Attr.getMinBlocks()) { |
304 | Result = S.SubstExpr(E: Attr.getMinBlocks(), TemplateArgs); |
305 | if (Result.isInvalid()) |
306 | return; |
307 | MinBlocks = Result.getAs<Expr>(); |
308 | } |
309 | |
310 | Expr *MaxBlocks = nullptr; |
311 | if (Attr.getMaxBlocks()) { |
312 | Result = S.SubstExpr(E: Attr.getMaxBlocks(), TemplateArgs); |
313 | if (Result.isInvalid()) |
314 | return; |
315 | MaxBlocks = Result.getAs<Expr>(); |
316 | } |
317 | |
318 | S.AddLaunchBoundsAttr(D: New, CI: Attr, MaxThreads, MinBlocks, MaxBlocks); |
319 | } |
320 | |
321 | static void |
322 | instantiateDependentModeAttr(Sema &S, |
323 | const MultiLevelTemplateArgumentList &TemplateArgs, |
324 | const ModeAttr &Attr, Decl *New) { |
325 | S.AddModeAttr(D: New, CI: Attr, Name: Attr.getMode(), |
326 | /*InInstantiation=*/true); |
327 | } |
328 | |
329 | /// Instantiation of 'declare simd' attribute and its arguments. |
330 | static void instantiateOMPDeclareSimdDeclAttr( |
331 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
332 | const OMPDeclareSimdDeclAttr &Attr, Decl *New) { |
333 | // Allow 'this' in clauses with varlists. |
334 | if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: New)) |
335 | New = FTD->getTemplatedDecl(); |
336 | auto *FD = cast<FunctionDecl>(Val: New); |
337 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: FD->getDeclContext()); |
338 | SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps; |
339 | SmallVector<unsigned, 4> LinModifiers; |
340 | |
341 | auto SubstExpr = [&](Expr *E) -> ExprResult { |
342 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts())) |
343 | if (auto *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl())) { |
344 | Sema::ContextRAII SavedContext(S, FD); |
345 | LocalInstantiationScope Local(S); |
346 | if (FD->getNumParams() > PVD->getFunctionScopeIndex()) |
347 | Local.InstantiatedLocal( |
348 | D: PVD, Inst: FD->getParamDecl(i: PVD->getFunctionScopeIndex())); |
349 | return S.SubstExpr(E, TemplateArgs); |
350 | } |
351 | Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(), |
352 | FD->isCXXInstanceMember()); |
353 | return S.SubstExpr(E, TemplateArgs); |
354 | }; |
355 | |
356 | // Substitute a single OpenMP clause, which is a potentially-evaluated |
357 | // full-expression. |
358 | auto Subst = [&](Expr *E) -> ExprResult { |
359 | EnterExpressionEvaluationContext Evaluated( |
360 | S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
361 | ExprResult Res = SubstExpr(E); |
362 | if (Res.isInvalid()) |
363 | return Res; |
364 | return S.ActOnFinishFullExpr(Expr: Res.get(), DiscardedValue: false); |
365 | }; |
366 | |
367 | ExprResult Simdlen; |
368 | if (auto *E = Attr.getSimdlen()) |
369 | Simdlen = Subst(E); |
370 | |
371 | if (Attr.uniforms_size() > 0) { |
372 | for(auto *E : Attr.uniforms()) { |
373 | ExprResult Inst = Subst(E); |
374 | if (Inst.isInvalid()) |
375 | continue; |
376 | Uniforms.push_back(Elt: Inst.get()); |
377 | } |
378 | } |
379 | |
380 | auto AI = Attr.alignments_begin(); |
381 | for (auto *E : Attr.aligneds()) { |
382 | ExprResult Inst = Subst(E); |
383 | if (Inst.isInvalid()) |
384 | continue; |
385 | Aligneds.push_back(Elt: Inst.get()); |
386 | Inst = ExprEmpty(); |
387 | if (*AI) |
388 | Inst = S.SubstExpr(E: *AI, TemplateArgs); |
389 | Alignments.push_back(Elt: Inst.get()); |
390 | ++AI; |
391 | } |
392 | |
393 | auto SI = Attr.steps_begin(); |
394 | for (auto *E : Attr.linears()) { |
395 | ExprResult Inst = Subst(E); |
396 | if (Inst.isInvalid()) |
397 | continue; |
398 | Linears.push_back(Elt: Inst.get()); |
399 | Inst = ExprEmpty(); |
400 | if (*SI) |
401 | Inst = S.SubstExpr(E: *SI, TemplateArgs); |
402 | Steps.push_back(Elt: Inst.get()); |
403 | ++SI; |
404 | } |
405 | LinModifiers.append(in_start: Attr.modifiers_begin(), in_end: Attr.modifiers_end()); |
406 | (void)S.OpenMP().ActOnOpenMPDeclareSimdDirective( |
407 | DG: S.ConvertDeclToDeclGroup(Ptr: New), BS: Attr.getBranchState(), Simdlen: Simdlen.get(), |
408 | Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps, |
409 | SR: Attr.getRange()); |
410 | } |
411 | |
412 | /// Instantiation of 'declare variant' attribute and its arguments. |
413 | static void instantiateOMPDeclareVariantAttr( |
414 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
415 | const OMPDeclareVariantAttr &Attr, Decl *New) { |
416 | // Allow 'this' in clauses with varlists. |
417 | if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: New)) |
418 | New = FTD->getTemplatedDecl(); |
419 | auto *FD = cast<FunctionDecl>(Val: New); |
420 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: FD->getDeclContext()); |
421 | |
422 | auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) { |
423 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts())) |
424 | if (auto *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl())) { |
425 | Sema::ContextRAII SavedContext(S, FD); |
426 | LocalInstantiationScope Local(S); |
427 | if (FD->getNumParams() > PVD->getFunctionScopeIndex()) |
428 | Local.InstantiatedLocal( |
429 | D: PVD, Inst: FD->getParamDecl(i: PVD->getFunctionScopeIndex())); |
430 | return S.SubstExpr(E, TemplateArgs); |
431 | } |
432 | Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(), |
433 | FD->isCXXInstanceMember()); |
434 | return S.SubstExpr(E, TemplateArgs); |
435 | }; |
436 | |
437 | // Substitute a single OpenMP clause, which is a potentially-evaluated |
438 | // full-expression. |
439 | auto &&Subst = [&SubstExpr, &S](Expr *E) { |
440 | EnterExpressionEvaluationContext Evaluated( |
441 | S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
442 | ExprResult Res = SubstExpr(E); |
443 | if (Res.isInvalid()) |
444 | return Res; |
445 | return S.ActOnFinishFullExpr(Expr: Res.get(), DiscardedValue: false); |
446 | }; |
447 | |
448 | ExprResult VariantFuncRef; |
449 | if (Expr *E = Attr.getVariantFuncRef()) { |
450 | // Do not mark function as is used to prevent its emission if this is the |
451 | // only place where it is used. |
452 | EnterExpressionEvaluationContext Unevaluated( |
453 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
454 | VariantFuncRef = Subst(E); |
455 | } |
456 | |
457 | // Copy the template version of the OMPTraitInfo and run substitute on all |
458 | // score and condition expressiosn. |
459 | OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo(); |
460 | TI = *Attr.getTraitInfos(); |
461 | |
462 | // Try to substitute template parameters in score and condition expressions. |
463 | auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) { |
464 | if (E) { |
465 | EnterExpressionEvaluationContext Unevaluated( |
466 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
467 | ExprResult ER = Subst(E); |
468 | if (ER.isUsable()) |
469 | E = ER.get(); |
470 | else |
471 | return true; |
472 | } |
473 | return false; |
474 | }; |
475 | if (TI.anyScoreOrCondition(Cond: SubstScoreOrConditionExpr)) |
476 | return; |
477 | |
478 | Expr *E = VariantFuncRef.get(); |
479 | |
480 | // Check function/variant ref for `omp declare variant` but not for `omp |
481 | // begin declare variant` (which use implicit attributes). |
482 | std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData = |
483 | S.OpenMP().checkOpenMPDeclareVariantFunction( |
484 | DG: S.ConvertDeclToDeclGroup(Ptr: New), VariantRef: E, TI, NumAppendArgs: Attr.appendArgs_size(), |
485 | SR: Attr.getRange()); |
486 | |
487 | if (!DeclVarData) |
488 | return; |
489 | |
490 | E = DeclVarData->second; |
491 | FD = DeclVarData->first; |
492 | |
493 | if (auto *VariantDRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts())) { |
494 | if (auto *VariantFD = dyn_cast<FunctionDecl>(Val: VariantDRE->getDecl())) { |
495 | if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) { |
496 | if (!VariantFTD->isThisDeclarationADefinition()) |
497 | return; |
498 | Sema::TentativeAnalysisScope Trap(S); |
499 | const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy( |
500 | Context&: S.Context, Args: TemplateArgs.getInnermost()); |
501 | |
502 | auto *SubstFD = S.InstantiateFunctionDeclaration(FTD: VariantFTD, Args: TAL, |
503 | Loc: New->getLocation()); |
504 | if (!SubstFD) |
505 | return; |
506 | QualType NewType = S.Context.mergeFunctionTypes( |
507 | SubstFD->getType(), FD->getType(), |
508 | /* OfBlockPointer */ false, |
509 | /* Unqualified */ false, /* AllowCXX */ true); |
510 | if (NewType.isNull()) |
511 | return; |
512 | S.InstantiateFunctionDefinition( |
513 | PointOfInstantiation: New->getLocation(), Function: SubstFD, /* Recursive */ true, |
514 | /* DefinitionRequired */ false, /* AtEndOfTU */ false); |
515 | SubstFD->setInstantiationIsPending(!SubstFD->isDefined()); |
516 | E = DeclRefExpr::Create(Context: S.Context, QualifierLoc: NestedNameSpecifierLoc(), |
517 | TemplateKWLoc: SourceLocation(), D: SubstFD, |
518 | /* RefersToEnclosingVariableOrCapture */ false, |
519 | /* NameLoc */ SubstFD->getLocation(), |
520 | T: SubstFD->getType(), VK: ExprValueKind::VK_PRValue); |
521 | } |
522 | } |
523 | } |
524 | |
525 | SmallVector<Expr *, 8> NothingExprs; |
526 | SmallVector<Expr *, 8> NeedDevicePtrExprs; |
527 | SmallVector<OMPInteropInfo, 4> AppendArgs; |
528 | |
529 | for (Expr *E : Attr.adjustArgsNothing()) { |
530 | ExprResult ER = Subst(E); |
531 | if (ER.isInvalid()) |
532 | continue; |
533 | NothingExprs.push_back(Elt: ER.get()); |
534 | } |
535 | for (Expr *E : Attr.adjustArgsNeedDevicePtr()) { |
536 | ExprResult ER = Subst(E); |
537 | if (ER.isInvalid()) |
538 | continue; |
539 | NeedDevicePtrExprs.push_back(Elt: ER.get()); |
540 | } |
541 | for (OMPInteropInfo &II : Attr.appendArgs()) { |
542 | // When prefer_type is implemented for append_args handle them here too. |
543 | AppendArgs.emplace_back(Args&: II.IsTarget, Args&: II.IsTargetSync); |
544 | } |
545 | |
546 | S.OpenMP().ActOnOpenMPDeclareVariantDirective( |
547 | FD, VariantRef: E, TI, AdjustArgsNothing: NothingExprs, AdjustArgsNeedDevicePtr: NeedDevicePtrExprs, AppendArgs, AdjustArgsLoc: SourceLocation(), |
548 | AppendArgsLoc: SourceLocation(), SR: Attr.getRange()); |
549 | } |
550 | |
551 | static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr( |
552 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
553 | const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) { |
554 | // Both min and max expression are constant expressions. |
555 | EnterExpressionEvaluationContext Unevaluated( |
556 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
557 | |
558 | ExprResult Result = S.SubstExpr(E: Attr.getMin(), TemplateArgs); |
559 | if (Result.isInvalid()) |
560 | return; |
561 | Expr *MinExpr = Result.getAs<Expr>(); |
562 | |
563 | Result = S.SubstExpr(E: Attr.getMax(), TemplateArgs); |
564 | if (Result.isInvalid()) |
565 | return; |
566 | Expr *MaxExpr = Result.getAs<Expr>(); |
567 | |
568 | S.AMDGPU().addAMDGPUFlatWorkGroupSizeAttr(D: New, CI: Attr, Min: MinExpr, Max: MaxExpr); |
569 | } |
570 | |
571 | ExplicitSpecifier Sema::instantiateExplicitSpecifier( |
572 | const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) { |
573 | if (!ES.getExpr()) |
574 | return ES; |
575 | Expr *OldCond = ES.getExpr(); |
576 | Expr *Cond = nullptr; |
577 | { |
578 | EnterExpressionEvaluationContext Unevaluated( |
579 | *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
580 | ExprResult SubstResult = SubstExpr(E: OldCond, TemplateArgs); |
581 | if (SubstResult.isInvalid()) { |
582 | return ExplicitSpecifier::Invalid(); |
583 | } |
584 | Cond = SubstResult.get(); |
585 | } |
586 | ExplicitSpecifier Result(Cond, ES.getKind()); |
587 | if (!Cond->isTypeDependent()) |
588 | tryResolveExplicitSpecifier(ExplicitSpec&: Result); |
589 | return Result; |
590 | } |
591 | |
592 | static void instantiateDependentAMDGPUWavesPerEUAttr( |
593 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
594 | const AMDGPUWavesPerEUAttr &Attr, Decl *New) { |
595 | // Both min and max expression are constant expressions. |
596 | EnterExpressionEvaluationContext Unevaluated( |
597 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
598 | |
599 | ExprResult Result = S.SubstExpr(E: Attr.getMin(), TemplateArgs); |
600 | if (Result.isInvalid()) |
601 | return; |
602 | Expr *MinExpr = Result.getAs<Expr>(); |
603 | |
604 | Expr *MaxExpr = nullptr; |
605 | if (auto Max = Attr.getMax()) { |
606 | Result = S.SubstExpr(E: Max, TemplateArgs); |
607 | if (Result.isInvalid()) |
608 | return; |
609 | MaxExpr = Result.getAs<Expr>(); |
610 | } |
611 | |
612 | S.AMDGPU().addAMDGPUWavesPerEUAttr(D: New, CI: Attr, Min: MinExpr, Max: MaxExpr); |
613 | } |
614 | |
615 | static void instantiateDependentAMDGPUMaxNumWorkGroupsAttr( |
616 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
617 | const AMDGPUMaxNumWorkGroupsAttr &Attr, Decl *New) { |
618 | EnterExpressionEvaluationContext Unevaluated( |
619 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
620 | |
621 | ExprResult ResultX = S.SubstExpr(E: Attr.getMaxNumWorkGroupsX(), TemplateArgs); |
622 | if (!ResultX.isUsable()) |
623 | return; |
624 | ExprResult ResultY = S.SubstExpr(E: Attr.getMaxNumWorkGroupsY(), TemplateArgs); |
625 | if (!ResultY.isUsable()) |
626 | return; |
627 | ExprResult ResultZ = S.SubstExpr(E: Attr.getMaxNumWorkGroupsZ(), TemplateArgs); |
628 | if (!ResultZ.isUsable()) |
629 | return; |
630 | |
631 | Expr *XExpr = ResultX.getAs<Expr>(); |
632 | Expr *YExpr = ResultY.getAs<Expr>(); |
633 | Expr *ZExpr = ResultZ.getAs<Expr>(); |
634 | |
635 | S.AMDGPU().addAMDGPUMaxNumWorkGroupsAttr(D: New, CI: Attr, XExpr, YExpr, ZExpr); |
636 | } |
637 | |
638 | // This doesn't take any template parameters, but we have a custom action that |
639 | // needs to happen when the kernel itself is instantiated. We need to run the |
640 | // ItaniumMangler to mark the names required to name this kernel. |
641 | static void instantiateDependentSYCLKernelAttr( |
642 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
643 | const SYCLKernelAttr &Attr, Decl *New) { |
644 | New->addAttr(A: Attr.clone(C&: S.getASTContext())); |
645 | } |
646 | |
647 | /// Determine whether the attribute A might be relevant to the declaration D. |
648 | /// If not, we can skip instantiating it. The attribute may or may not have |
649 | /// been instantiated yet. |
650 | static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) { |
651 | // 'preferred_name' is only relevant to the matching specialization of the |
652 | // template. |
653 | if (const auto *PNA = dyn_cast<PreferredNameAttr>(Val: A)) { |
654 | QualType T = PNA->getTypedefType(); |
655 | const auto *RD = cast<CXXRecordDecl>(Val: D); |
656 | if (!T->isDependentType() && !RD->isDependentContext() && |
657 | !declaresSameEntity(D1: T->getAsCXXRecordDecl(), D2: RD)) |
658 | return false; |
659 | for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>()) |
660 | if (S.Context.hasSameType(T1: ExistingPNA->getTypedefType(), |
661 | T2: PNA->getTypedefType())) |
662 | return false; |
663 | return true; |
664 | } |
665 | |
666 | if (const auto *BA = dyn_cast<BuiltinAttr>(Val: A)) { |
667 | const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D); |
668 | switch (BA->getID()) { |
669 | case Builtin::BIforward: |
670 | // Do not treat 'std::forward' as a builtin if it takes an rvalue reference |
671 | // type and returns an lvalue reference type. The library implementation |
672 | // will produce an error in this case; don't get in its way. |
673 | if (FD && FD->getNumParams() >= 1 && |
674 | FD->getParamDecl(i: 0)->getType()->isRValueReferenceType() && |
675 | FD->getReturnType()->isLValueReferenceType()) { |
676 | return false; |
677 | } |
678 | [[fallthrough]]; |
679 | case Builtin::BImove: |
680 | case Builtin::BImove_if_noexcept: |
681 | // HACK: Super-old versions of libc++ (3.1 and earlier) provide |
682 | // std::forward and std::move overloads that sometimes return by value |
683 | // instead of by reference when building in C++98 mode. Don't treat such |
684 | // cases as builtins. |
685 | if (FD && !FD->getReturnType()->isReferenceType()) |
686 | return false; |
687 | break; |
688 | } |
689 | } |
690 | |
691 | return true; |
692 | } |
693 | |
694 | static void instantiateDependentHLSLParamModifierAttr( |
695 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
696 | const HLSLParamModifierAttr *Attr, Decl *New) { |
697 | ParmVarDecl *P = cast<ParmVarDecl>(Val: New); |
698 | P->addAttr(A: Attr->clone(C&: S.getASTContext())); |
699 | P->setType(S.getASTContext().getLValueReferenceType(T: P->getType())); |
700 | } |
701 | |
702 | void Sema::InstantiateAttrsForDecl( |
703 | const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl, |
704 | Decl *New, LateInstantiatedAttrVec *LateAttrs, |
705 | LocalInstantiationScope *OuterMostScope) { |
706 | if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: New)) { |
707 | // FIXME: This function is called multiple times for the same template |
708 | // specialization. We should only instantiate attributes that were added |
709 | // since the previous instantiation. |
710 | for (const auto *TmplAttr : Tmpl->attrs()) { |
711 | if (!isRelevantAttr(S&: *this, D: New, A: TmplAttr)) |
712 | continue; |
713 | |
714 | // FIXME: If any of the special case versions from InstantiateAttrs become |
715 | // applicable to template declaration, we'll need to add them here. |
716 | CXXThisScopeRAII ThisScope( |
717 | *this, dyn_cast_or_null<CXXRecordDecl>(Val: ND->getDeclContext()), |
718 | Qualifiers(), ND->isCXXInstanceMember()); |
719 | |
720 | Attr *NewAttr = sema::instantiateTemplateAttributeForDecl( |
721 | At: TmplAttr, C&: Context, S&: *this, TemplateArgs); |
722 | if (NewAttr && isRelevantAttr(S&: *this, D: New, A: NewAttr)) |
723 | New->addAttr(A: NewAttr); |
724 | } |
725 | } |
726 | } |
727 | |
728 | static Sema::RetainOwnershipKind |
729 | attrToRetainOwnershipKind(const Attr *A) { |
730 | switch (A->getKind()) { |
731 | case clang::attr::CFConsumed: |
732 | return Sema::RetainOwnershipKind::CF; |
733 | case clang::attr::OSConsumed: |
734 | return Sema::RetainOwnershipKind::OS; |
735 | case clang::attr::NSConsumed: |
736 | return Sema::RetainOwnershipKind::NS; |
737 | default: |
738 | llvm_unreachable("Wrong argument supplied" ); |
739 | } |
740 | } |
741 | |
742 | void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, |
743 | const Decl *Tmpl, Decl *New, |
744 | LateInstantiatedAttrVec *LateAttrs, |
745 | LocalInstantiationScope *OuterMostScope) { |
746 | for (const auto *TmplAttr : Tmpl->attrs()) { |
747 | if (!isRelevantAttr(S&: *this, D: New, A: TmplAttr)) |
748 | continue; |
749 | |
750 | // FIXME: This should be generalized to more than just the AlignedAttr. |
751 | const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(Val: TmplAttr); |
752 | if (Aligned && Aligned->isAlignmentDependent()) { |
753 | instantiateDependentAlignedAttr(S&: *this, TemplateArgs, Aligned, New); |
754 | continue; |
755 | } |
756 | |
757 | if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(Val: TmplAttr)) { |
758 | instantiateDependentAssumeAlignedAttr(S&: *this, TemplateArgs, Aligned: AssumeAligned, New); |
759 | continue; |
760 | } |
761 | |
762 | if (const auto *AlignValue = dyn_cast<AlignValueAttr>(Val: TmplAttr)) { |
763 | instantiateDependentAlignValueAttr(S&: *this, TemplateArgs, Aligned: AlignValue, New); |
764 | continue; |
765 | } |
766 | |
767 | if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(Val: TmplAttr)) { |
768 | instantiateDependentAllocAlignAttr(S&: *this, TemplateArgs, Align: AllocAlign, New); |
769 | continue; |
770 | } |
771 | |
772 | if (const auto *Annotate = dyn_cast<AnnotateAttr>(Val: TmplAttr)) { |
773 | instantiateDependentAnnotationAttr(S&: *this, TemplateArgs, Attr: Annotate, New); |
774 | continue; |
775 | } |
776 | |
777 | if (const auto *EnableIf = dyn_cast<EnableIfAttr>(Val: TmplAttr)) { |
778 | instantiateDependentEnableIfAttr(S&: *this, TemplateArgs, EIA: EnableIf, Tmpl, |
779 | New: cast<FunctionDecl>(Val: New)); |
780 | continue; |
781 | } |
782 | |
783 | if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(Val: TmplAttr)) { |
784 | instantiateDependentDiagnoseIfAttr(S&: *this, TemplateArgs, DIA: DiagnoseIf, Tmpl, |
785 | New: cast<FunctionDecl>(Val: New)); |
786 | continue; |
787 | } |
788 | |
789 | if (const auto *CUDALaunchBounds = |
790 | dyn_cast<CUDALaunchBoundsAttr>(Val: TmplAttr)) { |
791 | instantiateDependentCUDALaunchBoundsAttr(S&: *this, TemplateArgs, |
792 | Attr: *CUDALaunchBounds, New); |
793 | continue; |
794 | } |
795 | |
796 | if (const auto *Mode = dyn_cast<ModeAttr>(Val: TmplAttr)) { |
797 | instantiateDependentModeAttr(S&: *this, TemplateArgs, Attr: *Mode, New); |
798 | continue; |
799 | } |
800 | |
801 | if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(Val: TmplAttr)) { |
802 | instantiateOMPDeclareSimdDeclAttr(S&: *this, TemplateArgs, Attr: *OMPAttr, New); |
803 | continue; |
804 | } |
805 | |
806 | if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(Val: TmplAttr)) { |
807 | instantiateOMPDeclareVariantAttr(S&: *this, TemplateArgs, Attr: *OMPAttr, New); |
808 | continue; |
809 | } |
810 | |
811 | if (const auto *AMDGPUFlatWorkGroupSize = |
812 | dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(Val: TmplAttr)) { |
813 | instantiateDependentAMDGPUFlatWorkGroupSizeAttr( |
814 | S&: *this, TemplateArgs, Attr: *AMDGPUFlatWorkGroupSize, New); |
815 | } |
816 | |
817 | if (const auto *AMDGPUFlatWorkGroupSize = |
818 | dyn_cast<AMDGPUWavesPerEUAttr>(Val: TmplAttr)) { |
819 | instantiateDependentAMDGPUWavesPerEUAttr(S&: *this, TemplateArgs, |
820 | Attr: *AMDGPUFlatWorkGroupSize, New); |
821 | } |
822 | |
823 | if (const auto *AMDGPUMaxNumWorkGroups = |
824 | dyn_cast<AMDGPUMaxNumWorkGroupsAttr>(Val: TmplAttr)) { |
825 | instantiateDependentAMDGPUMaxNumWorkGroupsAttr( |
826 | S&: *this, TemplateArgs, Attr: *AMDGPUMaxNumWorkGroups, New); |
827 | } |
828 | |
829 | if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(Val: TmplAttr)) { |
830 | instantiateDependentHLSLParamModifierAttr(S&: *this, TemplateArgs, Attr: ParamAttr, |
831 | New); |
832 | continue; |
833 | } |
834 | |
835 | // Existing DLL attribute on the instantiation takes precedence. |
836 | if (TmplAttr->getKind() == attr::DLLExport || |
837 | TmplAttr->getKind() == attr::DLLImport) { |
838 | if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) { |
839 | continue; |
840 | } |
841 | } |
842 | |
843 | if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(Val: TmplAttr)) { |
844 | Swift().AddParameterABIAttr(D: New, CI: *ABIAttr, abi: ABIAttr->getABI()); |
845 | continue; |
846 | } |
847 | |
848 | if (isa<NSConsumedAttr>(Val: TmplAttr) || isa<OSConsumedAttr>(Val: TmplAttr) || |
849 | isa<CFConsumedAttr>(Val: TmplAttr)) { |
850 | ObjC().AddXConsumedAttr(D: New, CI: *TmplAttr, |
851 | K: attrToRetainOwnershipKind(A: TmplAttr), |
852 | /*template instantiation=*/IsTemplateInstantiation: true); |
853 | continue; |
854 | } |
855 | |
856 | if (auto *A = dyn_cast<PointerAttr>(Val: TmplAttr)) { |
857 | if (!New->hasAttr<PointerAttr>()) |
858 | New->addAttr(A: A->clone(C&: Context)); |
859 | continue; |
860 | } |
861 | |
862 | if (auto *A = dyn_cast<OwnerAttr>(Val: TmplAttr)) { |
863 | if (!New->hasAttr<OwnerAttr>()) |
864 | New->addAttr(A: A->clone(C&: Context)); |
865 | continue; |
866 | } |
867 | |
868 | if (auto *A = dyn_cast<SYCLKernelAttr>(Val: TmplAttr)) { |
869 | instantiateDependentSYCLKernelAttr(S&: *this, TemplateArgs, Attr: *A, New); |
870 | continue; |
871 | } |
872 | |
873 | assert(!TmplAttr->isPackExpansion()); |
874 | if (TmplAttr->isLateParsed() && LateAttrs) { |
875 | // Late parsed attributes must be instantiated and attached after the |
876 | // enclosing class has been instantiated. See Sema::InstantiateClass. |
877 | LocalInstantiationScope *Saved = nullptr; |
878 | if (CurrentInstantiationScope) |
879 | Saved = CurrentInstantiationScope->cloneScopes(Outermost: OuterMostScope); |
880 | LateAttrs->push_back(Elt: LateInstantiatedAttribute(TmplAttr, Saved, New)); |
881 | } else { |
882 | // Allow 'this' within late-parsed attributes. |
883 | auto *ND = cast<NamedDecl>(Val: New); |
884 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: ND->getDeclContext()); |
885 | CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), |
886 | ND->isCXXInstanceMember()); |
887 | |
888 | Attr *NewAttr = sema::instantiateTemplateAttribute(At: TmplAttr, C&: Context, |
889 | S&: *this, TemplateArgs); |
890 | if (NewAttr && isRelevantAttr(S&: *this, D: New, A: TmplAttr)) |
891 | New->addAttr(A: NewAttr); |
892 | } |
893 | } |
894 | } |
895 | |
896 | void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) { |
897 | for (const auto *Attr : Pattern->attrs()) { |
898 | if (auto *A = dyn_cast<StrictFPAttr>(Val: Attr)) { |
899 | if (!Inst->hasAttr<StrictFPAttr>()) |
900 | Inst->addAttr(A: A->clone(C&: getASTContext())); |
901 | continue; |
902 | } |
903 | } |
904 | } |
905 | |
906 | void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) { |
907 | assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && |
908 | Ctor->isDefaultConstructor()); |
909 | unsigned NumParams = Ctor->getNumParams(); |
910 | if (NumParams == 0) |
911 | return; |
912 | DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>(); |
913 | if (!Attr) |
914 | return; |
915 | for (unsigned I = 0; I != NumParams; ++I) { |
916 | (void)CheckCXXDefaultArgExpr(CallLoc: Attr->getLocation(), FD: Ctor, |
917 | Param: Ctor->getParamDecl(i: I)); |
918 | CleanupVarDeclMarking(); |
919 | } |
920 | } |
921 | |
922 | /// Get the previous declaration of a declaration for the purposes of template |
923 | /// instantiation. If this finds a previous declaration, then the previous |
924 | /// declaration of the instantiation of D should be an instantiation of the |
925 | /// result of this function. |
926 | template<typename DeclT> |
927 | static DeclT *getPreviousDeclForInstantiation(DeclT *D) { |
928 | DeclT *Result = D->getPreviousDecl(); |
929 | |
930 | // If the declaration is within a class, and the previous declaration was |
931 | // merged from a different definition of that class, then we don't have a |
932 | // previous declaration for the purpose of template instantiation. |
933 | if (Result && isa<CXXRecordDecl>(D->getDeclContext()) && |
934 | D->getLexicalDeclContext() != Result->getLexicalDeclContext()) |
935 | return nullptr; |
936 | |
937 | return Result; |
938 | } |
939 | |
940 | Decl * |
941 | TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { |
942 | llvm_unreachable("Translation units cannot be instantiated" ); |
943 | } |
944 | |
945 | Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) { |
946 | llvm_unreachable("HLSL buffer declarations cannot be instantiated" ); |
947 | } |
948 | |
949 | Decl * |
950 | TemplateDeclInstantiator::(PragmaCommentDecl *D) { |
951 | llvm_unreachable("pragma comment cannot be instantiated" ); |
952 | } |
953 | |
954 | Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl( |
955 | PragmaDetectMismatchDecl *D) { |
956 | llvm_unreachable("pragma comment cannot be instantiated" ); |
957 | } |
958 | |
959 | Decl * |
960 | TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) { |
961 | llvm_unreachable("extern \"C\" context cannot be instantiated" ); |
962 | } |
963 | |
964 | Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) { |
965 | llvm_unreachable("GUID declaration cannot be instantiated" ); |
966 | } |
967 | |
968 | Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl( |
969 | UnnamedGlobalConstantDecl *D) { |
970 | llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated" ); |
971 | } |
972 | |
973 | Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl( |
974 | TemplateParamObjectDecl *D) { |
975 | llvm_unreachable("template parameter objects cannot be instantiated" ); |
976 | } |
977 | |
978 | Decl * |
979 | TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { |
980 | LabelDecl *Inst = LabelDecl::Create(C&: SemaRef.Context, DC: Owner, IdentL: D->getLocation(), |
981 | II: D->getIdentifier()); |
982 | Owner->addDecl(D: Inst); |
983 | return Inst; |
984 | } |
985 | |
986 | Decl * |
987 | TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { |
988 | llvm_unreachable("Namespaces cannot be instantiated" ); |
989 | } |
990 | |
991 | Decl * |
992 | TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { |
993 | NamespaceAliasDecl *Inst |
994 | = NamespaceAliasDecl::Create(C&: SemaRef.Context, DC: Owner, |
995 | NamespaceLoc: D->getNamespaceLoc(), |
996 | AliasLoc: D->getAliasLoc(), |
997 | Alias: D->getIdentifier(), |
998 | QualifierLoc: D->getQualifierLoc(), |
999 | IdentLoc: D->getTargetNameLoc(), |
1000 | Namespace: D->getNamespace()); |
1001 | Owner->addDecl(D: Inst); |
1002 | return Inst; |
1003 | } |
1004 | |
1005 | Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, |
1006 | bool IsTypeAlias) { |
1007 | bool Invalid = false; |
1008 | TypeSourceInfo *DI = D->getTypeSourceInfo(); |
1009 | if (DI->getType()->isInstantiationDependentType() || |
1010 | DI->getType()->isVariablyModifiedType()) { |
1011 | DI = SemaRef.SubstType(T: DI, TemplateArgs, |
1012 | Loc: D->getLocation(), Entity: D->getDeclName()); |
1013 | if (!DI) { |
1014 | Invalid = true; |
1015 | DI = SemaRef.Context.getTrivialTypeSourceInfo(T: SemaRef.Context.IntTy); |
1016 | } |
1017 | } else { |
1018 | SemaRef.MarkDeclarationsReferencedInType(Loc: D->getLocation(), T: DI->getType()); |
1019 | } |
1020 | |
1021 | // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong. |
1022 | // libstdc++ relies upon this bug in its implementation of common_type. If we |
1023 | // happen to be processing that implementation, fake up the g++ ?: |
1024 | // semantics. See LWG issue 2141 for more information on the bug. The bugs |
1025 | // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22). |
1026 | const DecltypeType *DT = DI->getType()->getAs<DecltypeType>(); |
1027 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D->getDeclContext()); |
1028 | if (DT && RD && isa<ConditionalOperator>(Val: DT->getUnderlyingExpr()) && |
1029 | DT->isReferenceType() && |
1030 | RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() && |
1031 | RD->getIdentifier() && RD->getIdentifier()->isStr(Str: "common_type" ) && |
1032 | D->getIdentifier() && D->getIdentifier()->isStr(Str: "type" ) && |
1033 | SemaRef.getSourceManager().isInSystemHeader(Loc: D->getBeginLoc())) |
1034 | // Fold it to the (non-reference) type which g++ would have produced. |
1035 | DI = SemaRef.Context.getTrivialTypeSourceInfo( |
1036 | T: DI->getType().getNonReferenceType()); |
1037 | |
1038 | // Create the new typedef |
1039 | TypedefNameDecl *Typedef; |
1040 | if (IsTypeAlias) |
1041 | Typedef = TypeAliasDecl::Create(C&: SemaRef.Context, DC: Owner, StartLoc: D->getBeginLoc(), |
1042 | IdLoc: D->getLocation(), Id: D->getIdentifier(), TInfo: DI); |
1043 | else |
1044 | Typedef = TypedefDecl::Create(C&: SemaRef.Context, DC: Owner, StartLoc: D->getBeginLoc(), |
1045 | IdLoc: D->getLocation(), Id: D->getIdentifier(), TInfo: DI); |
1046 | if (Invalid) |
1047 | Typedef->setInvalidDecl(); |
1048 | |
1049 | // If the old typedef was the name for linkage purposes of an anonymous |
1050 | // tag decl, re-establish that relationship for the new typedef. |
1051 | if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { |
1052 | TagDecl *oldTag = oldTagType->getDecl(); |
1053 | if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) { |
1054 | TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); |
1055 | assert(!newTag->hasNameForLinkage()); |
1056 | newTag->setTypedefNameForAnonDecl(Typedef); |
1057 | } |
1058 | } |
1059 | |
1060 | if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) { |
1061 | NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: Prev, |
1062 | TemplateArgs); |
1063 | if (!InstPrev) |
1064 | return nullptr; |
1065 | |
1066 | TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(Val: InstPrev); |
1067 | |
1068 | // If the typedef types are not identical, reject them. |
1069 | SemaRef.isIncompatibleTypedef(Old: InstPrevTypedef, New: Typedef); |
1070 | |
1071 | Typedef->setPreviousDecl(InstPrevTypedef); |
1072 | } |
1073 | |
1074 | SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: Typedef); |
1075 | |
1076 | if (D->getUnderlyingType()->getAs<DependentNameType>()) |
1077 | SemaRef.inferGslPointerAttribute(TD: Typedef); |
1078 | |
1079 | Typedef->setAccess(D->getAccess()); |
1080 | Typedef->setReferenced(D->isReferenced()); |
1081 | |
1082 | return Typedef; |
1083 | } |
1084 | |
1085 | Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { |
1086 | Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); |
1087 | if (Typedef) |
1088 | Owner->addDecl(D: Typedef); |
1089 | return Typedef; |
1090 | } |
1091 | |
1092 | Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { |
1093 | Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); |
1094 | if (Typedef) |
1095 | Owner->addDecl(D: Typedef); |
1096 | return Typedef; |
1097 | } |
1098 | |
1099 | Decl *TemplateDeclInstantiator::InstantiateTypeAliasTemplateDecl( |
1100 | TypeAliasTemplateDecl *D) { |
1101 | // Create a local instantiation scope for this type alias template, which |
1102 | // will contain the instantiations of the template parameters. |
1103 | LocalInstantiationScope Scope(SemaRef); |
1104 | |
1105 | TemplateParameterList *TempParams = D->getTemplateParameters(); |
1106 | TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams); |
1107 | if (!InstParams) |
1108 | return nullptr; |
1109 | |
1110 | TypeAliasDecl *Pattern = D->getTemplatedDecl(); |
1111 | Sema::InstantiatingTemplate InstTemplate( |
1112 | SemaRef, D->getBeginLoc(), D, |
1113 | D->getTemplateDepth() >= TemplateArgs.getNumLevels() |
1114 | ? ArrayRef<TemplateArgument>() |
1115 | : (TemplateArgs.begin() + TemplateArgs.getNumLevels() - 1 - |
1116 | D->getTemplateDepth()) |
1117 | ->Args); |
1118 | if (InstTemplate.isInvalid()) |
1119 | return nullptr; |
1120 | |
1121 | TypeAliasTemplateDecl *PrevAliasTemplate = nullptr; |
1122 | if (getPreviousDeclForInstantiation<TypedefNameDecl>(D: Pattern)) { |
1123 | DeclContext::lookup_result Found = Owner->lookup(Name: Pattern->getDeclName()); |
1124 | if (!Found.empty()) { |
1125 | PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Val: Found.front()); |
1126 | } |
1127 | } |
1128 | |
1129 | TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( |
1130 | Val: InstantiateTypedefNameDecl(D: Pattern, /*IsTypeAlias=*/true)); |
1131 | if (!AliasInst) |
1132 | return nullptr; |
1133 | |
1134 | TypeAliasTemplateDecl *Inst |
1135 | = TypeAliasTemplateDecl::Create(C&: SemaRef.Context, DC: Owner, L: D->getLocation(), |
1136 | Name: D->getDeclName(), Params: InstParams, Decl: AliasInst); |
1137 | AliasInst->setDescribedAliasTemplate(Inst); |
1138 | if (PrevAliasTemplate) |
1139 | Inst->setPreviousDecl(PrevAliasTemplate); |
1140 | |
1141 | Inst->setAccess(D->getAccess()); |
1142 | |
1143 | if (!PrevAliasTemplate) |
1144 | Inst->setInstantiatedFromMemberTemplate(D); |
1145 | |
1146 | return Inst; |
1147 | } |
1148 | |
1149 | Decl * |
1150 | TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { |
1151 | Decl *Inst = InstantiateTypeAliasTemplateDecl(D); |
1152 | if (Inst) |
1153 | Owner->addDecl(D: Inst); |
1154 | |
1155 | return Inst; |
1156 | } |
1157 | |
1158 | Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) { |
1159 | auto *NewBD = BindingDecl::Create(C&: SemaRef.Context, DC: Owner, IdLoc: D->getLocation(), |
1160 | Id: D->getIdentifier()); |
1161 | NewBD->setReferenced(D->isReferenced()); |
1162 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewBD); |
1163 | return NewBD; |
1164 | } |
1165 | |
1166 | Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) { |
1167 | // Transform the bindings first. |
1168 | SmallVector<BindingDecl*, 16> NewBindings; |
1169 | for (auto *OldBD : D->bindings()) |
1170 | NewBindings.push_back(Elt: cast<BindingDecl>(Val: VisitBindingDecl(D: OldBD))); |
1171 | ArrayRef<BindingDecl*> NewBindingArray = NewBindings; |
1172 | |
1173 | auto *NewDD = cast_or_null<DecompositionDecl>( |
1174 | Val: VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, Bindings: &NewBindingArray)); |
1175 | |
1176 | if (!NewDD || NewDD->isInvalidDecl()) |
1177 | for (auto *NewBD : NewBindings) |
1178 | NewBD->setInvalidDecl(); |
1179 | |
1180 | return NewDD; |
1181 | } |
1182 | |
1183 | Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { |
1184 | return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false); |
1185 | } |
1186 | |
1187 | Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, |
1188 | bool InstantiatingVarTemplate, |
1189 | ArrayRef<BindingDecl*> *Bindings) { |
1190 | |
1191 | // Do substitution on the type of the declaration |
1192 | TypeSourceInfo *DI = SemaRef.SubstType( |
1193 | T: D->getTypeSourceInfo(), TemplateArgs, Loc: D->getTypeSpecStartLoc(), |
1194 | Entity: D->getDeclName(), /*AllowDeducedTST*/true); |
1195 | if (!DI) |
1196 | return nullptr; |
1197 | |
1198 | if (DI->getType()->isFunctionType()) { |
1199 | SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_variable_instantiates_to_function) |
1200 | << D->isStaticDataMember() << DI->getType(); |
1201 | return nullptr; |
1202 | } |
1203 | |
1204 | DeclContext *DC = Owner; |
1205 | if (D->isLocalExternDecl()) |
1206 | SemaRef.adjustContextForLocalExternDecl(DC); |
1207 | |
1208 | // Build the instantiated declaration. |
1209 | VarDecl *Var; |
1210 | if (Bindings) |
1211 | Var = DecompositionDecl::Create(C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(), |
1212 | LSquareLoc: D->getLocation(), T: DI->getType(), TInfo: DI, |
1213 | S: D->getStorageClass(), Bindings: *Bindings); |
1214 | else |
1215 | Var = VarDecl::Create(C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(), |
1216 | IdLoc: D->getLocation(), Id: D->getIdentifier(), T: DI->getType(), |
1217 | TInfo: DI, S: D->getStorageClass()); |
1218 | |
1219 | // In ARC, infer 'retaining' for variables of retainable type. |
1220 | if (SemaRef.getLangOpts().ObjCAutoRefCount && |
1221 | SemaRef.ObjC().inferObjCARCLifetime(decl: Var)) |
1222 | Var->setInvalidDecl(); |
1223 | |
1224 | if (SemaRef.getLangOpts().OpenCL) |
1225 | SemaRef.deduceOpenCLAddressSpace(decl: Var); |
1226 | |
1227 | // Substitute the nested name specifier, if any. |
1228 | if (SubstQualifier(OldDecl: D, NewDecl: Var)) |
1229 | return nullptr; |
1230 | |
1231 | SemaRef.BuildVariableInstantiation(NewVar: Var, OldVar: D, TemplateArgs, LateAttrs, Owner, |
1232 | StartingScope, InstantiatingVarTemplate); |
1233 | if (D->isNRVOVariable() && !Var->isInvalidDecl()) { |
1234 | QualType RT; |
1235 | if (auto *F = dyn_cast<FunctionDecl>(Val: DC)) |
1236 | RT = F->getReturnType(); |
1237 | else if (isa<BlockDecl>(Val: DC)) |
1238 | RT = cast<FunctionType>(Val&: SemaRef.getCurBlock()->FunctionType) |
1239 | ->getReturnType(); |
1240 | else |
1241 | llvm_unreachable("Unknown context type" ); |
1242 | |
1243 | // This is the last chance we have of checking copy elision eligibility |
1244 | // for functions in dependent contexts. The sema actions for building |
1245 | // the return statement during template instantiation will have no effect |
1246 | // regarding copy elision, since NRVO propagation runs on the scope exit |
1247 | // actions, and these are not run on instantiation. |
1248 | // This might run through some VarDecls which were returned from non-taken |
1249 | // 'if constexpr' branches, and these will end up being constructed on the |
1250 | // return slot even if they will never be returned, as a sort of accidental |
1251 | // 'optimization'. Notably, functions with 'auto' return types won't have it |
1252 | // deduced by this point. Coupled with the limitation described |
1253 | // previously, this makes it very hard to support copy elision for these. |
1254 | Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(VD: Var); |
1255 | bool NRVO = SemaRef.getCopyElisionCandidate(Info, ReturnType: RT) != nullptr; |
1256 | Var->setNRVOVariable(NRVO); |
1257 | } |
1258 | |
1259 | Var->setImplicit(D->isImplicit()); |
1260 | |
1261 | if (Var->isStaticLocal()) |
1262 | SemaRef.CheckStaticLocalForDllExport(VD: Var); |
1263 | |
1264 | if (Var->getTLSKind()) |
1265 | SemaRef.CheckThreadLocalForLargeAlignment(VD: Var); |
1266 | |
1267 | return Var; |
1268 | } |
1269 | |
1270 | Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { |
1271 | AccessSpecDecl* AD |
1272 | = AccessSpecDecl::Create(C&: SemaRef.Context, AS: D->getAccess(), DC: Owner, |
1273 | ASLoc: D->getAccessSpecifierLoc(), ColonLoc: D->getColonLoc()); |
1274 | Owner->addHiddenDecl(D: AD); |
1275 | return AD; |
1276 | } |
1277 | |
1278 | Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { |
1279 | bool Invalid = false; |
1280 | TypeSourceInfo *DI = D->getTypeSourceInfo(); |
1281 | if (DI->getType()->isInstantiationDependentType() || |
1282 | DI->getType()->isVariablyModifiedType()) { |
1283 | DI = SemaRef.SubstType(T: DI, TemplateArgs, |
1284 | Loc: D->getLocation(), Entity: D->getDeclName()); |
1285 | if (!DI) { |
1286 | DI = D->getTypeSourceInfo(); |
1287 | Invalid = true; |
1288 | } else if (DI->getType()->isFunctionType()) { |
1289 | // C++ [temp.arg.type]p3: |
1290 | // If a declaration acquires a function type through a type |
1291 | // dependent on a template-parameter and this causes a |
1292 | // declaration that does not use the syntactic form of a |
1293 | // function declarator to have function type, the program is |
1294 | // ill-formed. |
1295 | SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_field_instantiates_to_function) |
1296 | << DI->getType(); |
1297 | Invalid = true; |
1298 | } |
1299 | } else { |
1300 | SemaRef.MarkDeclarationsReferencedInType(Loc: D->getLocation(), T: DI->getType()); |
1301 | } |
1302 | |
1303 | Expr *BitWidth = D->getBitWidth(); |
1304 | if (Invalid) |
1305 | BitWidth = nullptr; |
1306 | else if (BitWidth) { |
1307 | // The bit-width expression is a constant expression. |
1308 | EnterExpressionEvaluationContext Unevaluated( |
1309 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
1310 | |
1311 | ExprResult InstantiatedBitWidth |
1312 | = SemaRef.SubstExpr(E: BitWidth, TemplateArgs); |
1313 | if (InstantiatedBitWidth.isInvalid()) { |
1314 | Invalid = true; |
1315 | BitWidth = nullptr; |
1316 | } else |
1317 | BitWidth = InstantiatedBitWidth.getAs<Expr>(); |
1318 | } |
1319 | |
1320 | FieldDecl *Field = SemaRef.CheckFieldDecl(Name: D->getDeclName(), |
1321 | T: DI->getType(), TInfo: DI, |
1322 | Record: cast<RecordDecl>(Val: Owner), |
1323 | Loc: D->getLocation(), |
1324 | Mutable: D->isMutable(), |
1325 | BitfieldWidth: BitWidth, |
1326 | InitStyle: D->getInClassInitStyle(), |
1327 | TSSL: D->getInnerLocStart(), |
1328 | AS: D->getAccess(), |
1329 | PrevDecl: nullptr); |
1330 | if (!Field) { |
1331 | cast<Decl>(Val: Owner)->setInvalidDecl(); |
1332 | return nullptr; |
1333 | } |
1334 | |
1335 | SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: Field, LateAttrs, OuterMostScope: StartingScope); |
1336 | |
1337 | if (Field->hasAttrs()) |
1338 | SemaRef.CheckAlignasUnderalignment(D: Field); |
1339 | |
1340 | if (Invalid) |
1341 | Field->setInvalidDecl(); |
1342 | |
1343 | if (!Field->getDeclName()) { |
1344 | // Keep track of where this decl came from. |
1345 | SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Inst: Field, Tmpl: D); |
1346 | } |
1347 | if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Val: Field->getDeclContext())) { |
1348 | if (Parent->isAnonymousStructOrUnion() && |
1349 | Parent->getRedeclContext()->isFunctionOrMethod()) |
1350 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: Field); |
1351 | } |
1352 | |
1353 | Field->setImplicit(D->isImplicit()); |
1354 | Field->setAccess(D->getAccess()); |
1355 | Owner->addDecl(D: Field); |
1356 | |
1357 | return Field; |
1358 | } |
1359 | |
1360 | Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) { |
1361 | bool Invalid = false; |
1362 | TypeSourceInfo *DI = D->getTypeSourceInfo(); |
1363 | |
1364 | if (DI->getType()->isVariablyModifiedType()) { |
1365 | SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_property_is_variably_modified) |
1366 | << D; |
1367 | Invalid = true; |
1368 | } else if (DI->getType()->isInstantiationDependentType()) { |
1369 | DI = SemaRef.SubstType(T: DI, TemplateArgs, |
1370 | Loc: D->getLocation(), Entity: D->getDeclName()); |
1371 | if (!DI) { |
1372 | DI = D->getTypeSourceInfo(); |
1373 | Invalid = true; |
1374 | } else if (DI->getType()->isFunctionType()) { |
1375 | // C++ [temp.arg.type]p3: |
1376 | // If a declaration acquires a function type through a type |
1377 | // dependent on a template-parameter and this causes a |
1378 | // declaration that does not use the syntactic form of a |
1379 | // function declarator to have function type, the program is |
1380 | // ill-formed. |
1381 | SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_field_instantiates_to_function) |
1382 | << DI->getType(); |
1383 | Invalid = true; |
1384 | } |
1385 | } else { |
1386 | SemaRef.MarkDeclarationsReferencedInType(Loc: D->getLocation(), T: DI->getType()); |
1387 | } |
1388 | |
1389 | MSPropertyDecl *Property = MSPropertyDecl::Create( |
1390 | C&: SemaRef.Context, DC: Owner, L: D->getLocation(), N: D->getDeclName(), T: DI->getType(), |
1391 | TInfo: DI, StartL: D->getBeginLoc(), Getter: D->getGetterId(), Setter: D->getSetterId()); |
1392 | |
1393 | SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: Property, LateAttrs, |
1394 | OuterMostScope: StartingScope); |
1395 | |
1396 | if (Invalid) |
1397 | Property->setInvalidDecl(); |
1398 | |
1399 | Property->setAccess(D->getAccess()); |
1400 | Owner->addDecl(D: Property); |
1401 | |
1402 | return Property; |
1403 | } |
1404 | |
1405 | Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { |
1406 | NamedDecl **NamedChain = |
1407 | new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; |
1408 | |
1409 | int i = 0; |
1410 | for (auto *PI : D->chain()) { |
1411 | NamedDecl *Next = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: PI, |
1412 | TemplateArgs); |
1413 | if (!Next) |
1414 | return nullptr; |
1415 | |
1416 | NamedChain[i++] = Next; |
1417 | } |
1418 | |
1419 | QualType T = cast<FieldDecl>(Val: NamedChain[i-1])->getType(); |
1420 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( |
1421 | C&: SemaRef.Context, DC: Owner, L: D->getLocation(), Id: D->getIdentifier(), T, |
1422 | CH: {NamedChain, D->getChainingSize()}); |
1423 | |
1424 | for (const auto *Attr : D->attrs()) |
1425 | IndirectField->addAttr(A: Attr->clone(C&: SemaRef.Context)); |
1426 | |
1427 | IndirectField->setImplicit(D->isImplicit()); |
1428 | IndirectField->setAccess(D->getAccess()); |
1429 | Owner->addDecl(D: IndirectField); |
1430 | return IndirectField; |
1431 | } |
1432 | |
1433 | Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { |
1434 | // Handle friend type expressions by simply substituting template |
1435 | // parameters into the pattern type and checking the result. |
1436 | if (TypeSourceInfo *Ty = D->getFriendType()) { |
1437 | TypeSourceInfo *InstTy; |
1438 | // If this is an unsupported friend, don't bother substituting template |
1439 | // arguments into it. The actual type referred to won't be used by any |
1440 | // parts of Clang, and may not be valid for instantiating. Just use the |
1441 | // same info for the instantiated friend. |
1442 | if (D->isUnsupportedFriend()) { |
1443 | InstTy = Ty; |
1444 | } else { |
1445 | InstTy = SemaRef.SubstType(T: Ty, TemplateArgs, |
1446 | Loc: D->getLocation(), Entity: DeclarationName()); |
1447 | } |
1448 | if (!InstTy) |
1449 | return nullptr; |
1450 | |
1451 | FriendDecl *FD = FriendDecl::Create( |
1452 | C&: SemaRef.Context, DC: Owner, L: D->getLocation(), Friend_: InstTy, FriendL: D->getFriendLoc()); |
1453 | FD->setAccess(AS_public); |
1454 | FD->setUnsupportedFriend(D->isUnsupportedFriend()); |
1455 | Owner->addDecl(D: FD); |
1456 | return FD; |
1457 | } |
1458 | |
1459 | NamedDecl *ND = D->getFriendDecl(); |
1460 | assert(ND && "friend decl must be a decl or a type!" ); |
1461 | |
1462 | // All of the Visit implementations for the various potential friend |
1463 | // declarations have to be carefully written to work for friend |
1464 | // objects, with the most important detail being that the target |
1465 | // decl should almost certainly not be placed in Owner. |
1466 | Decl *NewND = Visit(D: ND); |
1467 | if (!NewND) return nullptr; |
1468 | |
1469 | FriendDecl *FD = |
1470 | FriendDecl::Create(C&: SemaRef.Context, DC: Owner, L: D->getLocation(), |
1471 | Friend_: cast<NamedDecl>(Val: NewND), FriendL: D->getFriendLoc()); |
1472 | FD->setAccess(AS_public); |
1473 | FD->setUnsupportedFriend(D->isUnsupportedFriend()); |
1474 | Owner->addDecl(D: FD); |
1475 | return FD; |
1476 | } |
1477 | |
1478 | Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { |
1479 | Expr *AssertExpr = D->getAssertExpr(); |
1480 | |
1481 | // The expression in a static assertion is a constant expression. |
1482 | EnterExpressionEvaluationContext Unevaluated( |
1483 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
1484 | |
1485 | ExprResult InstantiatedAssertExpr |
1486 | = SemaRef.SubstExpr(E: AssertExpr, TemplateArgs); |
1487 | if (InstantiatedAssertExpr.isInvalid()) |
1488 | return nullptr; |
1489 | |
1490 | ExprResult InstantiatedMessageExpr = |
1491 | SemaRef.SubstExpr(E: D->getMessage(), TemplateArgs); |
1492 | if (InstantiatedMessageExpr.isInvalid()) |
1493 | return nullptr; |
1494 | |
1495 | return SemaRef.BuildStaticAssertDeclaration( |
1496 | StaticAssertLoc: D->getLocation(), AssertExpr: InstantiatedAssertExpr.get(), |
1497 | AssertMessageExpr: InstantiatedMessageExpr.get(), RParenLoc: D->getRParenLoc(), Failed: D->isFailed()); |
1498 | } |
1499 | |
1500 | Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { |
1501 | EnumDecl *PrevDecl = nullptr; |
1502 | if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) { |
1503 | NamedDecl *Prev = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), |
1504 | D: PatternPrev, |
1505 | TemplateArgs); |
1506 | if (!Prev) return nullptr; |
1507 | PrevDecl = cast<EnumDecl>(Val: Prev); |
1508 | } |
1509 | |
1510 | EnumDecl *Enum = |
1511 | EnumDecl::Create(C&: SemaRef.Context, DC: Owner, StartLoc: D->getBeginLoc(), |
1512 | IdLoc: D->getLocation(), Id: D->getIdentifier(), PrevDecl, |
1513 | IsScoped: D->isScoped(), IsScopedUsingClassTag: D->isScopedUsingClassTag(), IsFixed: D->isFixed()); |
1514 | if (D->isFixed()) { |
1515 | if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) { |
1516 | // If we have type source information for the underlying type, it means it |
1517 | // has been explicitly set by the user. Perform substitution on it before |
1518 | // moving on. |
1519 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); |
1520 | TypeSourceInfo *NewTI = SemaRef.SubstType(T: TI, TemplateArgs, Loc: UnderlyingLoc, |
1521 | Entity: DeclarationName()); |
1522 | if (!NewTI || SemaRef.CheckEnumUnderlyingType(TI: NewTI)) |
1523 | Enum->setIntegerType(SemaRef.Context.IntTy); |
1524 | else |
1525 | Enum->setIntegerTypeSourceInfo(NewTI); |
1526 | } else { |
1527 | assert(!D->getIntegerType()->isDependentType() |
1528 | && "Dependent type without type source info" ); |
1529 | Enum->setIntegerType(D->getIntegerType()); |
1530 | } |
1531 | } |
1532 | |
1533 | SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: Enum); |
1534 | |
1535 | Enum->setInstantiationOfMemberEnum(ED: D, TSK: TSK_ImplicitInstantiation); |
1536 | Enum->setAccess(D->getAccess()); |
1537 | // Forward the mangling number from the template to the instantiated decl. |
1538 | SemaRef.Context.setManglingNumber(ND: Enum, Number: SemaRef.Context.getManglingNumber(ND: D)); |
1539 | // See if the old tag was defined along with a declarator. |
1540 | // If it did, mark the new tag as being associated with that declarator. |
1541 | if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(TD: D)) |
1542 | SemaRef.Context.addDeclaratorForUnnamedTagDecl(TD: Enum, DD); |
1543 | // See if the old tag was defined along with a typedef. |
1544 | // If it did, mark the new tag as being associated with that typedef. |
1545 | if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(TD: D)) |
1546 | SemaRef.Context.addTypedefNameForUnnamedTagDecl(TD: Enum, TND); |
1547 | if (SubstQualifier(OldDecl: D, NewDecl: Enum)) return nullptr; |
1548 | Owner->addDecl(D: Enum); |
1549 | |
1550 | EnumDecl *Def = D->getDefinition(); |
1551 | if (Def && Def != D) { |
1552 | // If this is an out-of-line definition of an enum member template, check |
1553 | // that the underlying types match in the instantiation of both |
1554 | // declarations. |
1555 | if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) { |
1556 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); |
1557 | QualType DefnUnderlying = |
1558 | SemaRef.SubstType(T: TI->getType(), TemplateArgs, |
1559 | Loc: UnderlyingLoc, Entity: DeclarationName()); |
1560 | SemaRef.CheckEnumRedeclaration(EnumLoc: Def->getLocation(), IsScoped: Def->isScoped(), |
1561 | EnumUnderlyingTy: DefnUnderlying, /*IsFixed=*/true, Prev: Enum); |
1562 | } |
1563 | } |
1564 | |
1565 | // C++11 [temp.inst]p1: The implicit instantiation of a class template |
1566 | // specialization causes the implicit instantiation of the declarations, but |
1567 | // not the definitions of scoped member enumerations. |
1568 | // |
1569 | // DR1484 clarifies that enumeration definitions inside of a template |
1570 | // declaration aren't considered entities that can be separately instantiated |
1571 | // from the rest of the entity they are declared inside of. |
1572 | if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) { |
1573 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: Enum); |
1574 | InstantiateEnumDefinition(Enum, Pattern: Def); |
1575 | } |
1576 | |
1577 | return Enum; |
1578 | } |
1579 | |
1580 | void TemplateDeclInstantiator::InstantiateEnumDefinition( |
1581 | EnumDecl *Enum, EnumDecl *Pattern) { |
1582 | Enum->startDefinition(); |
1583 | |
1584 | // Update the location to refer to the definition. |
1585 | Enum->setLocation(Pattern->getLocation()); |
1586 | |
1587 | SmallVector<Decl*, 4> Enumerators; |
1588 | |
1589 | EnumConstantDecl *LastEnumConst = nullptr; |
1590 | for (auto *EC : Pattern->enumerators()) { |
1591 | // The specified value for the enumerator. |
1592 | ExprResult Value((Expr *)nullptr); |
1593 | if (Expr *UninstValue = EC->getInitExpr()) { |
1594 | // The enumerator's value expression is a constant expression. |
1595 | EnterExpressionEvaluationContext Unevaluated( |
1596 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
1597 | |
1598 | Value = SemaRef.SubstExpr(E: UninstValue, TemplateArgs); |
1599 | } |
1600 | |
1601 | // Drop the initial value and continue. |
1602 | bool isInvalid = false; |
1603 | if (Value.isInvalid()) { |
1604 | Value = nullptr; |
1605 | isInvalid = true; |
1606 | } |
1607 | |
1608 | EnumConstantDecl *EnumConst |
1609 | = SemaRef.CheckEnumConstant(Enum, LastEnumConst, |
1610 | IdLoc: EC->getLocation(), Id: EC->getIdentifier(), |
1611 | val: Value.get()); |
1612 | |
1613 | if (isInvalid) { |
1614 | if (EnumConst) |
1615 | EnumConst->setInvalidDecl(); |
1616 | Enum->setInvalidDecl(); |
1617 | } |
1618 | |
1619 | if (EnumConst) { |
1620 | SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: EC, New: EnumConst); |
1621 | |
1622 | EnumConst->setAccess(Enum->getAccess()); |
1623 | Enum->addDecl(D: EnumConst); |
1624 | Enumerators.push_back(Elt: EnumConst); |
1625 | LastEnumConst = EnumConst; |
1626 | |
1627 | if (Pattern->getDeclContext()->isFunctionOrMethod() && |
1628 | !Enum->isScoped()) { |
1629 | // If the enumeration is within a function or method, record the enum |
1630 | // constant as a local. |
1631 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: EC, Inst: EnumConst); |
1632 | } |
1633 | } |
1634 | } |
1635 | |
1636 | SemaRef.ActOnEnumBody(EnumLoc: Enum->getLocation(), BraceRange: Enum->getBraceRange(), EnumDecl: Enum, |
1637 | Elements: Enumerators, S: nullptr, Attr: ParsedAttributesView()); |
1638 | } |
1639 | |
1640 | Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { |
1641 | llvm_unreachable("EnumConstantDecls can only occur within EnumDecls." ); |
1642 | } |
1643 | |
1644 | Decl * |
1645 | TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) { |
1646 | llvm_unreachable("BuiltinTemplateDecls cannot be instantiated." ); |
1647 | } |
1648 | |
1649 | Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { |
1650 | bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); |
1651 | |
1652 | // Create a local instantiation scope for this class template, which |
1653 | // will contain the instantiations of the template parameters. |
1654 | LocalInstantiationScope Scope(SemaRef); |
1655 | TemplateParameterList *TempParams = D->getTemplateParameters(); |
1656 | TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams); |
1657 | if (!InstParams) |
1658 | return nullptr; |
1659 | |
1660 | CXXRecordDecl *Pattern = D->getTemplatedDecl(); |
1661 | |
1662 | // Instantiate the qualifier. We have to do this first in case |
1663 | // we're a friend declaration, because if we are then we need to put |
1664 | // the new declaration in the appropriate context. |
1665 | NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); |
1666 | if (QualifierLoc) { |
1667 | QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, |
1668 | TemplateArgs); |
1669 | if (!QualifierLoc) |
1670 | return nullptr; |
1671 | } |
1672 | |
1673 | CXXRecordDecl *PrevDecl = nullptr; |
1674 | ClassTemplateDecl *PrevClassTemplate = nullptr; |
1675 | |
1676 | if (!isFriend && getPreviousDeclForInstantiation(D: Pattern)) { |
1677 | DeclContext::lookup_result Found = Owner->lookup(Name: Pattern->getDeclName()); |
1678 | if (!Found.empty()) { |
1679 | PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Val: Found.front()); |
1680 | if (PrevClassTemplate) |
1681 | PrevDecl = PrevClassTemplate->getTemplatedDecl(); |
1682 | } |
1683 | } |
1684 | |
1685 | // If this isn't a friend, then it's a member template, in which |
1686 | // case we just want to build the instantiation in the |
1687 | // specialization. If it is a friend, we want to build it in |
1688 | // the appropriate context. |
1689 | DeclContext *DC = Owner; |
1690 | if (isFriend) { |
1691 | if (QualifierLoc) { |
1692 | CXXScopeSpec SS; |
1693 | SS.Adopt(Other: QualifierLoc); |
1694 | DC = SemaRef.computeDeclContext(SS); |
1695 | if (!DC) return nullptr; |
1696 | } else { |
1697 | DC = SemaRef.FindInstantiatedContext(Loc: Pattern->getLocation(), |
1698 | DC: Pattern->getDeclContext(), |
1699 | TemplateArgs); |
1700 | } |
1701 | |
1702 | // Look for a previous declaration of the template in the owning |
1703 | // context. |
1704 | LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), |
1705 | Sema::LookupOrdinaryName, |
1706 | SemaRef.forRedeclarationInCurContext()); |
1707 | SemaRef.LookupQualifiedName(R, LookupCtx: DC); |
1708 | |
1709 | if (R.isSingleResult()) { |
1710 | PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); |
1711 | if (PrevClassTemplate) |
1712 | PrevDecl = PrevClassTemplate->getTemplatedDecl(); |
1713 | } |
1714 | |
1715 | if (!PrevClassTemplate && QualifierLoc) { |
1716 | SemaRef.Diag(Loc: Pattern->getLocation(), DiagID: diag::err_not_tag_in_scope) |
1717 | << llvm::to_underlying(E: D->getTemplatedDecl()->getTagKind()) |
1718 | << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange(); |
1719 | return nullptr; |
1720 | } |
1721 | } |
1722 | |
1723 | CXXRecordDecl *RecordInst = CXXRecordDecl::Create( |
1724 | C: SemaRef.Context, TK: Pattern->getTagKind(), DC, StartLoc: Pattern->getBeginLoc(), |
1725 | IdLoc: Pattern->getLocation(), Id: Pattern->getIdentifier(), PrevDecl, |
1726 | /*DelayTypeCreation=*/true); |
1727 | if (QualifierLoc) |
1728 | RecordInst->setQualifierInfo(QualifierLoc); |
1729 | |
1730 | SemaRef.InstantiateAttrsForDecl(TemplateArgs, Tmpl: Pattern, New: RecordInst, LateAttrs, |
1731 | OuterMostScope: StartingScope); |
1732 | |
1733 | ClassTemplateDecl *Inst |
1734 | = ClassTemplateDecl::Create(C&: SemaRef.Context, DC, L: D->getLocation(), |
1735 | Name: D->getIdentifier(), Params: InstParams, Decl: RecordInst); |
1736 | RecordInst->setDescribedClassTemplate(Inst); |
1737 | |
1738 | if (isFriend) { |
1739 | assert(!Owner->isDependentContext()); |
1740 | Inst->setLexicalDeclContext(Owner); |
1741 | RecordInst->setLexicalDeclContext(Owner); |
1742 | Inst->setObjectOfFriendDecl(); |
1743 | |
1744 | if (PrevClassTemplate) { |
1745 | Inst->setCommonPtr(PrevClassTemplate->getCommonPtr()); |
1746 | RecordInst->setTypeForDecl( |
1747 | PrevClassTemplate->getTemplatedDecl()->getTypeForDecl()); |
1748 | const ClassTemplateDecl *MostRecentPrevCT = |
1749 | PrevClassTemplate->getMostRecentDecl(); |
1750 | TemplateParameterList *PrevParams = |
1751 | MostRecentPrevCT->getTemplateParameters(); |
1752 | |
1753 | // Make sure the parameter lists match. |
1754 | if (!SemaRef.TemplateParameterListsAreEqual( |
1755 | NewInstFrom: RecordInst, New: InstParams, OldInstFrom: MostRecentPrevCT->getTemplatedDecl(), |
1756 | Old: PrevParams, Complain: true, Kind: Sema::TPL_TemplateMatch)) |
1757 | return nullptr; |
1758 | |
1759 | // Do some additional validation, then merge default arguments |
1760 | // from the existing declarations. |
1761 | if (SemaRef.CheckTemplateParameterList(NewParams: InstParams, OldParams: PrevParams, |
1762 | TPC: Sema::TPC_ClassTemplate)) |
1763 | return nullptr; |
1764 | |
1765 | Inst->setAccess(PrevClassTemplate->getAccess()); |
1766 | } else { |
1767 | Inst->setAccess(D->getAccess()); |
1768 | } |
1769 | |
1770 | Inst->setObjectOfFriendDecl(); |
1771 | // TODO: do we want to track the instantiation progeny of this |
1772 | // friend target decl? |
1773 | } else { |
1774 | Inst->setAccess(D->getAccess()); |
1775 | if (!PrevClassTemplate) |
1776 | Inst->setInstantiatedFromMemberTemplate(D); |
1777 | } |
1778 | |
1779 | Inst->setPreviousDecl(PrevClassTemplate); |
1780 | |
1781 | // Trigger creation of the type for the instantiation. |
1782 | SemaRef.Context.getInjectedClassNameType( |
1783 | Decl: RecordInst, TST: Inst->getInjectedClassNameSpecialization()); |
1784 | |
1785 | // Finish handling of friends. |
1786 | if (isFriend) { |
1787 | DC->makeDeclVisibleInContext(D: Inst); |
1788 | return Inst; |
1789 | } |
1790 | |
1791 | if (D->isOutOfLine()) { |
1792 | Inst->setLexicalDeclContext(D->getLexicalDeclContext()); |
1793 | RecordInst->setLexicalDeclContext(D->getLexicalDeclContext()); |
1794 | } |
1795 | |
1796 | Owner->addDecl(D: Inst); |
1797 | |
1798 | if (!PrevClassTemplate) { |
1799 | // Queue up any out-of-line partial specializations of this member |
1800 | // class template; the client will force their instantiation once |
1801 | // the enclosing class has been instantiated. |
1802 | SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
1803 | D->getPartialSpecializations(PS&: PartialSpecs); |
1804 | for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) |
1805 | if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) |
1806 | OutOfLinePartialSpecs.push_back(Elt: std::make_pair(x&: Inst, y&: PartialSpecs[I])); |
1807 | } |
1808 | |
1809 | return Inst; |
1810 | } |
1811 | |
1812 | Decl * |
1813 | TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( |
1814 | ClassTemplatePartialSpecializationDecl *D) { |
1815 | ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); |
1816 | |
1817 | // Lookup the already-instantiated declaration in the instantiation |
1818 | // of the class template and return that. |
1819 | DeclContext::lookup_result Found |
1820 | = Owner->lookup(Name: ClassTemplate->getDeclName()); |
1821 | if (Found.empty()) |
1822 | return nullptr; |
1823 | |
1824 | ClassTemplateDecl *InstClassTemplate |
1825 | = dyn_cast<ClassTemplateDecl>(Val: Found.front()); |
1826 | if (!InstClassTemplate) |
1827 | return nullptr; |
1828 | |
1829 | if (ClassTemplatePartialSpecializationDecl *Result |
1830 | = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) |
1831 | return Result; |
1832 | |
1833 | return InstantiateClassTemplatePartialSpecialization(ClassTemplate: InstClassTemplate, PartialSpec: D); |
1834 | } |
1835 | |
1836 | Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) { |
1837 | assert(D->getTemplatedDecl()->isStaticDataMember() && |
1838 | "Only static data member templates are allowed." ); |
1839 | |
1840 | // Create a local instantiation scope for this variable template, which |
1841 | // will contain the instantiations of the template parameters. |
1842 | LocalInstantiationScope Scope(SemaRef); |
1843 | TemplateParameterList *TempParams = D->getTemplateParameters(); |
1844 | TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams); |
1845 | if (!InstParams) |
1846 | return nullptr; |
1847 | |
1848 | VarDecl *Pattern = D->getTemplatedDecl(); |
1849 | VarTemplateDecl *PrevVarTemplate = nullptr; |
1850 | |
1851 | if (getPreviousDeclForInstantiation(D: Pattern)) { |
1852 | DeclContext::lookup_result Found = Owner->lookup(Name: Pattern->getDeclName()); |
1853 | if (!Found.empty()) |
1854 | PrevVarTemplate = dyn_cast<VarTemplateDecl>(Val: Found.front()); |
1855 | } |
1856 | |
1857 | VarDecl *VarInst = |
1858 | cast_or_null<VarDecl>(Val: VisitVarDecl(D: Pattern, |
1859 | /*InstantiatingVarTemplate=*/true)); |
1860 | if (!VarInst) return nullptr; |
1861 | |
1862 | DeclContext *DC = Owner; |
1863 | |
1864 | VarTemplateDecl *Inst = VarTemplateDecl::Create( |
1865 | C&: SemaRef.Context, DC, L: D->getLocation(), Name: D->getIdentifier(), Params: InstParams, |
1866 | Decl: VarInst); |
1867 | VarInst->setDescribedVarTemplate(Inst); |
1868 | Inst->setPreviousDecl(PrevVarTemplate); |
1869 | |
1870 | Inst->setAccess(D->getAccess()); |
1871 | if (!PrevVarTemplate) |
1872 | Inst->setInstantiatedFromMemberTemplate(D); |
1873 | |
1874 | if (D->isOutOfLine()) { |
1875 | Inst->setLexicalDeclContext(D->getLexicalDeclContext()); |
1876 | VarInst->setLexicalDeclContext(D->getLexicalDeclContext()); |
1877 | } |
1878 | |
1879 | Owner->addDecl(D: Inst); |
1880 | |
1881 | if (!PrevVarTemplate) { |
1882 | // Queue up any out-of-line partial specializations of this member |
1883 | // variable template; the client will force their instantiation once |
1884 | // the enclosing class has been instantiated. |
1885 | SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
1886 | D->getPartialSpecializations(PS&: PartialSpecs); |
1887 | for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) |
1888 | if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) |
1889 | OutOfLineVarPartialSpecs.push_back( |
1890 | Elt: std::make_pair(x&: Inst, y&: PartialSpecs[I])); |
1891 | } |
1892 | |
1893 | return Inst; |
1894 | } |
1895 | |
1896 | Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl( |
1897 | VarTemplatePartialSpecializationDecl *D) { |
1898 | assert(D->isStaticDataMember() && |
1899 | "Only static data member templates are allowed." ); |
1900 | |
1901 | VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); |
1902 | |
1903 | // Lookup the already-instantiated declaration and return that. |
1904 | DeclContext::lookup_result Found = Owner->lookup(Name: VarTemplate->getDeclName()); |
1905 | assert(!Found.empty() && "Instantiation found nothing?" ); |
1906 | |
1907 | VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Val: Found.front()); |
1908 | assert(InstVarTemplate && "Instantiation did not find a variable template?" ); |
1909 | |
1910 | if (VarTemplatePartialSpecializationDecl *Result = |
1911 | InstVarTemplate->findPartialSpecInstantiatedFromMember(D)) |
1912 | return Result; |
1913 | |
1914 | return InstantiateVarTemplatePartialSpecialization(VarTemplate: InstVarTemplate, PartialSpec: D); |
1915 | } |
1916 | |
1917 | Decl * |
1918 | TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { |
1919 | // Create a local instantiation scope for this function template, which |
1920 | // will contain the instantiations of the template parameters and then get |
1921 | // merged with the local instantiation scope for the function template |
1922 | // itself. |
1923 | LocalInstantiationScope Scope(SemaRef); |
1924 | Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this); |
1925 | |
1926 | TemplateParameterList *TempParams = D->getTemplateParameters(); |
1927 | TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams); |
1928 | if (!InstParams) |
1929 | return nullptr; |
1930 | |
1931 | FunctionDecl *Instantiated = nullptr; |
1932 | if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(Val: D->getTemplatedDecl())) |
1933 | Instantiated = cast_or_null<FunctionDecl>(Val: VisitCXXMethodDecl(D: DMethod, |
1934 | TemplateParams: InstParams)); |
1935 | else |
1936 | Instantiated = cast_or_null<FunctionDecl>(Val: VisitFunctionDecl( |
1937 | D: D->getTemplatedDecl(), |
1938 | TemplateParams: InstParams)); |
1939 | |
1940 | if (!Instantiated) |
1941 | return nullptr; |
1942 | |
1943 | // Link the instantiated function template declaration to the function |
1944 | // template from which it was instantiated. |
1945 | FunctionTemplateDecl *InstTemplate |
1946 | = Instantiated->getDescribedFunctionTemplate(); |
1947 | InstTemplate->setAccess(D->getAccess()); |
1948 | assert(InstTemplate && |
1949 | "VisitFunctionDecl/CXXMethodDecl didn't create a template!" ); |
1950 | |
1951 | bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); |
1952 | |
1953 | // Link the instantiation back to the pattern *unless* this is a |
1954 | // non-definition friend declaration. |
1955 | if (!InstTemplate->getInstantiatedFromMemberTemplate() && |
1956 | !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) |
1957 | InstTemplate->setInstantiatedFromMemberTemplate(D); |
1958 | |
1959 | // Make declarations visible in the appropriate context. |
1960 | if (!isFriend) { |
1961 | Owner->addDecl(D: InstTemplate); |
1962 | } else if (InstTemplate->getDeclContext()->isRecord() && |
1963 | !getPreviousDeclForInstantiation(D)) { |
1964 | SemaRef.CheckFriendAccess(D: InstTemplate); |
1965 | } |
1966 | |
1967 | return InstTemplate; |
1968 | } |
1969 | |
1970 | Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { |
1971 | CXXRecordDecl *PrevDecl = nullptr; |
1972 | if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) { |
1973 | NamedDecl *Prev = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), |
1974 | D: PatternPrev, |
1975 | TemplateArgs); |
1976 | if (!Prev) return nullptr; |
1977 | PrevDecl = cast<CXXRecordDecl>(Val: Prev); |
1978 | } |
1979 | |
1980 | CXXRecordDecl *Record = nullptr; |
1981 | bool IsInjectedClassName = D->isInjectedClassName(); |
1982 | if (D->isLambda()) |
1983 | Record = CXXRecordDecl::CreateLambda( |
1984 | C: SemaRef.Context, DC: Owner, Info: D->getLambdaTypeInfo(), Loc: D->getLocation(), |
1985 | DependencyKind: D->getLambdaDependencyKind(), IsGeneric: D->isGenericLambda(), |
1986 | CaptureDefault: D->getLambdaCaptureDefault()); |
1987 | else |
1988 | Record = CXXRecordDecl::Create(C: SemaRef.Context, TK: D->getTagKind(), DC: Owner, |
1989 | StartLoc: D->getBeginLoc(), IdLoc: D->getLocation(), |
1990 | Id: D->getIdentifier(), PrevDecl, |
1991 | /*DelayTypeCreation=*/IsInjectedClassName); |
1992 | // Link the type of the injected-class-name to that of the outer class. |
1993 | if (IsInjectedClassName) |
1994 | (void)SemaRef.Context.getTypeDeclType(Decl: Record, PrevDecl: cast<CXXRecordDecl>(Val: Owner)); |
1995 | |
1996 | // Substitute the nested name specifier, if any. |
1997 | if (SubstQualifier(OldDecl: D, NewDecl: Record)) |
1998 | return nullptr; |
1999 | |
2000 | SemaRef.InstantiateAttrsForDecl(TemplateArgs, Tmpl: D, New: Record, LateAttrs, |
2001 | OuterMostScope: StartingScope); |
2002 | |
2003 | Record->setImplicit(D->isImplicit()); |
2004 | // FIXME: Check against AS_none is an ugly hack to work around the issue that |
2005 | // the tag decls introduced by friend class declarations don't have an access |
2006 | // specifier. Remove once this area of the code gets sorted out. |
2007 | if (D->getAccess() != AS_none) |
2008 | Record->setAccess(D->getAccess()); |
2009 | if (!IsInjectedClassName) |
2010 | Record->setInstantiationOfMemberClass(RD: D, TSK: TSK_ImplicitInstantiation); |
2011 | |
2012 | // If the original function was part of a friend declaration, |
2013 | // inherit its namespace state. |
2014 | if (D->getFriendObjectKind()) |
2015 | Record->setObjectOfFriendDecl(); |
2016 | |
2017 | // Make sure that anonymous structs and unions are recorded. |
2018 | if (D->isAnonymousStructOrUnion()) |
2019 | Record->setAnonymousStructOrUnion(true); |
2020 | |
2021 | if (D->isLocalClass()) |
2022 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: Record); |
2023 | |
2024 | // Forward the mangling number from the template to the instantiated decl. |
2025 | SemaRef.Context.setManglingNumber(ND: Record, |
2026 | Number: SemaRef.Context.getManglingNumber(ND: D)); |
2027 | |
2028 | // See if the old tag was defined along with a declarator. |
2029 | // If it did, mark the new tag as being associated with that declarator. |
2030 | if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(TD: D)) |
2031 | SemaRef.Context.addDeclaratorForUnnamedTagDecl(TD: Record, DD); |
2032 | |
2033 | // See if the old tag was defined along with a typedef. |
2034 | // If it did, mark the new tag as being associated with that typedef. |
2035 | if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(TD: D)) |
2036 | SemaRef.Context.addTypedefNameForUnnamedTagDecl(TD: Record, TND); |
2037 | |
2038 | Owner->addDecl(D: Record); |
2039 | |
2040 | // DR1484 clarifies that the members of a local class are instantiated as part |
2041 | // of the instantiation of their enclosing entity. |
2042 | if (D->isCompleteDefinition() && D->isLocalClass()) { |
2043 | Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef); |
2044 | |
2045 | SemaRef.InstantiateClass(PointOfInstantiation: D->getLocation(), Instantiation: Record, Pattern: D, TemplateArgs, |
2046 | TSK: TSK_ImplicitInstantiation, |
2047 | /*Complain=*/true); |
2048 | |
2049 | // For nested local classes, we will instantiate the members when we |
2050 | // reach the end of the outermost (non-nested) local class. |
2051 | if (!D->isCXXClassMember()) |
2052 | SemaRef.InstantiateClassMembers(PointOfInstantiation: D->getLocation(), Instantiation: Record, TemplateArgs, |
2053 | TSK: TSK_ImplicitInstantiation); |
2054 | |
2055 | // This class may have local implicit instantiations that need to be |
2056 | // performed within this scope. |
2057 | LocalInstantiations.perform(); |
2058 | } |
2059 | |
2060 | SemaRef.DiagnoseUnusedNestedTypedefs(D: Record); |
2061 | |
2062 | if (IsInjectedClassName) |
2063 | assert(Record->isInjectedClassName() && "Broken injected-class-name" ); |
2064 | |
2065 | return Record; |
2066 | } |
2067 | |
2068 | /// Adjust the given function type for an instantiation of the |
2069 | /// given declaration, to cope with modifications to the function's type that |
2070 | /// aren't reflected in the type-source information. |
2071 | /// |
2072 | /// \param D The declaration we're instantiating. |
2073 | /// \param TInfo The already-instantiated type. |
2074 | static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, |
2075 | FunctionDecl *D, |
2076 | TypeSourceInfo *TInfo) { |
2077 | const FunctionProtoType *OrigFunc |
2078 | = D->getType()->castAs<FunctionProtoType>(); |
2079 | const FunctionProtoType *NewFunc |
2080 | = TInfo->getType()->castAs<FunctionProtoType>(); |
2081 | if (OrigFunc->getExtInfo() == NewFunc->getExtInfo()) |
2082 | return TInfo->getType(); |
2083 | |
2084 | FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo(); |
2085 | NewEPI.ExtInfo = OrigFunc->getExtInfo(); |
2086 | return Context.getFunctionType(ResultTy: NewFunc->getReturnType(), |
2087 | Args: NewFunc->getParamTypes(), EPI: NewEPI); |
2088 | } |
2089 | |
2090 | /// Normal class members are of more specific types and therefore |
2091 | /// don't make it here. This function serves three purposes: |
2092 | /// 1) instantiating function templates |
2093 | /// 2) substituting friend and local function declarations |
2094 | /// 3) substituting deduction guide declarations for nested class templates |
2095 | Decl *TemplateDeclInstantiator::VisitFunctionDecl( |
2096 | FunctionDecl *D, TemplateParameterList *TemplateParams, |
2097 | RewriteKind FunctionRewriteKind) { |
2098 | // Check whether there is already a function template specialization for |
2099 | // this declaration. |
2100 | FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); |
2101 | if (FunctionTemplate && !TemplateParams) { |
2102 | ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); |
2103 | |
2104 | void *InsertPos = nullptr; |
2105 | FunctionDecl *SpecFunc |
2106 | = FunctionTemplate->findSpecialization(Args: Innermost, InsertPos); |
2107 | |
2108 | // If we already have a function template specialization, return it. |
2109 | if (SpecFunc) |
2110 | return SpecFunc; |
2111 | } |
2112 | |
2113 | bool isFriend; |
2114 | if (FunctionTemplate) |
2115 | isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); |
2116 | else |
2117 | isFriend = (D->getFriendObjectKind() != Decl::FOK_None); |
2118 | |
2119 | bool MergeWithParentScope = (TemplateParams != nullptr) || |
2120 | Owner->isFunctionOrMethod() || |
2121 | !(isa<Decl>(Val: Owner) && |
2122 | cast<Decl>(Val: Owner)->isDefinedOutsideFunctionOrMethod()); |
2123 | LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); |
2124 | |
2125 | ExplicitSpecifier InstantiatedExplicitSpecifier; |
2126 | if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(Val: D)) { |
2127 | InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier( |
2128 | TemplateArgs, ES: DGuide->getExplicitSpecifier()); |
2129 | if (InstantiatedExplicitSpecifier.isInvalid()) |
2130 | return nullptr; |
2131 | } |
2132 | |
2133 | SmallVector<ParmVarDecl *, 4> Params; |
2134 | TypeSourceInfo *TInfo = SubstFunctionType(D, Params); |
2135 | if (!TInfo) |
2136 | return nullptr; |
2137 | QualType T = adjustFunctionTypeForInstantiation(Context&: SemaRef.Context, D, TInfo); |
2138 | |
2139 | if (TemplateParams && TemplateParams->size()) { |
2140 | auto *LastParam = |
2141 | dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->asArray().back()); |
2142 | if (LastParam && LastParam->isImplicit() && |
2143 | LastParam->hasTypeConstraint()) { |
2144 | // In abbreviated templates, the type-constraints of invented template |
2145 | // type parameters are instantiated with the function type, invalidating |
2146 | // the TemplateParameterList which relied on the template type parameter |
2147 | // not having a type constraint. Recreate the TemplateParameterList with |
2148 | // the updated parameter list. |
2149 | TemplateParams = TemplateParameterList::Create( |
2150 | C: SemaRef.Context, TemplateLoc: TemplateParams->getTemplateLoc(), |
2151 | LAngleLoc: TemplateParams->getLAngleLoc(), Params: TemplateParams->asArray(), |
2152 | RAngleLoc: TemplateParams->getRAngleLoc(), RequiresClause: TemplateParams->getRequiresClause()); |
2153 | } |
2154 | } |
2155 | |
2156 | NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); |
2157 | if (QualifierLoc) { |
2158 | QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, |
2159 | TemplateArgs); |
2160 | if (!QualifierLoc) |
2161 | return nullptr; |
2162 | } |
2163 | |
2164 | Expr *TrailingRequiresClause = D->getTrailingRequiresClause(); |
2165 | |
2166 | // If we're instantiating a local function declaration, put the result |
2167 | // in the enclosing namespace; otherwise we need to find the instantiated |
2168 | // context. |
2169 | DeclContext *DC; |
2170 | if (D->isLocalExternDecl()) { |
2171 | DC = Owner; |
2172 | SemaRef.adjustContextForLocalExternDecl(DC); |
2173 | } else if (isFriend && QualifierLoc) { |
2174 | CXXScopeSpec SS; |
2175 | SS.Adopt(Other: QualifierLoc); |
2176 | DC = SemaRef.computeDeclContext(SS); |
2177 | if (!DC) return nullptr; |
2178 | } else { |
2179 | DC = SemaRef.FindInstantiatedContext(Loc: D->getLocation(), DC: D->getDeclContext(), |
2180 | TemplateArgs); |
2181 | } |
2182 | |
2183 | DeclarationNameInfo NameInfo |
2184 | = SemaRef.SubstDeclarationNameInfo(NameInfo: D->getNameInfo(), TemplateArgs); |
2185 | |
2186 | if (FunctionRewriteKind != RewriteKind::None) |
2187 | adjustForRewrite(RK: FunctionRewriteKind, Orig: D, T, TInfo, NameInfo); |
2188 | |
2189 | FunctionDecl *Function; |
2190 | if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(Val: D)) { |
2191 | Function = CXXDeductionGuideDecl::Create( |
2192 | C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(), |
2193 | ES: InstantiatedExplicitSpecifier, NameInfo, T, TInfo, |
2194 | EndLocation: D->getSourceRange().getEnd(), Ctor: DGuide->getCorrespondingConstructor(), |
2195 | Kind: DGuide->getDeductionCandidateKind()); |
2196 | Function->setAccess(D->getAccess()); |
2197 | } else { |
2198 | Function = FunctionDecl::Create( |
2199 | C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(), NameInfo, T, TInfo, |
2200 | SC: D->getCanonicalDecl()->getStorageClass(), UsesFPIntrin: D->UsesFPIntrin(), |
2201 | isInlineSpecified: D->isInlineSpecified(), hasWrittenPrototype: D->hasWrittenPrototype(), ConstexprKind: D->getConstexprKind(), |
2202 | TrailingRequiresClause); |
2203 | Function->setFriendConstraintRefersToEnclosingTemplate( |
2204 | D->FriendConstraintRefersToEnclosingTemplate()); |
2205 | Function->setRangeEnd(D->getSourceRange().getEnd()); |
2206 | } |
2207 | |
2208 | if (D->isInlined()) |
2209 | Function->setImplicitlyInline(); |
2210 | |
2211 | if (QualifierLoc) |
2212 | Function->setQualifierInfo(QualifierLoc); |
2213 | |
2214 | if (D->isLocalExternDecl()) |
2215 | Function->setLocalExternDecl(); |
2216 | |
2217 | DeclContext *LexicalDC = Owner; |
2218 | if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) { |
2219 | assert(D->getDeclContext()->isFileContext()); |
2220 | LexicalDC = D->getDeclContext(); |
2221 | } |
2222 | else if (D->isLocalExternDecl()) { |
2223 | LexicalDC = SemaRef.CurContext; |
2224 | } |
2225 | |
2226 | Function->setLexicalDeclContext(LexicalDC); |
2227 | |
2228 | // Attach the parameters |
2229 | for (unsigned P = 0; P < Params.size(); ++P) |
2230 | if (Params[P]) |
2231 | Params[P]->setOwningFunction(Function); |
2232 | Function->setParams(Params); |
2233 | |
2234 | if (TrailingRequiresClause) |
2235 | Function->setTrailingRequiresClause(TrailingRequiresClause); |
2236 | |
2237 | if (TemplateParams) { |
2238 | // Our resulting instantiation is actually a function template, since we |
2239 | // are substituting only the outer template parameters. For example, given |
2240 | // |
2241 | // template<typename T> |
2242 | // struct X { |
2243 | // template<typename U> friend void f(T, U); |
2244 | // }; |
2245 | // |
2246 | // X<int> x; |
2247 | // |
2248 | // We are instantiating the friend function template "f" within X<int>, |
2249 | // which means substituting int for T, but leaving "f" as a friend function |
2250 | // template. |
2251 | // Build the function template itself. |
2252 | FunctionTemplate = FunctionTemplateDecl::Create(C&: SemaRef.Context, DC, |
2253 | L: Function->getLocation(), |
2254 | Name: Function->getDeclName(), |
2255 | Params: TemplateParams, Decl: Function); |
2256 | Function->setDescribedFunctionTemplate(FunctionTemplate); |
2257 | |
2258 | FunctionTemplate->setLexicalDeclContext(LexicalDC); |
2259 | |
2260 | if (isFriend && D->isThisDeclarationADefinition()) { |
2261 | FunctionTemplate->setInstantiatedFromMemberTemplate( |
2262 | D->getDescribedFunctionTemplate()); |
2263 | } |
2264 | } else if (FunctionTemplate && |
2265 | SemaRef.CodeSynthesisContexts.back().Kind != |
2266 | Sema::CodeSynthesisContext::BuildingDeductionGuides) { |
2267 | // Record this function template specialization. |
2268 | ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); |
2269 | Function->setFunctionTemplateSpecialization(Template: FunctionTemplate, |
2270 | TemplateArgs: TemplateArgumentList::CreateCopy(Context&: SemaRef.Context, |
2271 | Args: Innermost), |
2272 | /*InsertPos=*/nullptr); |
2273 | } else if (FunctionRewriteKind == RewriteKind::None) { |
2274 | if (isFriend && D->isThisDeclarationADefinition()) { |
2275 | // Do not connect the friend to the template unless it's actually a |
2276 | // definition. We don't want non-template functions to be marked as being |
2277 | // template instantiations. |
2278 | Function->setInstantiationOfMemberFunction(FD: D, TSK: TSK_ImplicitInstantiation); |
2279 | } else if (!isFriend) { |
2280 | // If this is not a function template, and this is not a friend (that is, |
2281 | // this is a locally declared function), save the instantiation |
2282 | // relationship for the purposes of constraint instantiation. |
2283 | Function->setInstantiatedFromDecl(D); |
2284 | } |
2285 | } |
2286 | |
2287 | if (isFriend) { |
2288 | Function->setObjectOfFriendDecl(); |
2289 | if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate()) |
2290 | FT->setObjectOfFriendDecl(); |
2291 | } |
2292 | |
2293 | if (InitFunctionInstantiation(New: Function, Tmpl: D)) |
2294 | Function->setInvalidDecl(); |
2295 | |
2296 | bool IsExplicitSpecialization = false; |
2297 | |
2298 | LookupResult Previous( |
2299 | SemaRef, Function->getDeclName(), SourceLocation(), |
2300 | D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage |
2301 | : Sema::LookupOrdinaryName, |
2302 | D->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration |
2303 | : SemaRef.forRedeclarationInCurContext()); |
2304 | |
2305 | if (DependentFunctionTemplateSpecializationInfo *DFTSI = |
2306 | D->getDependentSpecializationInfo()) { |
2307 | assert(isFriend && "dependent specialization info on " |
2308 | "non-member non-friend function?" ); |
2309 | |
2310 | // Instantiate the explicit template arguments. |
2311 | TemplateArgumentListInfo ExplicitArgs; |
2312 | if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) { |
2313 | ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc()); |
2314 | ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc()); |
2315 | if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs, |
2316 | Outputs&: ExplicitArgs)) |
2317 | return nullptr; |
2318 | } |
2319 | |
2320 | // Map the candidates for the primary template to their instantiations. |
2321 | for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) { |
2322 | if (NamedDecl *ND = |
2323 | SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: FTD, TemplateArgs)) |
2324 | Previous.addDecl(D: ND); |
2325 | else |
2326 | return nullptr; |
2327 | } |
2328 | |
2329 | if (SemaRef.CheckFunctionTemplateSpecialization( |
2330 | FD: Function, |
2331 | ExplicitTemplateArgs: DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr, |
2332 | Previous)) |
2333 | Function->setInvalidDecl(); |
2334 | |
2335 | IsExplicitSpecialization = true; |
2336 | } else if (const ASTTemplateArgumentListInfo *ArgsWritten = |
2337 | D->getTemplateSpecializationArgsAsWritten()) { |
2338 | // The name of this function was written as a template-id. |
2339 | SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: DC); |
2340 | |
2341 | // Instantiate the explicit template arguments. |
2342 | TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(), |
2343 | ArgsWritten->getRAngleLoc()); |
2344 | if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs, |
2345 | Outputs&: ExplicitArgs)) |
2346 | return nullptr; |
2347 | |
2348 | if (SemaRef.CheckFunctionTemplateSpecialization(FD: Function, |
2349 | ExplicitTemplateArgs: &ExplicitArgs, |
2350 | Previous)) |
2351 | Function->setInvalidDecl(); |
2352 | |
2353 | IsExplicitSpecialization = true; |
2354 | } else if (TemplateParams || !FunctionTemplate) { |
2355 | // Look only into the namespace where the friend would be declared to |
2356 | // find a previous declaration. This is the innermost enclosing namespace, |
2357 | // as described in ActOnFriendFunctionDecl. |
2358 | SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: DC->getRedeclContext()); |
2359 | |
2360 | // In C++, the previous declaration we find might be a tag type |
2361 | // (class or enum). In this case, the new declaration will hide the |
2362 | // tag type. Note that this does not apply if we're declaring a |
2363 | // typedef (C++ [dcl.typedef]p4). |
2364 | if (Previous.isSingleTagDecl()) |
2365 | Previous.clear(); |
2366 | |
2367 | // Filter out previous declarations that don't match the scope. The only |
2368 | // effect this has is to remove declarations found in inline namespaces |
2369 | // for friend declarations with unqualified names. |
2370 | if (isFriend && !QualifierLoc) { |
2371 | SemaRef.FilterLookupForScope(R&: Previous, Ctx: DC, /*Scope=*/ S: nullptr, |
2372 | /*ConsiderLinkage=*/ true, |
2373 | AllowInlineNamespace: QualifierLoc.hasQualifier()); |
2374 | } |
2375 | } |
2376 | |
2377 | // Per [temp.inst], default arguments in function declarations at local scope |
2378 | // are instantiated along with the enclosing declaration. For example: |
2379 | // |
2380 | // template<typename T> |
2381 | // void ft() { |
2382 | // void f(int = []{ return T::value; }()); |
2383 | // } |
2384 | // template void ft<int>(); // error: type 'int' cannot be used prior |
2385 | // to '::' because it has no members |
2386 | // |
2387 | // The error is issued during instantiation of ft<int>() because substitution |
2388 | // into the default argument fails; the default argument is instantiated even |
2389 | // though it is never used. |
2390 | if (Function->isLocalExternDecl()) { |
2391 | for (ParmVarDecl *PVD : Function->parameters()) { |
2392 | if (!PVD->hasDefaultArg()) |
2393 | continue; |
2394 | if (SemaRef.SubstDefaultArgument(Loc: D->getInnerLocStart(), Param: PVD, TemplateArgs)) { |
2395 | // If substitution fails, the default argument is set to a |
2396 | // RecoveryExpr that wraps the uninstantiated default argument so |
2397 | // that downstream diagnostics are omitted. |
2398 | Expr *UninstExpr = PVD->getUninstantiatedDefaultArg(); |
2399 | ExprResult ErrorResult = SemaRef.CreateRecoveryExpr( |
2400 | Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(), |
2401 | SubExprs: { UninstExpr }, T: UninstExpr->getType()); |
2402 | if (ErrorResult.isUsable()) |
2403 | PVD->setDefaultArg(ErrorResult.get()); |
2404 | } |
2405 | } |
2406 | } |
2407 | |
2408 | SemaRef.CheckFunctionDeclaration(/*Scope*/ S: nullptr, NewFD: Function, Previous, |
2409 | IsMemberSpecialization: IsExplicitSpecialization, |
2410 | DeclIsDefn: Function->isThisDeclarationADefinition()); |
2411 | |
2412 | // Check the template parameter list against the previous declaration. The |
2413 | // goal here is to pick up default arguments added since the friend was |
2414 | // declared; we know the template parameter lists match, since otherwise |
2415 | // we would not have picked this template as the previous declaration. |
2416 | if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) { |
2417 | SemaRef.CheckTemplateParameterList( |
2418 | NewParams: TemplateParams, |
2419 | OldParams: FunctionTemplate->getPreviousDecl()->getTemplateParameters(), |
2420 | TPC: Function->isThisDeclarationADefinition() |
2421 | ? Sema::TPC_FriendFunctionTemplateDefinition |
2422 | : Sema::TPC_FriendFunctionTemplate); |
2423 | } |
2424 | |
2425 | // If we're introducing a friend definition after the first use, trigger |
2426 | // instantiation. |
2427 | // FIXME: If this is a friend function template definition, we should check |
2428 | // to see if any specializations have been used. |
2429 | if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(CheckUsedAttr: false)) { |
2430 | if (MemberSpecializationInfo *MSInfo = |
2431 | Function->getMemberSpecializationInfo()) { |
2432 | if (MSInfo->getPointOfInstantiation().isInvalid()) { |
2433 | SourceLocation Loc = D->getLocation(); // FIXME |
2434 | MSInfo->setPointOfInstantiation(Loc); |
2435 | SemaRef.PendingLocalImplicitInstantiations.push_back( |
2436 | x: std::make_pair(x&: Function, y&: Loc)); |
2437 | } |
2438 | } |
2439 | } |
2440 | |
2441 | if (D->isExplicitlyDefaulted()) { |
2442 | if (SubstDefaultedFunction(New: Function, Tmpl: D)) |
2443 | return nullptr; |
2444 | } |
2445 | if (D->isDeleted()) |
2446 | SemaRef.SetDeclDeleted(dcl: Function, DelLoc: D->getLocation(), Message: D->getDeletedMessage()); |
2447 | |
2448 | NamedDecl *PrincipalDecl = |
2449 | (TemplateParams ? cast<NamedDecl>(Val: FunctionTemplate) : Function); |
2450 | |
2451 | // If this declaration lives in a different context from its lexical context, |
2452 | // add it to the corresponding lookup table. |
2453 | if (isFriend || |
2454 | (Function->isLocalExternDecl() && !Function->getPreviousDecl())) |
2455 | DC->makeDeclVisibleInContext(D: PrincipalDecl); |
2456 | |
2457 | if (Function->isOverloadedOperator() && !DC->isRecord() && |
2458 | PrincipalDecl->isInIdentifierNamespace(NS: Decl::IDNS_Ordinary)) |
2459 | PrincipalDecl->setNonMemberOperator(); |
2460 | |
2461 | return Function; |
2462 | } |
2463 | |
2464 | Decl *TemplateDeclInstantiator::VisitCXXMethodDecl( |
2465 | CXXMethodDecl *D, TemplateParameterList *TemplateParams, |
2466 | RewriteKind FunctionRewriteKind) { |
2467 | FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); |
2468 | if (FunctionTemplate && !TemplateParams) { |
2469 | // We are creating a function template specialization from a function |
2470 | // template. Check whether there is already a function template |
2471 | // specialization for this particular set of template arguments. |
2472 | ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); |
2473 | |
2474 | void *InsertPos = nullptr; |
2475 | FunctionDecl *SpecFunc |
2476 | = FunctionTemplate->findSpecialization(Args: Innermost, InsertPos); |
2477 | |
2478 | // If we already have a function template specialization, return it. |
2479 | if (SpecFunc) |
2480 | return SpecFunc; |
2481 | } |
2482 | |
2483 | bool isFriend; |
2484 | if (FunctionTemplate) |
2485 | isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); |
2486 | else |
2487 | isFriend = (D->getFriendObjectKind() != Decl::FOK_None); |
2488 | |
2489 | bool MergeWithParentScope = (TemplateParams != nullptr) || |
2490 | !(isa<Decl>(Val: Owner) && |
2491 | cast<Decl>(Val: Owner)->isDefinedOutsideFunctionOrMethod()); |
2492 | LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); |
2493 | |
2494 | Sema::LambdaScopeForCallOperatorInstantiationRAII LambdaScope( |
2495 | SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope); |
2496 | |
2497 | // Instantiate enclosing template arguments for friends. |
2498 | SmallVector<TemplateParameterList *, 4> TempParamLists; |
2499 | unsigned NumTempParamLists = 0; |
2500 | if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { |
2501 | TempParamLists.resize(N: NumTempParamLists); |
2502 | for (unsigned I = 0; I != NumTempParamLists; ++I) { |
2503 | TemplateParameterList *TempParams = D->getTemplateParameterList(index: I); |
2504 | TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams); |
2505 | if (!InstParams) |
2506 | return nullptr; |
2507 | TempParamLists[I] = InstParams; |
2508 | } |
2509 | } |
2510 | |
2511 | auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(Function: D); |
2512 | // deduction guides need this |
2513 | const bool CouldInstantiate = |
2514 | InstantiatedExplicitSpecifier.getExpr() == nullptr || |
2515 | !InstantiatedExplicitSpecifier.getExpr()->isValueDependent(); |
2516 | |
2517 | // Delay the instantiation of the explicit-specifier until after the |
2518 | // constraints are checked during template argument deduction. |
2519 | if (CouldInstantiate || |
2520 | SemaRef.CodeSynthesisContexts.back().Kind != |
2521 | Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution) { |
2522 | InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier( |
2523 | TemplateArgs, ES: InstantiatedExplicitSpecifier); |
2524 | |
2525 | if (InstantiatedExplicitSpecifier.isInvalid()) |
2526 | return nullptr; |
2527 | } else { |
2528 | InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved); |
2529 | } |
2530 | |
2531 | // Implicit destructors/constructors created for local classes in |
2532 | // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI. |
2533 | // Unfortunately there isn't enough context in those functions to |
2534 | // conditionally populate the TSI without breaking non-template related use |
2535 | // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get |
2536 | // a proper transformation. |
2537 | if (cast<CXXRecordDecl>(Val: D->getParent())->isLambda() && |
2538 | !D->getTypeSourceInfo() && |
2539 | isa<CXXConstructorDecl, CXXDestructorDecl>(Val: D)) { |
2540 | TypeSourceInfo *TSI = |
2541 | SemaRef.Context.getTrivialTypeSourceInfo(T: D->getType()); |
2542 | D->setTypeSourceInfo(TSI); |
2543 | } |
2544 | |
2545 | SmallVector<ParmVarDecl *, 4> Params; |
2546 | TypeSourceInfo *TInfo = SubstFunctionType(D, Params); |
2547 | if (!TInfo) |
2548 | return nullptr; |
2549 | QualType T = adjustFunctionTypeForInstantiation(Context&: SemaRef.Context, D, TInfo); |
2550 | |
2551 | if (TemplateParams && TemplateParams->size()) { |
2552 | auto *LastParam = |
2553 | dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->asArray().back()); |
2554 | if (LastParam && LastParam->isImplicit() && |
2555 | LastParam->hasTypeConstraint()) { |
2556 | // In abbreviated templates, the type-constraints of invented template |
2557 | // type parameters are instantiated with the function type, invalidating |
2558 | // the TemplateParameterList which relied on the template type parameter |
2559 | // not having a type constraint. Recreate the TemplateParameterList with |
2560 | // the updated parameter list. |
2561 | TemplateParams = TemplateParameterList::Create( |
2562 | C: SemaRef.Context, TemplateLoc: TemplateParams->getTemplateLoc(), |
2563 | LAngleLoc: TemplateParams->getLAngleLoc(), Params: TemplateParams->asArray(), |
2564 | RAngleLoc: TemplateParams->getRAngleLoc(), RequiresClause: TemplateParams->getRequiresClause()); |
2565 | } |
2566 | } |
2567 | |
2568 | NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); |
2569 | if (QualifierLoc) { |
2570 | QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, |
2571 | TemplateArgs); |
2572 | if (!QualifierLoc) |
2573 | return nullptr; |
2574 | } |
2575 | |
2576 | DeclContext *DC = Owner; |
2577 | if (isFriend) { |
2578 | if (QualifierLoc) { |
2579 | CXXScopeSpec SS; |
2580 | SS.Adopt(Other: QualifierLoc); |
2581 | DC = SemaRef.computeDeclContext(SS); |
2582 | |
2583 | if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) |
2584 | return nullptr; |
2585 | } else { |
2586 | DC = SemaRef.FindInstantiatedContext(Loc: D->getLocation(), |
2587 | DC: D->getDeclContext(), |
2588 | TemplateArgs); |
2589 | } |
2590 | if (!DC) return nullptr; |
2591 | } |
2592 | |
2593 | CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC); |
2594 | Expr *TrailingRequiresClause = D->getTrailingRequiresClause(); |
2595 | |
2596 | DeclarationNameInfo NameInfo |
2597 | = SemaRef.SubstDeclarationNameInfo(NameInfo: D->getNameInfo(), TemplateArgs); |
2598 | |
2599 | if (FunctionRewriteKind != RewriteKind::None) |
2600 | adjustForRewrite(RK: FunctionRewriteKind, Orig: D, T, TInfo, NameInfo); |
2601 | |
2602 | // Build the instantiated method declaration. |
2603 | CXXMethodDecl *Method = nullptr; |
2604 | |
2605 | SourceLocation StartLoc = D->getInnerLocStart(); |
2606 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: D)) { |
2607 | Method = CXXConstructorDecl::Create( |
2608 | C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo, |
2609 | ES: InstantiatedExplicitSpecifier, UsesFPIntrin: Constructor->UsesFPIntrin(), |
2610 | isInline: Constructor->isInlineSpecified(), isImplicitlyDeclared: false, |
2611 | ConstexprKind: Constructor->getConstexprKind(), Inherited: InheritedConstructor(), |
2612 | TrailingRequiresClause); |
2613 | Method->setRangeEnd(Constructor->getEndLoc()); |
2614 | } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: D)) { |
2615 | Method = CXXDestructorDecl::Create( |
2616 | C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo, |
2617 | UsesFPIntrin: Destructor->UsesFPIntrin(), isInline: Destructor->isInlineSpecified(), isImplicitlyDeclared: false, |
2618 | ConstexprKind: Destructor->getConstexprKind(), TrailingRequiresClause); |
2619 | Method->setIneligibleOrNotSelected(true); |
2620 | Method->setRangeEnd(Destructor->getEndLoc()); |
2621 | Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName( |
2622 | Ty: SemaRef.Context.getCanonicalType( |
2623 | T: SemaRef.Context.getTypeDeclType(Decl: Record)))); |
2624 | } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: D)) { |
2625 | Method = CXXConversionDecl::Create( |
2626 | C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo, |
2627 | UsesFPIntrin: Conversion->UsesFPIntrin(), isInline: Conversion->isInlineSpecified(), |
2628 | ES: InstantiatedExplicitSpecifier, ConstexprKind: Conversion->getConstexprKind(), |
2629 | EndLocation: Conversion->getEndLoc(), TrailingRequiresClause); |
2630 | } else { |
2631 | StorageClass SC = D->isStatic() ? SC_Static : SC_None; |
2632 | Method = CXXMethodDecl::Create( |
2633 | C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo, SC, |
2634 | UsesFPIntrin: D->UsesFPIntrin(), isInline: D->isInlineSpecified(), ConstexprKind: D->getConstexprKind(), |
2635 | EndLocation: D->getEndLoc(), TrailingRequiresClause); |
2636 | } |
2637 | |
2638 | if (D->isInlined()) |
2639 | Method->setImplicitlyInline(); |
2640 | |
2641 | if (QualifierLoc) |
2642 | Method->setQualifierInfo(QualifierLoc); |
2643 | |
2644 | if (TemplateParams) { |
2645 | // Our resulting instantiation is actually a function template, since we |
2646 | // are substituting only the outer template parameters. For example, given |
2647 | // |
2648 | // template<typename T> |
2649 | // struct X { |
2650 | // template<typename U> void f(T, U); |
2651 | // }; |
2652 | // |
2653 | // X<int> x; |
2654 | // |
2655 | // We are instantiating the member template "f" within X<int>, which means |
2656 | // substituting int for T, but leaving "f" as a member function template. |
2657 | // Build the function template itself. |
2658 | FunctionTemplate = FunctionTemplateDecl::Create(C&: SemaRef.Context, DC: Record, |
2659 | L: Method->getLocation(), |
2660 | Name: Method->getDeclName(), |
2661 | Params: TemplateParams, Decl: Method); |
2662 | if (isFriend) { |
2663 | FunctionTemplate->setLexicalDeclContext(Owner); |
2664 | FunctionTemplate->setObjectOfFriendDecl(); |
2665 | } else if (D->isOutOfLine()) |
2666 | FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); |
2667 | Method->setDescribedFunctionTemplate(FunctionTemplate); |
2668 | } else if (FunctionTemplate) { |
2669 | // Record this function template specialization. |
2670 | ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); |
2671 | Method->setFunctionTemplateSpecialization(Template: FunctionTemplate, |
2672 | TemplateArgs: TemplateArgumentList::CreateCopy(Context&: SemaRef.Context, |
2673 | Args: Innermost), |
2674 | /*InsertPos=*/nullptr); |
2675 | } else if (!isFriend && FunctionRewriteKind == RewriteKind::None) { |
2676 | // Record that this is an instantiation of a member function. |
2677 | Method->setInstantiationOfMemberFunction(FD: D, TSK: TSK_ImplicitInstantiation); |
2678 | } |
2679 | |
2680 | // If we are instantiating a member function defined |
2681 | // out-of-line, the instantiation will have the same lexical |
2682 | // context (which will be a namespace scope) as the template. |
2683 | if (isFriend) { |
2684 | if (NumTempParamLists) |
2685 | Method->setTemplateParameterListsInfo( |
2686 | Context&: SemaRef.Context, |
2687 | TPLists: llvm::ArrayRef(TempParamLists.data(), NumTempParamLists)); |
2688 | |
2689 | Method->setLexicalDeclContext(Owner); |
2690 | Method->setObjectOfFriendDecl(); |
2691 | } else if (D->isOutOfLine()) |
2692 | Method->setLexicalDeclContext(D->getLexicalDeclContext()); |
2693 | |
2694 | // Attach the parameters |
2695 | for (unsigned P = 0; P < Params.size(); ++P) |
2696 | Params[P]->setOwningFunction(Method); |
2697 | Method->setParams(Params); |
2698 | |
2699 | if (InitMethodInstantiation(New: Method, Tmpl: D)) |
2700 | Method->setInvalidDecl(); |
2701 | |
2702 | LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, |
2703 | RedeclarationKind::ForExternalRedeclaration); |
2704 | |
2705 | bool IsExplicitSpecialization = false; |
2706 | |
2707 | // If the name of this function was written as a template-id, instantiate |
2708 | // the explicit template arguments. |
2709 | if (DependentFunctionTemplateSpecializationInfo *DFTSI = |
2710 | D->getDependentSpecializationInfo()) { |
2711 | // Instantiate the explicit template arguments. |
2712 | TemplateArgumentListInfo ExplicitArgs; |
2713 | if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) { |
2714 | ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc()); |
2715 | ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc()); |
2716 | if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs, |
2717 | Outputs&: ExplicitArgs)) |
2718 | return nullptr; |
2719 | } |
2720 | |
2721 | // Map the candidates for the primary template to their instantiations. |
2722 | for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) { |
2723 | if (NamedDecl *ND = |
2724 | SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: FTD, TemplateArgs)) |
2725 | Previous.addDecl(D: ND); |
2726 | else |
2727 | return nullptr; |
2728 | } |
2729 | |
2730 | if (SemaRef.CheckFunctionTemplateSpecialization( |
2731 | FD: Method, ExplicitTemplateArgs: DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr, |
2732 | Previous)) |
2733 | Method->setInvalidDecl(); |
2734 | |
2735 | IsExplicitSpecialization = true; |
2736 | } else if (const ASTTemplateArgumentListInfo *ArgsWritten = |
2737 | D->getTemplateSpecializationArgsAsWritten()) { |
2738 | SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: DC); |
2739 | |
2740 | TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(), |
2741 | ArgsWritten->getRAngleLoc()); |
2742 | |
2743 | if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs, |
2744 | Outputs&: ExplicitArgs)) |
2745 | return nullptr; |
2746 | |
2747 | if (SemaRef.CheckFunctionTemplateSpecialization(FD: Method, |
2748 | ExplicitTemplateArgs: &ExplicitArgs, |
2749 | Previous)) |
2750 | Method->setInvalidDecl(); |
2751 | |
2752 | IsExplicitSpecialization = true; |
2753 | } else if (!FunctionTemplate || TemplateParams || isFriend) { |
2754 | SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: Record); |
2755 | |
2756 | // In C++, the previous declaration we find might be a tag type |
2757 | // (class or enum). In this case, the new declaration will hide the |
2758 | // tag type. Note that this does not apply if we're declaring a |
2759 | // typedef (C++ [dcl.typedef]p4). |
2760 | if (Previous.isSingleTagDecl()) |
2761 | Previous.clear(); |
2762 | } |
2763 | |
2764 | // Per [temp.inst], default arguments in member functions of local classes |
2765 | // are instantiated along with the member function declaration. For example: |
2766 | // |
2767 | // template<typename T> |
2768 | // void ft() { |
2769 | // struct lc { |
2770 | // int operator()(int p = []{ return T::value; }()); |
2771 | // }; |
2772 | // } |
2773 | // template void ft<int>(); // error: type 'int' cannot be used prior |
2774 | // to '::'because it has no members |
2775 | // |
2776 | // The error is issued during instantiation of ft<int>()::lc::operator() |
2777 | // because substitution into the default argument fails; the default argument |
2778 | // is instantiated even though it is never used. |
2779 | if (D->isInLocalScopeForInstantiation()) { |
2780 | for (unsigned P = 0; P < Params.size(); ++P) { |
2781 | if (!Params[P]->hasDefaultArg()) |
2782 | continue; |
2783 | if (SemaRef.SubstDefaultArgument(Loc: StartLoc, Param: Params[P], TemplateArgs)) { |
2784 | // If substitution fails, the default argument is set to a |
2785 | // RecoveryExpr that wraps the uninstantiated default argument so |
2786 | // that downstream diagnostics are omitted. |
2787 | Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg(); |
2788 | ExprResult ErrorResult = SemaRef.CreateRecoveryExpr( |
2789 | Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(), |
2790 | SubExprs: { UninstExpr }, T: UninstExpr->getType()); |
2791 | if (ErrorResult.isUsable()) |
2792 | Params[P]->setDefaultArg(ErrorResult.get()); |
2793 | } |
2794 | } |
2795 | } |
2796 | |
2797 | SemaRef.CheckFunctionDeclaration(S: nullptr, NewFD: Method, Previous, |
2798 | IsMemberSpecialization: IsExplicitSpecialization, |
2799 | DeclIsDefn: Method->isThisDeclarationADefinition()); |
2800 | |
2801 | if (D->isPureVirtual()) |
2802 | SemaRef.CheckPureMethod(Method, InitRange: SourceRange()); |
2803 | |
2804 | // Propagate access. For a non-friend declaration, the access is |
2805 | // whatever we're propagating from. For a friend, it should be the |
2806 | // previous declaration we just found. |
2807 | if (isFriend && Method->getPreviousDecl()) |
2808 | Method->setAccess(Method->getPreviousDecl()->getAccess()); |
2809 | else |
2810 | Method->setAccess(D->getAccess()); |
2811 | if (FunctionTemplate) |
2812 | FunctionTemplate->setAccess(Method->getAccess()); |
2813 | |
2814 | SemaRef.CheckOverrideControl(D: Method); |
2815 | |
2816 | // If a function is defined as defaulted or deleted, mark it as such now. |
2817 | if (D->isExplicitlyDefaulted()) { |
2818 | if (SubstDefaultedFunction(New: Method, Tmpl: D)) |
2819 | return nullptr; |
2820 | } |
2821 | if (D->isDeletedAsWritten()) |
2822 | SemaRef.SetDeclDeleted(dcl: Method, DelLoc: Method->getLocation(), |
2823 | Message: D->getDeletedMessage()); |
2824 | |
2825 | // If this is an explicit specialization, mark the implicitly-instantiated |
2826 | // template specialization as being an explicit specialization too. |
2827 | // FIXME: Is this necessary? |
2828 | if (IsExplicitSpecialization && !isFriend) |
2829 | SemaRef.CompleteMemberSpecialization(Member: Method, Previous); |
2830 | |
2831 | // If the method is a special member function, we need to mark it as |
2832 | // ineligible so that Owner->addDecl() won't mark the class as non trivial. |
2833 | // At the end of the class instantiation, we calculate eligibility again and |
2834 | // then we adjust trivility if needed. |
2835 | // We need this check to happen only after the method parameters are set, |
2836 | // because being e.g. a copy constructor depends on the instantiated |
2837 | // arguments. |
2838 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method)) { |
2839 | if (Constructor->isDefaultConstructor() || |
2840 | Constructor->isCopyOrMoveConstructor()) |
2841 | Method->setIneligibleOrNotSelected(true); |
2842 | } else if (Method->isCopyAssignmentOperator() || |
2843 | Method->isMoveAssignmentOperator()) { |
2844 | Method->setIneligibleOrNotSelected(true); |
2845 | } |
2846 | |
2847 | // If there's a function template, let our caller handle it. |
2848 | if (FunctionTemplate) { |
2849 | // do nothing |
2850 | |
2851 | // Don't hide a (potentially) valid declaration with an invalid one. |
2852 | } else if (Method->isInvalidDecl() && !Previous.empty()) { |
2853 | // do nothing |
2854 | |
2855 | // Otherwise, check access to friends and make them visible. |
2856 | } else if (isFriend) { |
2857 | // We only need to re-check access for methods which we didn't |
2858 | // manage to match during parsing. |
2859 | if (!D->getPreviousDecl()) |
2860 | SemaRef.CheckFriendAccess(D: Method); |
2861 | |
2862 | Record->makeDeclVisibleInContext(D: Method); |
2863 | |
2864 | // Otherwise, add the declaration. We don't need to do this for |
2865 | // class-scope specializations because we'll have matched them with |
2866 | // the appropriate template. |
2867 | } else { |
2868 | Owner->addDecl(D: Method); |
2869 | } |
2870 | |
2871 | // PR17480: Honor the used attribute to instantiate member function |
2872 | // definitions |
2873 | if (Method->hasAttr<UsedAttr>()) { |
2874 | if (const auto *A = dyn_cast<CXXRecordDecl>(Val: Owner)) { |
2875 | SourceLocation Loc; |
2876 | if (const MemberSpecializationInfo *MSInfo = |
2877 | A->getMemberSpecializationInfo()) |
2878 | Loc = MSInfo->getPointOfInstantiation(); |
2879 | else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: A)) |
2880 | Loc = Spec->getPointOfInstantiation(); |
2881 | SemaRef.MarkFunctionReferenced(Loc, Func: Method); |
2882 | } |
2883 | } |
2884 | |
2885 | return Method; |
2886 | } |
2887 | |
2888 | Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { |
2889 | return VisitCXXMethodDecl(D); |
2890 | } |
2891 | |
2892 | Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { |
2893 | return VisitCXXMethodDecl(D); |
2894 | } |
2895 | |
2896 | Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { |
2897 | return VisitCXXMethodDecl(D); |
2898 | } |
2899 | |
2900 | Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { |
2901 | return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, |
2902 | NumExpansions: std::nullopt, |
2903 | /*ExpectParameterPack=*/false); |
2904 | } |
2905 | |
2906 | Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( |
2907 | TemplateTypeParmDecl *D) { |
2908 | assert(D->getTypeForDecl()->isTemplateTypeParmType()); |
2909 | |
2910 | std::optional<unsigned> NumExpanded; |
2911 | |
2912 | if (const TypeConstraint *TC = D->getTypeConstraint()) { |
2913 | if (D->isPackExpansion() && !D->isExpandedParameterPack()) { |
2914 | assert(TC->getTemplateArgsAsWritten() && |
2915 | "type parameter can only be an expansion when explicit arguments " |
2916 | "are specified" ); |
2917 | // The template type parameter pack's type is a pack expansion of types. |
2918 | // Determine whether we need to expand this parameter pack into separate |
2919 | // types. |
2920 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
2921 | for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments()) |
2922 | SemaRef.collectUnexpandedParameterPacks(Arg: ArgLoc, Unexpanded); |
2923 | |
2924 | // Determine whether the set of unexpanded parameter packs can and should |
2925 | // be expanded. |
2926 | bool Expand = true; |
2927 | bool RetainExpansion = false; |
2928 | if (SemaRef.CheckParameterPacksForExpansion( |
2929 | EllipsisLoc: cast<CXXFoldExpr>(Val: TC->getImmediatelyDeclaredConstraint()) |
2930 | ->getEllipsisLoc(), |
2931 | PatternRange: SourceRange(TC->getConceptNameLoc(), |
2932 | TC->hasExplicitTemplateArgs() ? |
2933 | TC->getTemplateArgsAsWritten()->getRAngleLoc() : |
2934 | TC->getConceptNameInfo().getEndLoc()), |
2935 | Unexpanded, TemplateArgs, ShouldExpand&: Expand, RetainExpansion, NumExpansions&: NumExpanded)) |
2936 | return nullptr; |
2937 | } |
2938 | } |
2939 | |
2940 | TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create( |
2941 | C: SemaRef.Context, DC: Owner, KeyLoc: D->getBeginLoc(), NameLoc: D->getLocation(), |
2942 | D: D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), P: D->getIndex(), |
2943 | Id: D->getIdentifier(), Typename: D->wasDeclaredWithTypename(), ParameterPack: D->isParameterPack(), |
2944 | HasTypeConstraint: D->hasTypeConstraint(), NumExpanded); |
2945 | |
2946 | Inst->setAccess(AS_public); |
2947 | Inst->setImplicit(D->isImplicit()); |
2948 | if (auto *TC = D->getTypeConstraint()) { |
2949 | if (!D->isImplicit()) { |
2950 | // Invented template parameter type constraints will be instantiated |
2951 | // with the corresponding auto-typed parameter as it might reference |
2952 | // other parameters. |
2953 | if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs, |
2954 | EvaluateConstraint: EvaluateConstraints)) |
2955 | return nullptr; |
2956 | } |
2957 | } |
2958 | if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { |
2959 | TemplateArgumentLoc Output; |
2960 | if (!SemaRef.SubstTemplateArgument(Input: D->getDefaultArgument(), TemplateArgs, |
2961 | Output)) |
2962 | Inst->setDefaultArgument(C: SemaRef.getASTContext(), DefArg: Output); |
2963 | } |
2964 | |
2965 | // Introduce this template parameter's instantiation into the instantiation |
2966 | // scope. |
2967 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); |
2968 | |
2969 | return Inst; |
2970 | } |
2971 | |
2972 | Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( |
2973 | NonTypeTemplateParmDecl *D) { |
2974 | // Substitute into the type of the non-type template parameter. |
2975 | TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); |
2976 | SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; |
2977 | SmallVector<QualType, 4> ExpandedParameterPackTypes; |
2978 | bool IsExpandedParameterPack = false; |
2979 | TypeSourceInfo *DI; |
2980 | QualType T; |
2981 | bool Invalid = false; |
2982 | |
2983 | if (D->isExpandedParameterPack()) { |
2984 | // The non-type template parameter pack is an already-expanded pack |
2985 | // expansion of types. Substitute into each of the expanded types. |
2986 | ExpandedParameterPackTypes.reserve(N: D->getNumExpansionTypes()); |
2987 | ExpandedParameterPackTypesAsWritten.reserve(N: D->getNumExpansionTypes()); |
2988 | for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { |
2989 | TypeSourceInfo *NewDI = |
2990 | SemaRef.SubstType(T: D->getExpansionTypeSourceInfo(I), TemplateArgs, |
2991 | Loc: D->getLocation(), Entity: D->getDeclName()); |
2992 | if (!NewDI) |
2993 | return nullptr; |
2994 | |
2995 | QualType NewT = |
2996 | SemaRef.CheckNonTypeTemplateParameterType(TSI&: NewDI, Loc: D->getLocation()); |
2997 | if (NewT.isNull()) |
2998 | return nullptr; |
2999 | |
3000 | ExpandedParameterPackTypesAsWritten.push_back(Elt: NewDI); |
3001 | ExpandedParameterPackTypes.push_back(Elt: NewT); |
3002 | } |
3003 | |
3004 | IsExpandedParameterPack = true; |
3005 | DI = D->getTypeSourceInfo(); |
3006 | T = DI->getType(); |
3007 | } else if (D->isPackExpansion()) { |
3008 | // The non-type template parameter pack's type is a pack expansion of types. |
3009 | // Determine whether we need to expand this parameter pack into separate |
3010 | // types. |
3011 | PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); |
3012 | TypeLoc Pattern = Expansion.getPatternLoc(); |
3013 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
3014 | SemaRef.collectUnexpandedParameterPacks(TL: Pattern, Unexpanded); |
3015 | |
3016 | // Determine whether the set of unexpanded parameter packs can and should |
3017 | // be expanded. |
3018 | bool Expand = true; |
3019 | bool RetainExpansion = false; |
3020 | std::optional<unsigned> OrigNumExpansions = |
3021 | Expansion.getTypePtr()->getNumExpansions(); |
3022 | std::optional<unsigned> NumExpansions = OrigNumExpansions; |
3023 | if (SemaRef.CheckParameterPacksForExpansion(EllipsisLoc: Expansion.getEllipsisLoc(), |
3024 | PatternRange: Pattern.getSourceRange(), |
3025 | Unexpanded, |
3026 | TemplateArgs, |
3027 | ShouldExpand&: Expand, RetainExpansion, |
3028 | NumExpansions)) |
3029 | return nullptr; |
3030 | |
3031 | if (Expand) { |
3032 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
3033 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); |
3034 | TypeSourceInfo *NewDI = SemaRef.SubstType(TL: Pattern, TemplateArgs, |
3035 | Loc: D->getLocation(), |
3036 | Entity: D->getDeclName()); |
3037 | if (!NewDI) |
3038 | return nullptr; |
3039 | |
3040 | QualType NewT = |
3041 | SemaRef.CheckNonTypeTemplateParameterType(TSI&: NewDI, Loc: D->getLocation()); |
3042 | if (NewT.isNull()) |
3043 | return nullptr; |
3044 | |
3045 | ExpandedParameterPackTypesAsWritten.push_back(Elt: NewDI); |
3046 | ExpandedParameterPackTypes.push_back(Elt: NewT); |
3047 | } |
3048 | |
3049 | // Note that we have an expanded parameter pack. The "type" of this |
3050 | // expanded parameter pack is the original expansion type, but callers |
3051 | // will end up using the expanded parameter pack types for type-checking. |
3052 | IsExpandedParameterPack = true; |
3053 | DI = D->getTypeSourceInfo(); |
3054 | T = DI->getType(); |
3055 | } else { |
3056 | // We cannot fully expand the pack expansion now, so substitute into the |
3057 | // pattern and create a new pack expansion type. |
3058 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); |
3059 | TypeSourceInfo *NewPattern = SemaRef.SubstType(TL: Pattern, TemplateArgs, |
3060 | Loc: D->getLocation(), |
3061 | Entity: D->getDeclName()); |
3062 | if (!NewPattern) |
3063 | return nullptr; |
3064 | |
3065 | SemaRef.CheckNonTypeTemplateParameterType(TSI&: NewPattern, Loc: D->getLocation()); |
3066 | DI = SemaRef.CheckPackExpansion(Pattern: NewPattern, EllipsisLoc: Expansion.getEllipsisLoc(), |
3067 | NumExpansions); |
3068 | if (!DI) |
3069 | return nullptr; |
3070 | |
3071 | T = DI->getType(); |
3072 | } |
3073 | } else { |
3074 | // Simple case: substitution into a parameter that is not a parameter pack. |
3075 | DI = SemaRef.SubstType(T: D->getTypeSourceInfo(), TemplateArgs, |
3076 | Loc: D->getLocation(), Entity: D->getDeclName()); |
3077 | if (!DI) |
3078 | return nullptr; |
3079 | |
3080 | // Check that this type is acceptable for a non-type template parameter. |
3081 | T = SemaRef.CheckNonTypeTemplateParameterType(TSI&: DI, Loc: D->getLocation()); |
3082 | if (T.isNull()) { |
3083 | T = SemaRef.Context.IntTy; |
3084 | Invalid = true; |
3085 | } |
3086 | } |
3087 | |
3088 | NonTypeTemplateParmDecl *Param; |
3089 | if (IsExpandedParameterPack) |
3090 | Param = NonTypeTemplateParmDecl::Create( |
3091 | C: SemaRef.Context, DC: Owner, StartLoc: D->getInnerLocStart(), IdLoc: D->getLocation(), |
3092 | D: D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), |
3093 | P: D->getPosition(), Id: D->getIdentifier(), T, TInfo: DI, ExpandedTypes: ExpandedParameterPackTypes, |
3094 | ExpandedTInfos: ExpandedParameterPackTypesAsWritten); |
3095 | else |
3096 | Param = NonTypeTemplateParmDecl::Create( |
3097 | C: SemaRef.Context, DC: Owner, StartLoc: D->getInnerLocStart(), IdLoc: D->getLocation(), |
3098 | D: D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), |
3099 | P: D->getPosition(), Id: D->getIdentifier(), T, ParameterPack: D->isParameterPack(), TInfo: DI); |
3100 | |
3101 | if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc()) |
3102 | if (AutoLoc.isConstrained()) { |
3103 | SourceLocation EllipsisLoc; |
3104 | if (IsExpandedParameterPack) |
3105 | EllipsisLoc = |
3106 | DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc(); |
3107 | else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>( |
3108 | Val: D->getPlaceholderTypeConstraint())) |
3109 | EllipsisLoc = Constraint->getEllipsisLoc(); |
3110 | // Note: We attach the uninstantiated constriant here, so that it can be |
3111 | // instantiated relative to the top level, like all our other |
3112 | // constraints. |
3113 | if (SemaRef.AttachTypeConstraint(TL: AutoLoc, /*NewConstrainedParm=*/Param, |
3114 | /*OrigConstrainedParm=*/D, EllipsisLoc)) |
3115 | Invalid = true; |
3116 | } |
3117 | |
3118 | Param->setAccess(AS_public); |
3119 | Param->setImplicit(D->isImplicit()); |
3120 | if (Invalid) |
3121 | Param->setInvalidDecl(); |
3122 | |
3123 | if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { |
3124 | EnterExpressionEvaluationContext ConstantEvaluated( |
3125 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
3126 | TemplateArgumentLoc Result; |
3127 | if (!SemaRef.SubstTemplateArgument(Input: D->getDefaultArgument(), TemplateArgs, |
3128 | Output&: Result)) |
3129 | Param->setDefaultArgument(C: SemaRef.Context, DefArg: Result); |
3130 | } |
3131 | |
3132 | // Introduce this template parameter's instantiation into the instantiation |
3133 | // scope. |
3134 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: Param); |
3135 | return Param; |
3136 | } |
3137 | |
3138 | static void collectUnexpandedParameterPacks( |
3139 | Sema &S, |
3140 | TemplateParameterList *Params, |
3141 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { |
3142 | for (const auto &P : *Params) { |
3143 | if (P->isTemplateParameterPack()) |
3144 | continue; |
3145 | if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) |
3146 | S.collectUnexpandedParameterPacks(TL: NTTP->getTypeSourceInfo()->getTypeLoc(), |
3147 | Unexpanded); |
3148 | if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: P)) |
3149 | collectUnexpandedParameterPacks(S, Params: TTP->getTemplateParameters(), |
3150 | Unexpanded); |
3151 | } |
3152 | } |
3153 | |
3154 | Decl * |
3155 | TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( |
3156 | TemplateTemplateParmDecl *D) { |
3157 | // Instantiate the template parameter list of the template template parameter. |
3158 | TemplateParameterList *TempParams = D->getTemplateParameters(); |
3159 | TemplateParameterList *InstParams; |
3160 | SmallVector<TemplateParameterList*, 8> ExpandedParams; |
3161 | |
3162 | bool IsExpandedParameterPack = false; |
3163 | |
3164 | if (D->isExpandedParameterPack()) { |
3165 | // The template template parameter pack is an already-expanded pack |
3166 | // expansion of template parameters. Substitute into each of the expanded |
3167 | // parameters. |
3168 | ExpandedParams.reserve(N: D->getNumExpansionTemplateParameters()); |
3169 | for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); |
3170 | I != N; ++I) { |
3171 | LocalInstantiationScope Scope(SemaRef); |
3172 | TemplateParameterList *Expansion = |
3173 | SubstTemplateParams(List: D->getExpansionTemplateParameters(I)); |
3174 | if (!Expansion) |
3175 | return nullptr; |
3176 | ExpandedParams.push_back(Elt: Expansion); |
3177 | } |
3178 | |
3179 | IsExpandedParameterPack = true; |
3180 | InstParams = TempParams; |
3181 | } else if (D->isPackExpansion()) { |
3182 | // The template template parameter pack expands to a pack of template |
3183 | // template parameters. Determine whether we need to expand this parameter |
3184 | // pack into separate parameters. |
3185 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
3186 | collectUnexpandedParameterPacks(S&: SemaRef, Params: D->getTemplateParameters(), |
3187 | Unexpanded); |
3188 | |
3189 | // Determine whether the set of unexpanded parameter packs can and should |
3190 | // be expanded. |
3191 | bool Expand = true; |
3192 | bool RetainExpansion = false; |
3193 | std::optional<unsigned> NumExpansions; |
3194 | if (SemaRef.CheckParameterPacksForExpansion(EllipsisLoc: D->getLocation(), |
3195 | PatternRange: TempParams->getSourceRange(), |
3196 | Unexpanded, |
3197 | TemplateArgs, |
3198 | ShouldExpand&: Expand, RetainExpansion, |
3199 | NumExpansions)) |
3200 | return nullptr; |
3201 | |
3202 | if (Expand) { |
3203 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
3204 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); |
3205 | LocalInstantiationScope Scope(SemaRef); |
3206 | TemplateParameterList *Expansion = SubstTemplateParams(List: TempParams); |
3207 | if (!Expansion) |
3208 | return nullptr; |
3209 | ExpandedParams.push_back(Elt: Expansion); |
3210 | } |
3211 | |
3212 | // Note that we have an expanded parameter pack. The "type" of this |
3213 | // expanded parameter pack is the original expansion type, but callers |
3214 | // will end up using the expanded parameter pack types for type-checking. |
3215 | IsExpandedParameterPack = true; |
3216 | InstParams = TempParams; |
3217 | } else { |
3218 | // We cannot fully expand the pack expansion now, so just substitute |
3219 | // into the pattern. |
3220 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); |
3221 | |
3222 | LocalInstantiationScope Scope(SemaRef); |
3223 | InstParams = SubstTemplateParams(List: TempParams); |
3224 | if (!InstParams) |
3225 | return nullptr; |
3226 | } |
3227 | } else { |
3228 | // Perform the actual substitution of template parameters within a new, |
3229 | // local instantiation scope. |
3230 | LocalInstantiationScope Scope(SemaRef); |
3231 | InstParams = SubstTemplateParams(List: TempParams); |
3232 | if (!InstParams) |
3233 | return nullptr; |
3234 | } |
3235 | |
3236 | // Build the template template parameter. |
3237 | TemplateTemplateParmDecl *Param; |
3238 | if (IsExpandedParameterPack) |
3239 | Param = TemplateTemplateParmDecl::Create( |
3240 | C: SemaRef.Context, DC: Owner, L: D->getLocation(), |
3241 | D: D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), |
3242 | P: D->getPosition(), Id: D->getIdentifier(), Typename: D->wasDeclaredWithTypename(), |
3243 | Params: InstParams, Expansions: ExpandedParams); |
3244 | else |
3245 | Param = TemplateTemplateParmDecl::Create( |
3246 | C: SemaRef.Context, DC: Owner, L: D->getLocation(), |
3247 | D: D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), |
3248 | P: D->getPosition(), ParameterPack: D->isParameterPack(), Id: D->getIdentifier(), |
3249 | Typename: D->wasDeclaredWithTypename(), Params: InstParams); |
3250 | if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { |
3251 | NestedNameSpecifierLoc QualifierLoc = |
3252 | D->getDefaultArgument().getTemplateQualifierLoc(); |
3253 | QualifierLoc = |
3254 | SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, TemplateArgs); |
3255 | TemplateName TName = SemaRef.SubstTemplateName( |
3256 | QualifierLoc, Name: D->getDefaultArgument().getArgument().getAsTemplate(), |
3257 | Loc: D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); |
3258 | if (!TName.isNull()) |
3259 | Param->setDefaultArgument( |
3260 | C: SemaRef.Context, |
3261 | DefArg: TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName), |
3262 | D->getDefaultArgument().getTemplateQualifierLoc(), |
3263 | D->getDefaultArgument().getTemplateNameLoc())); |
3264 | } |
3265 | Param->setAccess(AS_public); |
3266 | Param->setImplicit(D->isImplicit()); |
3267 | |
3268 | // Introduce this template parameter's instantiation into the instantiation |
3269 | // scope. |
3270 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: Param); |
3271 | |
3272 | return Param; |
3273 | } |
3274 | |
3275 | Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { |
3276 | // Using directives are never dependent (and never contain any types or |
3277 | // expressions), so they require no explicit instantiation work. |
3278 | |
3279 | UsingDirectiveDecl *Inst |
3280 | = UsingDirectiveDecl::Create(C&: SemaRef.Context, DC: Owner, UsingLoc: D->getLocation(), |
3281 | NamespaceLoc: D->getNamespaceKeyLocation(), |
3282 | QualifierLoc: D->getQualifierLoc(), |
3283 | IdentLoc: D->getIdentLocation(), |
3284 | Nominated: D->getNominatedNamespace(), |
3285 | CommonAncestor: D->getCommonAncestor()); |
3286 | |
3287 | // Add the using directive to its declaration context |
3288 | // only if this is not a function or method. |
3289 | if (!Owner->isFunctionOrMethod()) |
3290 | Owner->addDecl(D: Inst); |
3291 | |
3292 | return Inst; |
3293 | } |
3294 | |
3295 | Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D, |
3296 | BaseUsingDecl *Inst, |
3297 | LookupResult *Lookup) { |
3298 | |
3299 | bool isFunctionScope = Owner->isFunctionOrMethod(); |
3300 | |
3301 | for (auto *Shadow : D->shadows()) { |
3302 | // FIXME: UsingShadowDecl doesn't preserve its immediate target, so |
3303 | // reconstruct it in the case where it matters. Hm, can we extract it from |
3304 | // the DeclSpec when parsing and save it in the UsingDecl itself? |
3305 | NamedDecl *OldTarget = Shadow->getTargetDecl(); |
3306 | if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Val: Shadow)) |
3307 | if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl()) |
3308 | OldTarget = BaseShadow; |
3309 | |
3310 | NamedDecl *InstTarget = nullptr; |
3311 | if (auto *EmptyD = |
3312 | dyn_cast<UnresolvedUsingIfExistsDecl>(Val: Shadow->getTargetDecl())) { |
3313 | InstTarget = UnresolvedUsingIfExistsDecl::Create( |
3314 | Ctx&: SemaRef.Context, DC: Owner, Loc: EmptyD->getLocation(), Name: EmptyD->getDeclName()); |
3315 | } else { |
3316 | InstTarget = cast_or_null<NamedDecl>(Val: SemaRef.FindInstantiatedDecl( |
3317 | Loc: Shadow->getLocation(), D: OldTarget, TemplateArgs)); |
3318 | } |
3319 | if (!InstTarget) |
3320 | return nullptr; |
3321 | |
3322 | UsingShadowDecl *PrevDecl = nullptr; |
3323 | if (Lookup && |
3324 | SemaRef.CheckUsingShadowDecl(BUD: Inst, Target: InstTarget, PreviousDecls: *Lookup, PrevShadow&: PrevDecl)) |
3325 | continue; |
3326 | |
3327 | if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(D: Shadow)) |
3328 | PrevDecl = cast_or_null<UsingShadowDecl>(Val: SemaRef.FindInstantiatedDecl( |
3329 | Loc: Shadow->getLocation(), D: OldPrev, TemplateArgs)); |
3330 | |
3331 | UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl( |
3332 | /*Scope*/ S: nullptr, BUD: Inst, Target: InstTarget, PrevDecl); |
3333 | SemaRef.Context.setInstantiatedFromUsingShadowDecl(Inst: InstShadow, Pattern: Shadow); |
3334 | |
3335 | if (isFunctionScope) |
3336 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D: Shadow, Inst: InstShadow); |
3337 | } |
3338 | |
3339 | return Inst; |
3340 | } |
3341 | |
3342 | Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { |
3343 | |
3344 | // The nested name specifier may be dependent, for example |
3345 | // template <typename T> struct t { |
3346 | // struct s1 { T f1(); }; |
3347 | // struct s2 : s1 { using s1::f1; }; |
3348 | // }; |
3349 | // template struct t<int>; |
3350 | // Here, in using s1::f1, s1 refers to t<T>::s1; |
3351 | // we need to substitute for t<int>::s1. |
3352 | NestedNameSpecifierLoc QualifierLoc |
3353 | = SemaRef.SubstNestedNameSpecifierLoc(NNS: D->getQualifierLoc(), |
3354 | TemplateArgs); |
3355 | if (!QualifierLoc) |
3356 | return nullptr; |
3357 | |
3358 | // For an inheriting constructor declaration, the name of the using |
3359 | // declaration is the name of a constructor in this class, not in the |
3360 | // base class. |
3361 | DeclarationNameInfo NameInfo = D->getNameInfo(); |
3362 | if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) |
3363 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: SemaRef.CurContext)) |
3364 | NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName( |
3365 | Ty: SemaRef.Context.getCanonicalType(T: SemaRef.Context.getRecordType(Decl: RD)))); |
3366 | |
3367 | // We only need to do redeclaration lookups if we're in a class scope (in |
3368 | // fact, it's not really even possible in non-class scopes). |
3369 | bool CheckRedeclaration = Owner->isRecord(); |
3370 | LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, |
3371 | RedeclarationKind::ForVisibleRedeclaration); |
3372 | |
3373 | UsingDecl *NewUD = UsingDecl::Create(C&: SemaRef.Context, DC: Owner, |
3374 | UsingL: D->getUsingLoc(), |
3375 | QualifierLoc, |
3376 | NameInfo, |
3377 | HasTypenameKeyword: D->hasTypename()); |
3378 | |
3379 | CXXScopeSpec SS; |
3380 | SS.Adopt(Other: QualifierLoc); |
3381 | if (CheckRedeclaration) { |
3382 | Prev.setHideTags(false); |
3383 | SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: Owner); |
3384 | |
3385 | // Check for invalid redeclarations. |
3386 | if (SemaRef.CheckUsingDeclRedeclaration(UsingLoc: D->getUsingLoc(), |
3387 | HasTypenameKeyword: D->hasTypename(), SS, |
3388 | NameLoc: D->getLocation(), Previous: Prev)) |
3389 | NewUD->setInvalidDecl(); |
3390 | } |
3391 | |
3392 | if (!NewUD->isInvalidDecl() && |
3393 | SemaRef.CheckUsingDeclQualifier(UsingLoc: D->getUsingLoc(), HasTypename: D->hasTypename(), SS, |
3394 | NameInfo, NameLoc: D->getLocation(), R: nullptr, UD: D)) |
3395 | NewUD->setInvalidDecl(); |
3396 | |
3397 | SemaRef.Context.setInstantiatedFromUsingDecl(Inst: NewUD, Pattern: D); |
3398 | NewUD->setAccess(D->getAccess()); |
3399 | Owner->addDecl(D: NewUD); |
3400 | |
3401 | // Don't process the shadow decls for an invalid decl. |
3402 | if (NewUD->isInvalidDecl()) |
3403 | return NewUD; |
3404 | |
3405 | // If the using scope was dependent, or we had dependent bases, we need to |
3406 | // recheck the inheritance |
3407 | if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) |
3408 | SemaRef.CheckInheritingConstructorUsingDecl(UD: NewUD); |
3409 | |
3410 | return VisitBaseUsingDecls(D, Inst: NewUD, Lookup: CheckRedeclaration ? &Prev : nullptr); |
3411 | } |
3412 | |
3413 | Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) { |
3414 | // Cannot be a dependent type, but still could be an instantiation |
3415 | EnumDecl *EnumD = cast_or_null<EnumDecl>(Val: SemaRef.FindInstantiatedDecl( |
3416 | Loc: D->getLocation(), D: D->getEnumDecl(), TemplateArgs)); |
3417 | |
3418 | if (SemaRef.RequireCompleteEnumDecl(D: EnumD, L: EnumD->getLocation())) |
3419 | return nullptr; |
3420 | |
3421 | TypeSourceInfo *TSI = SemaRef.SubstType(T: D->getEnumType(), TemplateArgs, |
3422 | Loc: D->getLocation(), Entity: D->getDeclName()); |
3423 | |
3424 | if (!TSI) |
3425 | return nullptr; |
3426 | |
3427 | UsingEnumDecl *NewUD = |
3428 | UsingEnumDecl::Create(C&: SemaRef.Context, DC: Owner, UsingL: D->getUsingLoc(), |
3429 | EnumL: D->getEnumLoc(), NameL: D->getLocation(), EnumType: TSI); |
3430 | |
3431 | SemaRef.Context.setInstantiatedFromUsingEnumDecl(Inst: NewUD, Pattern: D); |
3432 | NewUD->setAccess(D->getAccess()); |
3433 | Owner->addDecl(D: NewUD); |
3434 | |
3435 | // Don't process the shadow decls for an invalid decl. |
3436 | if (NewUD->isInvalidDecl()) |
3437 | return NewUD; |
3438 | |
3439 | // We don't have to recheck for duplication of the UsingEnumDecl itself, as it |
3440 | // cannot be dependent, and will therefore have been checked during template |
3441 | // definition. |
3442 | |
3443 | return VisitBaseUsingDecls(D, Inst: NewUD, Lookup: nullptr); |
3444 | } |
3445 | |
3446 | Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { |
3447 | // Ignore these; we handle them in bulk when processing the UsingDecl. |
3448 | return nullptr; |
3449 | } |
3450 | |
3451 | Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl( |
3452 | ConstructorUsingShadowDecl *D) { |
3453 | // Ignore these; we handle them in bulk when processing the UsingDecl. |
3454 | return nullptr; |
3455 | } |
3456 | |
3457 | template <typename T> |
3458 | Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl( |
3459 | T *D, bool InstantiatingPackElement) { |
3460 | // If this is a pack expansion, expand it now. |
3461 | if (D->isPackExpansion() && !InstantiatingPackElement) { |
3462 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
3463 | SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded); |
3464 | SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded); |
3465 | |
3466 | // Determine whether the set of unexpanded parameter packs can and should |
3467 | // be expanded. |
3468 | bool Expand = true; |
3469 | bool RetainExpansion = false; |
3470 | std::optional<unsigned> NumExpansions; |
3471 | if (SemaRef.CheckParameterPacksForExpansion( |
3472 | EllipsisLoc: D->getEllipsisLoc(), PatternRange: D->getSourceRange(), Unexpanded, TemplateArgs, |
3473 | ShouldExpand&: Expand, RetainExpansion, NumExpansions)) |
3474 | return nullptr; |
3475 | |
3476 | // This declaration cannot appear within a function template signature, |
3477 | // so we can't have a partial argument list for a parameter pack. |
3478 | assert(!RetainExpansion && |
3479 | "should never need to retain an expansion for UsingPackDecl" ); |
3480 | |
3481 | if (!Expand) { |
3482 | // We cannot fully expand the pack expansion now, so substitute into the |
3483 | // pattern and create a new pack expansion. |
3484 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); |
3485 | return instantiateUnresolvedUsingDecl(D, true); |
3486 | } |
3487 | |
3488 | // Within a function, we don't have any normal way to check for conflicts |
3489 | // between shadow declarations from different using declarations in the |
3490 | // same pack expansion, but this is always ill-formed because all expansions |
3491 | // must produce (conflicting) enumerators. |
3492 | // |
3493 | // Sadly we can't just reject this in the template definition because it |
3494 | // could be valid if the pack is empty or has exactly one expansion. |
3495 | if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) { |
3496 | SemaRef.Diag(D->getEllipsisLoc(), |
3497 | diag::err_using_decl_redeclaration_expansion); |
3498 | return nullptr; |
3499 | } |
3500 | |
3501 | // Instantiate the slices of this pack and build a UsingPackDecl. |
3502 | SmallVector<NamedDecl*, 8> Expansions; |
3503 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
3504 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); |
3505 | Decl *Slice = instantiateUnresolvedUsingDecl(D, true); |
3506 | if (!Slice) |
3507 | return nullptr; |
3508 | // Note that we can still get unresolved using declarations here, if we |
3509 | // had arguments for all packs but the pattern also contained other |
3510 | // template arguments (this only happens during partial substitution, eg |
3511 | // into the body of a generic lambda in a function template). |
3512 | Expansions.push_back(Elt: cast<NamedDecl>(Val: Slice)); |
3513 | } |
3514 | |
3515 | auto *NewD = SemaRef.BuildUsingPackDecl(InstantiatedFrom: D, Expansions); |
3516 | if (isDeclWithinFunction(D)) |
3517 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewD); |
3518 | return NewD; |
3519 | } |
3520 | |
3521 | UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D); |
3522 | SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation(); |
3523 | |
3524 | NestedNameSpecifierLoc QualifierLoc |
3525 | = SemaRef.SubstNestedNameSpecifierLoc(NNS: D->getQualifierLoc(), |
3526 | TemplateArgs); |
3527 | if (!QualifierLoc) |
3528 | return nullptr; |
3529 | |
3530 | CXXScopeSpec SS; |
3531 | SS.Adopt(Other: QualifierLoc); |
3532 | |
3533 | DeclarationNameInfo NameInfo |
3534 | = SemaRef.SubstDeclarationNameInfo(NameInfo: D->getNameInfo(), TemplateArgs); |
3535 | |
3536 | // Produce a pack expansion only if we're not instantiating a particular |
3537 | // slice of a pack expansion. |
3538 | bool InstantiatingSlice = D->getEllipsisLoc().isValid() && |
3539 | SemaRef.ArgumentPackSubstitutionIndex != -1; |
3540 | SourceLocation EllipsisLoc = |
3541 | InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc(); |
3542 | |
3543 | bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>(); |
3544 | NamedDecl *UD = SemaRef.BuildUsingDeclaration( |
3545 | /*Scope*/ S: nullptr, AS: D->getAccess(), UsingLoc: D->getUsingLoc(), |
3546 | /*HasTypename*/ HasTypenameKeyword: TD, TypenameLoc, SS, NameInfo, EllipsisLoc, |
3547 | AttrList: ParsedAttributesView(), |
3548 | /*IsInstantiation*/ true, IsUsingIfExists); |
3549 | if (UD) { |
3550 | SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: UD); |
3551 | SemaRef.Context.setInstantiatedFromUsingDecl(Inst: UD, Pattern: D); |
3552 | } |
3553 | |
3554 | return UD; |
3555 | } |
3556 | |
3557 | Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl( |
3558 | UnresolvedUsingTypenameDecl *D) { |
3559 | return instantiateUnresolvedUsingDecl(D); |
3560 | } |
3561 | |
3562 | Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl( |
3563 | UnresolvedUsingValueDecl *D) { |
3564 | return instantiateUnresolvedUsingDecl(D); |
3565 | } |
3566 | |
3567 | Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl( |
3568 | UnresolvedUsingIfExistsDecl *D) { |
3569 | llvm_unreachable("referring to unresolved decl out of UsingShadowDecl" ); |
3570 | } |
3571 | |
3572 | Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) { |
3573 | SmallVector<NamedDecl*, 8> Expansions; |
3574 | for (auto *UD : D->expansions()) { |
3575 | if (NamedDecl *NewUD = |
3576 | SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: UD, TemplateArgs)) |
3577 | Expansions.push_back(Elt: NewUD); |
3578 | else |
3579 | return nullptr; |
3580 | } |
3581 | |
3582 | auto *NewD = SemaRef.BuildUsingPackDecl(InstantiatedFrom: D, Expansions); |
3583 | if (isDeclWithinFunction(D)) |
3584 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewD); |
3585 | return NewD; |
3586 | } |
3587 | |
3588 | Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( |
3589 | OMPThreadPrivateDecl *D) { |
3590 | SmallVector<Expr *, 5> Vars; |
3591 | for (auto *I : D->varlists()) { |
3592 | Expr *Var = SemaRef.SubstExpr(E: I, TemplateArgs).get(); |
3593 | assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr" ); |
3594 | Vars.push_back(Elt: Var); |
3595 | } |
3596 | |
3597 | OMPThreadPrivateDecl *TD = |
3598 | SemaRef.OpenMP().CheckOMPThreadPrivateDecl(Loc: D->getLocation(), VarList: Vars); |
3599 | |
3600 | TD->setAccess(AS_public); |
3601 | Owner->addDecl(D: TD); |
3602 | |
3603 | return TD; |
3604 | } |
3605 | |
3606 | Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) { |
3607 | SmallVector<Expr *, 5> Vars; |
3608 | for (auto *I : D->varlists()) { |
3609 | Expr *Var = SemaRef.SubstExpr(E: I, TemplateArgs).get(); |
3610 | assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr" ); |
3611 | Vars.push_back(Elt: Var); |
3612 | } |
3613 | SmallVector<OMPClause *, 4> Clauses; |
3614 | // Copy map clauses from the original mapper. |
3615 | for (OMPClause *C : D->clauselists()) { |
3616 | OMPClause *IC = nullptr; |
3617 | if (auto *AC = dyn_cast<OMPAllocatorClause>(Val: C)) { |
3618 | ExprResult NewE = SemaRef.SubstExpr(E: AC->getAllocator(), TemplateArgs); |
3619 | if (!NewE.isUsable()) |
3620 | continue; |
3621 | IC = SemaRef.OpenMP().ActOnOpenMPAllocatorClause( |
3622 | Allocator: NewE.get(), StartLoc: AC->getBeginLoc(), LParenLoc: AC->getLParenLoc(), EndLoc: AC->getEndLoc()); |
3623 | } else if (auto *AC = dyn_cast<OMPAlignClause>(Val: C)) { |
3624 | ExprResult NewE = SemaRef.SubstExpr(E: AC->getAlignment(), TemplateArgs); |
3625 | if (!NewE.isUsable()) |
3626 | continue; |
3627 | IC = SemaRef.OpenMP().ActOnOpenMPAlignClause( |
3628 | Alignment: NewE.get(), StartLoc: AC->getBeginLoc(), LParenLoc: AC->getLParenLoc(), EndLoc: AC->getEndLoc()); |
3629 | // If align clause value ends up being invalid, this can end up null. |
3630 | if (!IC) |
3631 | continue; |
3632 | } |
3633 | Clauses.push_back(Elt: IC); |
3634 | } |
3635 | |
3636 | Sema::DeclGroupPtrTy Res = SemaRef.OpenMP().ActOnOpenMPAllocateDirective( |
3637 | Loc: D->getLocation(), VarList: Vars, Clauses, Owner); |
3638 | if (Res.get().isNull()) |
3639 | return nullptr; |
3640 | return Res.get().getSingleDecl(); |
3641 | } |
3642 | |
3643 | Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) { |
3644 | llvm_unreachable( |
3645 | "Requires directive cannot be instantiated within a dependent context" ); |
3646 | } |
3647 | |
3648 | Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl( |
3649 | OMPDeclareReductionDecl *D) { |
3650 | // Instantiate type and check if it is allowed. |
3651 | const bool RequiresInstantiation = |
3652 | D->getType()->isDependentType() || |
3653 | D->getType()->isInstantiationDependentType() || |
3654 | D->getType()->containsUnexpandedParameterPack(); |
3655 | QualType SubstReductionType; |
3656 | if (RequiresInstantiation) { |
3657 | SubstReductionType = SemaRef.OpenMP().ActOnOpenMPDeclareReductionType( |
3658 | TyLoc: D->getLocation(), |
3659 | ParsedType: ParsedType::make(P: SemaRef.SubstType( |
3660 | T: D->getType(), TemplateArgs, Loc: D->getLocation(), Entity: DeclarationName()))); |
3661 | } else { |
3662 | SubstReductionType = D->getType(); |
3663 | } |
3664 | if (SubstReductionType.isNull()) |
3665 | return nullptr; |
3666 | Expr *Combiner = D->getCombiner(); |
3667 | Expr *Init = D->getInitializer(); |
3668 | bool IsCorrect = true; |
3669 | // Create instantiated copy. |
3670 | std::pair<QualType, SourceLocation> ReductionTypes[] = { |
3671 | std::make_pair(x&: SubstReductionType, y: D->getLocation())}; |
3672 | auto *PrevDeclInScope = D->getPrevDeclInScope(); |
3673 | if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { |
3674 | PrevDeclInScope = cast<OMPDeclareReductionDecl>( |
3675 | Val: SemaRef.CurrentInstantiationScope->findInstantiationOf(D: PrevDeclInScope) |
3676 | ->get<Decl *>()); |
3677 | } |
3678 | auto DRD = SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveStart( |
3679 | /*S=*/nullptr, DC: Owner, Name: D->getDeclName(), ReductionTypes, AS: D->getAccess(), |
3680 | PrevDeclInScope); |
3681 | auto *NewDRD = cast<OMPDeclareReductionDecl>(Val: DRD.get().getSingleDecl()); |
3682 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewDRD); |
3683 | Expr *SubstCombiner = nullptr; |
3684 | Expr *SubstInitializer = nullptr; |
3685 | // Combiners instantiation sequence. |
3686 | if (Combiner) { |
3687 | SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerStart( |
3688 | /*S=*/nullptr, D: NewDRD); |
3689 | SemaRef.CurrentInstantiationScope->InstantiatedLocal( |
3690 | D: cast<DeclRefExpr>(Val: D->getCombinerIn())->getDecl(), |
3691 | Inst: cast<DeclRefExpr>(Val: NewDRD->getCombinerIn())->getDecl()); |
3692 | SemaRef.CurrentInstantiationScope->InstantiatedLocal( |
3693 | D: cast<DeclRefExpr>(Val: D->getCombinerOut())->getDecl(), |
3694 | Inst: cast<DeclRefExpr>(Val: NewDRD->getCombinerOut())->getDecl()); |
3695 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: Owner); |
3696 | Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), |
3697 | ThisContext); |
3698 | SubstCombiner = SemaRef.SubstExpr(E: Combiner, TemplateArgs).get(); |
3699 | SemaRef.OpenMP().ActOnOpenMPDeclareReductionCombinerEnd(D: NewDRD, |
3700 | Combiner: SubstCombiner); |
3701 | } |
3702 | // Initializers instantiation sequence. |
3703 | if (Init) { |
3704 | VarDecl *OmpPrivParm = |
3705 | SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerStart( |
3706 | /*S=*/nullptr, D: NewDRD); |
3707 | SemaRef.CurrentInstantiationScope->InstantiatedLocal( |
3708 | D: cast<DeclRefExpr>(Val: D->getInitOrig())->getDecl(), |
3709 | Inst: cast<DeclRefExpr>(Val: NewDRD->getInitOrig())->getDecl()); |
3710 | SemaRef.CurrentInstantiationScope->InstantiatedLocal( |
3711 | D: cast<DeclRefExpr>(Val: D->getInitPriv())->getDecl(), |
3712 | Inst: cast<DeclRefExpr>(Val: NewDRD->getInitPriv())->getDecl()); |
3713 | if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) { |
3714 | SubstInitializer = SemaRef.SubstExpr(E: Init, TemplateArgs).get(); |
3715 | } else { |
3716 | auto *OldPrivParm = |
3717 | cast<VarDecl>(Val: cast<DeclRefExpr>(Val: D->getInitPriv())->getDecl()); |
3718 | IsCorrect = IsCorrect && OldPrivParm->hasInit(); |
3719 | if (IsCorrect) |
3720 | SemaRef.InstantiateVariableInitializer(Var: OmpPrivParm, OldVar: OldPrivParm, |
3721 | TemplateArgs); |
3722 | } |
3723 | SemaRef.OpenMP().ActOnOpenMPDeclareReductionInitializerEnd( |
3724 | D: NewDRD, Initializer: SubstInitializer, OmpPrivParm); |
3725 | } |
3726 | IsCorrect = IsCorrect && SubstCombiner && |
3727 | (!Init || |
3728 | (D->getInitializerKind() == OMPDeclareReductionInitKind::Call && |
3729 | SubstInitializer) || |
3730 | (D->getInitializerKind() != OMPDeclareReductionInitKind::Call && |
3731 | !SubstInitializer)); |
3732 | |
3733 | (void)SemaRef.OpenMP().ActOnOpenMPDeclareReductionDirectiveEnd( |
3734 | /*S=*/nullptr, DeclReductions: DRD, IsValid: IsCorrect && !D->isInvalidDecl()); |
3735 | |
3736 | return NewDRD; |
3737 | } |
3738 | |
3739 | Decl * |
3740 | TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) { |
3741 | // Instantiate type and check if it is allowed. |
3742 | const bool RequiresInstantiation = |
3743 | D->getType()->isDependentType() || |
3744 | D->getType()->isInstantiationDependentType() || |
3745 | D->getType()->containsUnexpandedParameterPack(); |
3746 | QualType SubstMapperTy; |
3747 | DeclarationName VN = D->getVarName(); |
3748 | if (RequiresInstantiation) { |
3749 | SubstMapperTy = SemaRef.OpenMP().ActOnOpenMPDeclareMapperType( |
3750 | TyLoc: D->getLocation(), |
3751 | ParsedType: ParsedType::make(P: SemaRef.SubstType(T: D->getType(), TemplateArgs, |
3752 | Loc: D->getLocation(), Entity: VN))); |
3753 | } else { |
3754 | SubstMapperTy = D->getType(); |
3755 | } |
3756 | if (SubstMapperTy.isNull()) |
3757 | return nullptr; |
3758 | // Create an instantiated copy of mapper. |
3759 | auto *PrevDeclInScope = D->getPrevDeclInScope(); |
3760 | if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { |
3761 | PrevDeclInScope = cast<OMPDeclareMapperDecl>( |
3762 | Val: SemaRef.CurrentInstantiationScope->findInstantiationOf(D: PrevDeclInScope) |
3763 | ->get<Decl *>()); |
3764 | } |
3765 | bool IsCorrect = true; |
3766 | SmallVector<OMPClause *, 6> Clauses; |
3767 | // Instantiate the mapper variable. |
3768 | DeclarationNameInfo DirName; |
3769 | SemaRef.OpenMP().StartOpenMPDSABlock(K: llvm::omp::OMPD_declare_mapper, DirName, |
3770 | /*S=*/CurScope: nullptr, |
3771 | Loc: (*D->clauselist_begin())->getBeginLoc()); |
3772 | ExprResult MapperVarRef = |
3773 | SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirectiveVarDecl( |
3774 | /*S=*/nullptr, MapperType: SubstMapperTy, StartLoc: D->getLocation(), VN); |
3775 | SemaRef.CurrentInstantiationScope->InstantiatedLocal( |
3776 | D: cast<DeclRefExpr>(Val: D->getMapperVarRef())->getDecl(), |
3777 | Inst: cast<DeclRefExpr>(Val: MapperVarRef.get())->getDecl()); |
3778 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: Owner); |
3779 | Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), |
3780 | ThisContext); |
3781 | // Instantiate map clauses. |
3782 | for (OMPClause *C : D->clauselists()) { |
3783 | auto *OldC = cast<OMPMapClause>(Val: C); |
3784 | SmallVector<Expr *, 4> NewVars; |
3785 | for (Expr *OE : OldC->varlists()) { |
3786 | Expr *NE = SemaRef.SubstExpr(E: OE, TemplateArgs).get(); |
3787 | if (!NE) { |
3788 | IsCorrect = false; |
3789 | break; |
3790 | } |
3791 | NewVars.push_back(Elt: NE); |
3792 | } |
3793 | if (!IsCorrect) |
3794 | break; |
3795 | NestedNameSpecifierLoc NewQualifierLoc = |
3796 | SemaRef.SubstNestedNameSpecifierLoc(NNS: OldC->getMapperQualifierLoc(), |
3797 | TemplateArgs); |
3798 | CXXScopeSpec SS; |
3799 | SS.Adopt(Other: NewQualifierLoc); |
3800 | DeclarationNameInfo NewNameInfo = |
3801 | SemaRef.SubstDeclarationNameInfo(NameInfo: OldC->getMapperIdInfo(), TemplateArgs); |
3802 | OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(), |
3803 | OldC->getEndLoc()); |
3804 | OMPClause *NewC = SemaRef.OpenMP().ActOnOpenMPMapClause( |
3805 | IteratorModifier: OldC->getIteratorModifier(), MapTypeModifiers: OldC->getMapTypeModifiers(), |
3806 | MapTypeModifiersLoc: OldC->getMapTypeModifiersLoc(), MapperIdScopeSpec&: SS, MapperId&: NewNameInfo, MapType: OldC->getMapType(), |
3807 | IsMapTypeImplicit: OldC->isImplicitMapType(), MapLoc: OldC->getMapLoc(), ColonLoc: OldC->getColonLoc(), |
3808 | VarList: NewVars, Locs); |
3809 | Clauses.push_back(Elt: NewC); |
3810 | } |
3811 | SemaRef.OpenMP().EndOpenMPDSABlock(CurDirective: nullptr); |
3812 | if (!IsCorrect) |
3813 | return nullptr; |
3814 | Sema::DeclGroupPtrTy DG = SemaRef.OpenMP().ActOnOpenMPDeclareMapperDirective( |
3815 | /*S=*/nullptr, DC: Owner, Name: D->getDeclName(), MapperType: SubstMapperTy, StartLoc: D->getLocation(), |
3816 | VN, AS: D->getAccess(), MapperVarRef: MapperVarRef.get(), Clauses, PrevDeclInScope); |
3817 | Decl *NewDMD = DG.get().getSingleDecl(); |
3818 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewDMD); |
3819 | return NewDMD; |
3820 | } |
3821 | |
3822 | Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl( |
3823 | OMPCapturedExprDecl * /*D*/) { |
3824 | llvm_unreachable("Should not be met in templates" ); |
3825 | } |
3826 | |
3827 | Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { |
3828 | return VisitFunctionDecl(D, TemplateParams: nullptr); |
3829 | } |
3830 | |
3831 | Decl * |
3832 | TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) { |
3833 | Decl *Inst = VisitFunctionDecl(D, TemplateParams: nullptr); |
3834 | if (Inst && !D->getDescribedFunctionTemplate()) |
3835 | Owner->addDecl(D: Inst); |
3836 | return Inst; |
3837 | } |
3838 | |
3839 | Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { |
3840 | return VisitCXXMethodDecl(D, TemplateParams: nullptr); |
3841 | } |
3842 | |
3843 | Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { |
3844 | llvm_unreachable("There are only CXXRecordDecls in C++" ); |
3845 | } |
3846 | |
3847 | Decl * |
3848 | TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( |
3849 | ClassTemplateSpecializationDecl *D) { |
3850 | // As a MS extension, we permit class-scope explicit specialization |
3851 | // of member class templates. |
3852 | ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); |
3853 | assert(ClassTemplate->getDeclContext()->isRecord() && |
3854 | D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && |
3855 | "can only instantiate an explicit specialization " |
3856 | "for a member class template" ); |
3857 | |
3858 | // Lookup the already-instantiated declaration in the instantiation |
3859 | // of the class template. |
3860 | ClassTemplateDecl *InstClassTemplate = |
3861 | cast_or_null<ClassTemplateDecl>(Val: SemaRef.FindInstantiatedDecl( |
3862 | Loc: D->getLocation(), D: ClassTemplate, TemplateArgs)); |
3863 | if (!InstClassTemplate) |
3864 | return nullptr; |
3865 | |
3866 | // Substitute into the template arguments of the class template explicit |
3867 | // specialization. |
3868 | TemplateArgumentListInfo InstTemplateArgs; |
3869 | if (const ASTTemplateArgumentListInfo *TemplateArgsInfo = |
3870 | D->getTemplateArgsAsWritten()) { |
3871 | InstTemplateArgs.setLAngleLoc(TemplateArgsInfo->getLAngleLoc()); |
3872 | InstTemplateArgs.setRAngleLoc(TemplateArgsInfo->getRAngleLoc()); |
3873 | |
3874 | if (SemaRef.SubstTemplateArguments(Args: TemplateArgsInfo->arguments(), |
3875 | TemplateArgs, Outputs&: InstTemplateArgs)) |
3876 | return nullptr; |
3877 | } |
3878 | |
3879 | // Check that the template argument list is well-formed for this |
3880 | // class template. |
3881 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
3882 | if (SemaRef.CheckTemplateArgumentList(Template: InstClassTemplate, TemplateLoc: D->getLocation(), |
3883 | TemplateArgs&: InstTemplateArgs, PartialTemplateArgs: false, |
3884 | SugaredConverted, CanonicalConverted, |
3885 | /*UpdateArgsWithConversions=*/true)) |
3886 | return nullptr; |
3887 | |
3888 | // Figure out where to insert this class template explicit specialization |
3889 | // in the member template's set of class template explicit specializations. |
3890 | void *InsertPos = nullptr; |
3891 | ClassTemplateSpecializationDecl *PrevDecl = |
3892 | InstClassTemplate->findSpecialization(Args: CanonicalConverted, InsertPos); |
3893 | |
3894 | // Check whether we've already seen a conflicting instantiation of this |
3895 | // declaration (for instance, if there was a prior implicit instantiation). |
3896 | bool Ignored; |
3897 | if (PrevDecl && |
3898 | SemaRef.CheckSpecializationInstantiationRedecl(NewLoc: D->getLocation(), |
3899 | ActOnExplicitInstantiationNewTSK: D->getSpecializationKind(), |
3900 | PrevDecl, |
3901 | PrevTSK: PrevDecl->getSpecializationKind(), |
3902 | PrevPtOfInstantiation: PrevDecl->getPointOfInstantiation(), |
3903 | SuppressNew&: Ignored)) |
3904 | return nullptr; |
3905 | |
3906 | // If PrevDecl was a definition and D is also a definition, diagnose. |
3907 | // This happens in cases like: |
3908 | // |
3909 | // template<typename T, typename U> |
3910 | // struct Outer { |
3911 | // template<typename X> struct Inner; |
3912 | // template<> struct Inner<T> {}; |
3913 | // template<> struct Inner<U> {}; |
3914 | // }; |
3915 | // |
3916 | // Outer<int, int> outer; // error: the explicit specializations of Inner |
3917 | // // have the same signature. |
3918 | if (PrevDecl && PrevDecl->getDefinition() && |
3919 | D->isThisDeclarationADefinition()) { |
3920 | SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_redefinition) << PrevDecl; |
3921 | SemaRef.Diag(Loc: PrevDecl->getDefinition()->getLocation(), |
3922 | DiagID: diag::note_previous_definition); |
3923 | return nullptr; |
3924 | } |
3925 | |
3926 | // Create the class template partial specialization declaration. |
3927 | ClassTemplateSpecializationDecl *InstD = |
3928 | ClassTemplateSpecializationDecl::Create( |
3929 | Context&: SemaRef.Context, TK: D->getTagKind(), DC: Owner, StartLoc: D->getBeginLoc(), |
3930 | IdLoc: D->getLocation(), SpecializedTemplate: InstClassTemplate, Args: CanonicalConverted, PrevDecl); |
3931 | InstD->setTemplateArgsAsWritten(InstTemplateArgs); |
3932 | |
3933 | // Add this partial specialization to the set of class template partial |
3934 | // specializations. |
3935 | if (!PrevDecl) |
3936 | InstClassTemplate->AddSpecialization(D: InstD, InsertPos); |
3937 | |
3938 | // Substitute the nested name specifier, if any. |
3939 | if (SubstQualifier(OldDecl: D, NewDecl: InstD)) |
3940 | return nullptr; |
3941 | |
3942 | InstD->setAccess(D->getAccess()); |
3943 | InstD->setInstantiationOfMemberClass(RD: D, TSK: TSK_ImplicitInstantiation); |
3944 | InstD->setSpecializationKind(D->getSpecializationKind()); |
3945 | InstD->setExternKeywordLoc(D->getExternKeywordLoc()); |
3946 | InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); |
3947 | |
3948 | Owner->addDecl(D: InstD); |
3949 | |
3950 | // Instantiate the members of the class-scope explicit specialization eagerly. |
3951 | // We don't have support for lazy instantiation of an explicit specialization |
3952 | // yet, and MSVC eagerly instantiates in this case. |
3953 | // FIXME: This is wrong in standard C++. |
3954 | if (D->isThisDeclarationADefinition() && |
3955 | SemaRef.InstantiateClass(PointOfInstantiation: D->getLocation(), Instantiation: InstD, Pattern: D, TemplateArgs, |
3956 | TSK: TSK_ImplicitInstantiation, |
3957 | /*Complain=*/true)) |
3958 | return nullptr; |
3959 | |
3960 | return InstD; |
3961 | } |
3962 | |
3963 | Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( |
3964 | VarTemplateSpecializationDecl *D) { |
3965 | |
3966 | TemplateArgumentListInfo VarTemplateArgsInfo; |
3967 | VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); |
3968 | assert(VarTemplate && |
3969 | "A template specialization without specialized template?" ); |
3970 | |
3971 | VarTemplateDecl *InstVarTemplate = |
3972 | cast_or_null<VarTemplateDecl>(Val: SemaRef.FindInstantiatedDecl( |
3973 | Loc: D->getLocation(), D: VarTemplate, TemplateArgs)); |
3974 | if (!InstVarTemplate) |
3975 | return nullptr; |
3976 | |
3977 | // Substitute the current template arguments. |
3978 | if (const ASTTemplateArgumentListInfo *TemplateArgsInfo = |
3979 | D->getTemplateArgsAsWritten()) { |
3980 | VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc()); |
3981 | VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc()); |
3982 | |
3983 | if (SemaRef.SubstTemplateArguments(Args: TemplateArgsInfo->arguments(), |
3984 | TemplateArgs, Outputs&: VarTemplateArgsInfo)) |
3985 | return nullptr; |
3986 | } |
3987 | |
3988 | // Check that the template argument list is well-formed for this template. |
3989 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
3990 | if (SemaRef.CheckTemplateArgumentList(Template: InstVarTemplate, TemplateLoc: D->getLocation(), |
3991 | TemplateArgs&: VarTemplateArgsInfo, PartialTemplateArgs: false, |
3992 | SugaredConverted, CanonicalConverted, |
3993 | /*UpdateArgsWithConversions=*/true)) |
3994 | return nullptr; |
3995 | |
3996 | // Check whether we've already seen a declaration of this specialization. |
3997 | void *InsertPos = nullptr; |
3998 | VarTemplateSpecializationDecl *PrevDecl = |
3999 | InstVarTemplate->findSpecialization(Args: CanonicalConverted, InsertPos); |
4000 | |
4001 | // Check whether we've already seen a conflicting instantiation of this |
4002 | // declaration (for instance, if there was a prior implicit instantiation). |
4003 | bool Ignored; |
4004 | if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl( |
4005 | NewLoc: D->getLocation(), ActOnExplicitInstantiationNewTSK: D->getSpecializationKind(), PrevDecl, |
4006 | PrevTSK: PrevDecl->getSpecializationKind(), |
4007 | PrevPtOfInstantiation: PrevDecl->getPointOfInstantiation(), SuppressNew&: Ignored)) |
4008 | return nullptr; |
4009 | |
4010 | return VisitVarTemplateSpecializationDecl( |
4011 | VarTemplate: InstVarTemplate, FromVar: D, TemplateArgsInfo: VarTemplateArgsInfo, Converted: CanonicalConverted, PrevDecl); |
4012 | } |
4013 | |
4014 | Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( |
4015 | VarTemplateDecl *VarTemplate, VarDecl *D, |
4016 | const TemplateArgumentListInfo &TemplateArgsInfo, |
4017 | ArrayRef<TemplateArgument> Converted, |
4018 | VarTemplateSpecializationDecl *PrevDecl) { |
4019 | |
4020 | // Do substitution on the type of the declaration |
4021 | TypeSourceInfo *DI = |
4022 | SemaRef.SubstType(T: D->getTypeSourceInfo(), TemplateArgs, |
4023 | Loc: D->getTypeSpecStartLoc(), Entity: D->getDeclName()); |
4024 | if (!DI) |
4025 | return nullptr; |
4026 | |
4027 | if (DI->getType()->isFunctionType()) { |
4028 | SemaRef.Diag(Loc: D->getLocation(), DiagID: diag::err_variable_instantiates_to_function) |
4029 | << D->isStaticDataMember() << DI->getType(); |
4030 | return nullptr; |
4031 | } |
4032 | |
4033 | // Build the instantiated declaration |
4034 | VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( |
4035 | Context&: SemaRef.Context, DC: Owner, StartLoc: D->getInnerLocStart(), IdLoc: D->getLocation(), |
4036 | SpecializedTemplate: VarTemplate, T: DI->getType(), TInfo: DI, S: D->getStorageClass(), Args: Converted); |
4037 | Var->setTemplateArgsAsWritten(TemplateArgsInfo); |
4038 | if (!PrevDecl) { |
4039 | void *InsertPos = nullptr; |
4040 | VarTemplate->findSpecialization(Args: Converted, InsertPos); |
4041 | VarTemplate->AddSpecialization(D: Var, InsertPos); |
4042 | } |
4043 | |
4044 | if (SemaRef.getLangOpts().OpenCL) |
4045 | SemaRef.deduceOpenCLAddressSpace(decl: Var); |
4046 | |
4047 | // Substitute the nested name specifier, if any. |
4048 | if (SubstQualifier(OldDecl: D, NewDecl: Var)) |
4049 | return nullptr; |
4050 | |
4051 | SemaRef.BuildVariableInstantiation(NewVar: Var, OldVar: D, TemplateArgs, LateAttrs, Owner, |
4052 | StartingScope, InstantiatingVarTemplate: false, PrevVTSD: PrevDecl); |
4053 | |
4054 | return Var; |
4055 | } |
4056 | |
4057 | Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { |
4058 | llvm_unreachable("@defs is not supported in Objective-C++" ); |
4059 | } |
4060 | |
4061 | Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { |
4062 | // FIXME: We need to be able to instantiate FriendTemplateDecls. |
4063 | unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( |
4064 | L: DiagnosticsEngine::Error, |
4065 | FormatString: "cannot instantiate %0 yet" ); |
4066 | SemaRef.Diag(Loc: D->getLocation(), DiagID) |
4067 | << D->getDeclKindName(); |
4068 | |
4069 | return nullptr; |
4070 | } |
4071 | |
4072 | Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) { |
4073 | llvm_unreachable("Concept definitions cannot reside inside a template" ); |
4074 | } |
4075 | |
4076 | Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl( |
4077 | ImplicitConceptSpecializationDecl *D) { |
4078 | llvm_unreachable("Concept specializations cannot reside inside a template" ); |
4079 | } |
4080 | |
4081 | Decl * |
4082 | TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) { |
4083 | return RequiresExprBodyDecl::Create(C&: SemaRef.Context, DC: D->getDeclContext(), |
4084 | StartLoc: D->getBeginLoc()); |
4085 | } |
4086 | |
4087 | Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { |
4088 | llvm_unreachable("Unexpected decl" ); |
4089 | } |
4090 | |
4091 | Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, |
4092 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
4093 | TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); |
4094 | if (D->isInvalidDecl()) |
4095 | return nullptr; |
4096 | |
4097 | Decl *SubstD; |
4098 | runWithSufficientStackSpace(Loc: D->getLocation(), Fn: [&] { |
4099 | SubstD = Instantiator.Visit(D); |
4100 | }); |
4101 | return SubstD; |
4102 | } |
4103 | |
4104 | void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK, |
4105 | FunctionDecl *Orig, QualType &T, |
4106 | TypeSourceInfo *&TInfo, |
4107 | DeclarationNameInfo &NameInfo) { |
4108 | assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual); |
4109 | |
4110 | // C++2a [class.compare.default]p3: |
4111 | // the return type is replaced with bool |
4112 | auto *FPT = T->castAs<FunctionProtoType>(); |
4113 | T = SemaRef.Context.getFunctionType( |
4114 | ResultTy: SemaRef.Context.BoolTy, Args: FPT->getParamTypes(), EPI: FPT->getExtProtoInfo()); |
4115 | |
4116 | // Update the return type in the source info too. The most straightforward |
4117 | // way is to create new TypeSourceInfo for the new type. Use the location of |
4118 | // the '= default' as the location of the new type. |
4119 | // |
4120 | // FIXME: Set the correct return type when we initially transform the type, |
4121 | // rather than delaying it to now. |
4122 | TypeSourceInfo *NewTInfo = |
4123 | SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Orig->getEndLoc()); |
4124 | auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>(); |
4125 | assert(OldLoc && "type of function is not a function type?" ); |
4126 | auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>(); |
4127 | for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I) |
4128 | NewLoc.setParam(i: I, VD: OldLoc.getParam(i: I)); |
4129 | TInfo = NewTInfo; |
4130 | |
4131 | // and the declarator-id is replaced with operator== |
4132 | NameInfo.setName( |
4133 | SemaRef.Context.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual)); |
4134 | } |
4135 | |
4136 | FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, |
4137 | FunctionDecl *Spaceship) { |
4138 | if (Spaceship->isInvalidDecl()) |
4139 | return nullptr; |
4140 | |
4141 | // C++2a [class.compare.default]p3: |
4142 | // an == operator function is declared implicitly [...] with the same |
4143 | // access and function-definition and in the same class scope as the |
4144 | // three-way comparison operator function |
4145 | MultiLevelTemplateArgumentList NoTemplateArgs; |
4146 | NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite); |
4147 | NoTemplateArgs.addOuterRetainedLevels(Num: RD->getTemplateDepth()); |
4148 | TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs); |
4149 | Decl *R; |
4150 | if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Spaceship)) { |
4151 | R = Instantiator.VisitCXXMethodDecl( |
4152 | D: MD, /*TemplateParams=*/nullptr, |
4153 | FunctionRewriteKind: TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual); |
4154 | } else { |
4155 | assert(Spaceship->getFriendObjectKind() && |
4156 | "defaulted spaceship is neither a member nor a friend" ); |
4157 | |
4158 | R = Instantiator.VisitFunctionDecl( |
4159 | D: Spaceship, /*TemplateParams=*/nullptr, |
4160 | FunctionRewriteKind: TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual); |
4161 | if (!R) |
4162 | return nullptr; |
4163 | |
4164 | FriendDecl *FD = |
4165 | FriendDecl::Create(C&: Context, DC: RD, L: Spaceship->getLocation(), |
4166 | Friend_: cast<NamedDecl>(Val: R), FriendL: Spaceship->getBeginLoc()); |
4167 | FD->setAccess(AS_public); |
4168 | RD->addDecl(D: FD); |
4169 | } |
4170 | return cast_or_null<FunctionDecl>(Val: R); |
4171 | } |
4172 | |
4173 | /// Instantiates a nested template parameter list in the current |
4174 | /// instantiation context. |
4175 | /// |
4176 | /// \param L The parameter list to instantiate |
4177 | /// |
4178 | /// \returns NULL if there was an error |
4179 | TemplateParameterList * |
4180 | TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { |
4181 | // Get errors for all the parameters before bailing out. |
4182 | bool Invalid = false; |
4183 | |
4184 | unsigned N = L->size(); |
4185 | typedef SmallVector<NamedDecl *, 8> ParamVector; |
4186 | ParamVector Params; |
4187 | Params.reserve(N); |
4188 | for (auto &P : *L) { |
4189 | NamedDecl *D = cast_or_null<NamedDecl>(Val: Visit(D: P)); |
4190 | Params.push_back(Elt: D); |
4191 | Invalid = Invalid || !D || D->isInvalidDecl(); |
4192 | } |
4193 | |
4194 | // Clean up if we had an error. |
4195 | if (Invalid) |
4196 | return nullptr; |
4197 | |
4198 | Expr *InstRequiresClause = L->getRequiresClause(); |
4199 | |
4200 | TemplateParameterList *InstL |
4201 | = TemplateParameterList::Create(C: SemaRef.Context, TemplateLoc: L->getTemplateLoc(), |
4202 | LAngleLoc: L->getLAngleLoc(), Params, |
4203 | RAngleLoc: L->getRAngleLoc(), RequiresClause: InstRequiresClause); |
4204 | return InstL; |
4205 | } |
4206 | |
4207 | TemplateParameterList * |
4208 | Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, |
4209 | const MultiLevelTemplateArgumentList &TemplateArgs, |
4210 | bool EvaluateConstraints) { |
4211 | TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); |
4212 | Instantiator.setEvaluateConstraints(EvaluateConstraints); |
4213 | return Instantiator.SubstTemplateParams(L: Params); |
4214 | } |
4215 | |
4216 | /// Instantiate the declaration of a class template partial |
4217 | /// specialization. |
4218 | /// |
4219 | /// \param ClassTemplate the (instantiated) class template that is partially |
4220 | // specialized by the instantiation of \p PartialSpec. |
4221 | /// |
4222 | /// \param PartialSpec the (uninstantiated) class template partial |
4223 | /// specialization that we are instantiating. |
4224 | /// |
4225 | /// \returns The instantiated partial specialization, if successful; otherwise, |
4226 | /// NULL to indicate an error. |
4227 | ClassTemplatePartialSpecializationDecl * |
4228 | TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( |
4229 | ClassTemplateDecl *ClassTemplate, |
4230 | ClassTemplatePartialSpecializationDecl *PartialSpec) { |
4231 | // Create a local instantiation scope for this class template partial |
4232 | // specialization, which will contain the instantiations of the template |
4233 | // parameters. |
4234 | LocalInstantiationScope Scope(SemaRef); |
4235 | |
4236 | // Substitute into the template parameters of the class template partial |
4237 | // specialization. |
4238 | TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); |
4239 | TemplateParameterList *InstParams = SubstTemplateParams(L: TempParams); |
4240 | if (!InstParams) |
4241 | return nullptr; |
4242 | |
4243 | // Substitute into the template arguments of the class template partial |
4244 | // specialization. |
4245 | const ASTTemplateArgumentListInfo *TemplArgInfo |
4246 | = PartialSpec->getTemplateArgsAsWritten(); |
4247 | TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, |
4248 | TemplArgInfo->RAngleLoc); |
4249 | if (SemaRef.SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs, |
4250 | Outputs&: InstTemplateArgs)) |
4251 | return nullptr; |
4252 | |
4253 | // Check that the template argument list is well-formed for this |
4254 | // class template. |
4255 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
4256 | if (SemaRef.CheckTemplateArgumentList( |
4257 | Template: ClassTemplate, TemplateLoc: PartialSpec->getLocation(), TemplateArgs&: InstTemplateArgs, |
4258 | /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted)) |
4259 | return nullptr; |
4260 | |
4261 | // Check these arguments are valid for a template partial specialization. |
4262 | if (SemaRef.CheckTemplatePartialSpecializationArgs( |
4263 | Loc: PartialSpec->getLocation(), PrimaryTemplate: ClassTemplate, NumExplicitArgs: InstTemplateArgs.size(), |
4264 | Args: CanonicalConverted)) |
4265 | return nullptr; |
4266 | |
4267 | // Figure out where to insert this class template partial specialization |
4268 | // in the member template's set of class template partial specializations. |
4269 | void *InsertPos = nullptr; |
4270 | ClassTemplateSpecializationDecl *PrevDecl = |
4271 | ClassTemplate->findPartialSpecialization(Args: CanonicalConverted, TPL: InstParams, |
4272 | InsertPos); |
4273 | |
4274 | // Build the canonical type that describes the converted template |
4275 | // arguments of the class template partial specialization. |
4276 | QualType CanonType = SemaRef.Context.getTemplateSpecializationType( |
4277 | T: TemplateName(ClassTemplate), Args: CanonicalConverted); |
4278 | |
4279 | // Create the class template partial specialization declaration. |
4280 | ClassTemplatePartialSpecializationDecl *InstPartialSpec = |
4281 | ClassTemplatePartialSpecializationDecl::Create( |
4282 | Context&: SemaRef.Context, TK: PartialSpec->getTagKind(), DC: Owner, |
4283 | StartLoc: PartialSpec->getBeginLoc(), IdLoc: PartialSpec->getLocation(), Params: InstParams, |
4284 | SpecializedTemplate: ClassTemplate, Args: CanonicalConverted, CanonInjectedType: CanonType, |
4285 | /*PrevDecl=*/nullptr); |
4286 | |
4287 | InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs); |
4288 | |
4289 | // Substitute the nested name specifier, if any. |
4290 | if (SubstQualifier(OldDecl: PartialSpec, NewDecl: InstPartialSpec)) |
4291 | return nullptr; |
4292 | |
4293 | InstPartialSpec->setInstantiatedFromMember(PartialSpec); |
4294 | |
4295 | if (PrevDecl) { |
4296 | // We've already seen a partial specialization with the same template |
4297 | // parameters and template arguments. This can happen, for example, when |
4298 | // substituting the outer template arguments ends up causing two |
4299 | // class template partial specializations of a member class template |
4300 | // to have identical forms, e.g., |
4301 | // |
4302 | // template<typename T, typename U> |
4303 | // struct Outer { |
4304 | // template<typename X, typename Y> struct Inner; |
4305 | // template<typename Y> struct Inner<T, Y>; |
4306 | // template<typename Y> struct Inner<U, Y>; |
4307 | // }; |
4308 | // |
4309 | // Outer<int, int> outer; // error: the partial specializations of Inner |
4310 | // // have the same signature. |
4311 | SemaRef.Diag(Loc: InstPartialSpec->getLocation(), |
4312 | DiagID: diag::err_partial_spec_redeclared) |
4313 | << InstPartialSpec; |
4314 | SemaRef.Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_prev_partial_spec_here) |
4315 | << SemaRef.Context.getTypeDeclType(Decl: PrevDecl); |
4316 | return nullptr; |
4317 | } |
4318 | |
4319 | // Check the completed partial specialization. |
4320 | SemaRef.CheckTemplatePartialSpecialization(Partial: InstPartialSpec); |
4321 | |
4322 | // Add this partial specialization to the set of class template partial |
4323 | // specializations. |
4324 | ClassTemplate->AddPartialSpecialization(D: InstPartialSpec, |
4325 | /*InsertPos=*/nullptr); |
4326 | return InstPartialSpec; |
4327 | } |
4328 | |
4329 | /// Instantiate the declaration of a variable template partial |
4330 | /// specialization. |
4331 | /// |
4332 | /// \param VarTemplate the (instantiated) variable template that is partially |
4333 | /// specialized by the instantiation of \p PartialSpec. |
4334 | /// |
4335 | /// \param PartialSpec the (uninstantiated) variable template partial |
4336 | /// specialization that we are instantiating. |
4337 | /// |
4338 | /// \returns The instantiated partial specialization, if successful; otherwise, |
4339 | /// NULL to indicate an error. |
4340 | VarTemplatePartialSpecializationDecl * |
4341 | TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( |
4342 | VarTemplateDecl *VarTemplate, |
4343 | VarTemplatePartialSpecializationDecl *PartialSpec) { |
4344 | // Create a local instantiation scope for this variable template partial |
4345 | // specialization, which will contain the instantiations of the template |
4346 | // parameters. |
4347 | LocalInstantiationScope Scope(SemaRef); |
4348 | |
4349 | // Substitute into the template parameters of the variable template partial |
4350 | // specialization. |
4351 | TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); |
4352 | TemplateParameterList *InstParams = SubstTemplateParams(L: TempParams); |
4353 | if (!InstParams) |
4354 | return nullptr; |
4355 | |
4356 | // Substitute into the template arguments of the variable template partial |
4357 | // specialization. |
4358 | const ASTTemplateArgumentListInfo *TemplArgInfo |
4359 | = PartialSpec->getTemplateArgsAsWritten(); |
4360 | TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, |
4361 | TemplArgInfo->RAngleLoc); |
4362 | if (SemaRef.SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs, |
4363 | Outputs&: InstTemplateArgs)) |
4364 | return nullptr; |
4365 | |
4366 | // Check that the template argument list is well-formed for this |
4367 | // class template. |
4368 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
4369 | if (SemaRef.CheckTemplateArgumentList( |
4370 | Template: VarTemplate, TemplateLoc: PartialSpec->getLocation(), TemplateArgs&: InstTemplateArgs, |
4371 | /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted)) |
4372 | return nullptr; |
4373 | |
4374 | // Check these arguments are valid for a template partial specialization. |
4375 | if (SemaRef.CheckTemplatePartialSpecializationArgs( |
4376 | Loc: PartialSpec->getLocation(), PrimaryTemplate: VarTemplate, NumExplicitArgs: InstTemplateArgs.size(), |
4377 | Args: CanonicalConverted)) |
4378 | return nullptr; |
4379 | |
4380 | // Figure out where to insert this variable template partial specialization |
4381 | // in the member template's set of variable template partial specializations. |
4382 | void *InsertPos = nullptr; |
4383 | VarTemplateSpecializationDecl *PrevDecl = |
4384 | VarTemplate->findPartialSpecialization(Args: CanonicalConverted, TPL: InstParams, |
4385 | InsertPos); |
4386 | |
4387 | // Do substitution on the type of the declaration |
4388 | TypeSourceInfo *DI = SemaRef.SubstType( |
4389 | T: PartialSpec->getTypeSourceInfo(), TemplateArgs, |
4390 | Loc: PartialSpec->getTypeSpecStartLoc(), Entity: PartialSpec->getDeclName()); |
4391 | if (!DI) |
4392 | return nullptr; |
4393 | |
4394 | if (DI->getType()->isFunctionType()) { |
4395 | SemaRef.Diag(Loc: PartialSpec->getLocation(), |
4396 | DiagID: diag::err_variable_instantiates_to_function) |
4397 | << PartialSpec->isStaticDataMember() << DI->getType(); |
4398 | return nullptr; |
4399 | } |
4400 | |
4401 | // Create the variable template partial specialization declaration. |
4402 | VarTemplatePartialSpecializationDecl *InstPartialSpec = |
4403 | VarTemplatePartialSpecializationDecl::Create( |
4404 | Context&: SemaRef.Context, DC: Owner, StartLoc: PartialSpec->getInnerLocStart(), |
4405 | IdLoc: PartialSpec->getLocation(), Params: InstParams, SpecializedTemplate: VarTemplate, T: DI->getType(), |
4406 | TInfo: DI, S: PartialSpec->getStorageClass(), Args: CanonicalConverted); |
4407 | |
4408 | InstPartialSpec->setTemplateArgsAsWritten(InstTemplateArgs); |
4409 | |
4410 | // Substitute the nested name specifier, if any. |
4411 | if (SubstQualifier(OldDecl: PartialSpec, NewDecl: InstPartialSpec)) |
4412 | return nullptr; |
4413 | |
4414 | InstPartialSpec->setInstantiatedFromMember(PartialSpec); |
4415 | |
4416 | if (PrevDecl) { |
4417 | // We've already seen a partial specialization with the same template |
4418 | // parameters and template arguments. This can happen, for example, when |
4419 | // substituting the outer template arguments ends up causing two |
4420 | // variable template partial specializations of a member variable template |
4421 | // to have identical forms, e.g., |
4422 | // |
4423 | // template<typename T, typename U> |
4424 | // struct Outer { |
4425 | // template<typename X, typename Y> pair<X,Y> p; |
4426 | // template<typename Y> pair<T, Y> p; |
4427 | // template<typename Y> pair<U, Y> p; |
4428 | // }; |
4429 | // |
4430 | // Outer<int, int> outer; // error: the partial specializations of Inner |
4431 | // // have the same signature. |
4432 | SemaRef.Diag(Loc: PartialSpec->getLocation(), |
4433 | DiagID: diag::err_var_partial_spec_redeclared) |
4434 | << InstPartialSpec; |
4435 | SemaRef.Diag(Loc: PrevDecl->getLocation(), |
4436 | DiagID: diag::note_var_prev_partial_spec_here); |
4437 | return nullptr; |
4438 | } |
4439 | // Check the completed partial specialization. |
4440 | SemaRef.CheckTemplatePartialSpecialization(Partial: InstPartialSpec); |
4441 | |
4442 | // Add this partial specialization to the set of variable template partial |
4443 | // specializations. The instantiation of the initializer is not necessary. |
4444 | VarTemplate->AddPartialSpecialization(D: InstPartialSpec, /*InsertPos=*/nullptr); |
4445 | |
4446 | SemaRef.BuildVariableInstantiation(NewVar: InstPartialSpec, OldVar: PartialSpec, TemplateArgs, |
4447 | LateAttrs, Owner, StartingScope); |
4448 | |
4449 | return InstPartialSpec; |
4450 | } |
4451 | |
4452 | TypeSourceInfo* |
4453 | TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, |
4454 | SmallVectorImpl<ParmVarDecl *> &Params) { |
4455 | TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); |
4456 | assert(OldTInfo && "substituting function without type source info" ); |
4457 | assert(Params.empty() && "parameter vector is non-empty at start" ); |
4458 | |
4459 | CXXRecordDecl *ThisContext = nullptr; |
4460 | Qualifiers ThisTypeQuals; |
4461 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) { |
4462 | ThisContext = cast<CXXRecordDecl>(Val: Owner); |
4463 | ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers(); |
4464 | } |
4465 | |
4466 | TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType( |
4467 | T: OldTInfo, TemplateArgs, Loc: D->getTypeSpecStartLoc(), Entity: D->getDeclName(), |
4468 | ThisContext, ThisTypeQuals, EvaluateConstraints); |
4469 | if (!NewTInfo) |
4470 | return nullptr; |
4471 | |
4472 | TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); |
4473 | if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { |
4474 | if (NewTInfo != OldTInfo) { |
4475 | // Get parameters from the new type info. |
4476 | TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); |
4477 | FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); |
4478 | unsigned NewIdx = 0; |
4479 | for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); |
4480 | OldIdx != NumOldParams; ++OldIdx) { |
4481 | ParmVarDecl *OldParam = OldProtoLoc.getParam(i: OldIdx); |
4482 | if (!OldParam) |
4483 | return nullptr; |
4484 | |
4485 | LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; |
4486 | |
4487 | std::optional<unsigned> NumArgumentsInExpansion; |
4488 | if (OldParam->isParameterPack()) |
4489 | NumArgumentsInExpansion = |
4490 | SemaRef.getNumArgumentsInExpansion(T: OldParam->getType(), |
4491 | TemplateArgs); |
4492 | if (!NumArgumentsInExpansion) { |
4493 | // Simple case: normal parameter, or a parameter pack that's |
4494 | // instantiated to a (still-dependent) parameter pack. |
4495 | ParmVarDecl *NewParam = NewProtoLoc.getParam(i: NewIdx++); |
4496 | Params.push_back(Elt: NewParam); |
4497 | Scope->InstantiatedLocal(D: OldParam, Inst: NewParam); |
4498 | } else { |
4499 | // Parameter pack expansion: make the instantiation an argument pack. |
4500 | Scope->MakeInstantiatedLocalArgPack(D: OldParam); |
4501 | for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { |
4502 | ParmVarDecl *NewParam = NewProtoLoc.getParam(i: NewIdx++); |
4503 | Params.push_back(Elt: NewParam); |
4504 | Scope->InstantiatedLocalPackArg(D: OldParam, Inst: NewParam); |
4505 | } |
4506 | } |
4507 | } |
4508 | } else { |
4509 | // The function type itself was not dependent and therefore no |
4510 | // substitution occurred. However, we still need to instantiate |
4511 | // the function parameters themselves. |
4512 | const FunctionProtoType *OldProto = |
4513 | cast<FunctionProtoType>(Val: OldProtoLoc.getType()); |
4514 | for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; |
4515 | ++i) { |
4516 | ParmVarDecl *OldParam = OldProtoLoc.getParam(i); |
4517 | if (!OldParam) { |
4518 | Params.push_back(Elt: SemaRef.BuildParmVarDeclForTypedef( |
4519 | DC: D, Loc: D->getLocation(), T: OldProto->getParamType(i))); |
4520 | continue; |
4521 | } |
4522 | |
4523 | ParmVarDecl *Parm = |
4524 | cast_or_null<ParmVarDecl>(Val: VisitParmVarDecl(D: OldParam)); |
4525 | if (!Parm) |
4526 | return nullptr; |
4527 | Params.push_back(Elt: Parm); |
4528 | } |
4529 | } |
4530 | } else { |
4531 | // If the type of this function, after ignoring parentheses, is not |
4532 | // *directly* a function type, then we're instantiating a function that |
4533 | // was declared via a typedef or with attributes, e.g., |
4534 | // |
4535 | // typedef int functype(int, int); |
4536 | // functype func; |
4537 | // int __cdecl meth(int, int); |
4538 | // |
4539 | // In this case, we'll just go instantiate the ParmVarDecls that we |
4540 | // synthesized in the method declaration. |
4541 | SmallVector<QualType, 4> ParamTypes; |
4542 | Sema::ExtParameterInfoBuilder ExtParamInfos; |
4543 | if (SemaRef.SubstParmTypes(Loc: D->getLocation(), Params: D->parameters(), ExtParamInfos: nullptr, |
4544 | TemplateArgs, ParamTypes, OutParams: &Params, |
4545 | ParamInfos&: ExtParamInfos)) |
4546 | return nullptr; |
4547 | } |
4548 | |
4549 | return NewTInfo; |
4550 | } |
4551 | |
4552 | void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function, |
4553 | const FunctionDecl *PatternDecl, |
4554 | LocalInstantiationScope &Scope) { |
4555 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: getFunctionScopes().back()); |
4556 | |
4557 | for (auto *decl : PatternDecl->decls()) { |
4558 | if (!isa<VarDecl>(Val: decl) || isa<ParmVarDecl>(Val: decl)) |
4559 | continue; |
4560 | |
4561 | VarDecl *VD = cast<VarDecl>(Val: decl); |
4562 | IdentifierInfo *II = VD->getIdentifier(); |
4563 | |
4564 | auto it = llvm::find_if(Range: Function->decls(), P: [&](Decl *inst) { |
4565 | VarDecl *InstVD = dyn_cast<VarDecl>(Val: inst); |
4566 | return InstVD && InstVD->isLocalVarDecl() && |
4567 | InstVD->getIdentifier() == II; |
4568 | }); |
4569 | |
4570 | if (it == Function->decls().end()) |
4571 | continue; |
4572 | |
4573 | Scope.InstantiatedLocal(D: VD, Inst: *it); |
4574 | LSI->addCapture(Var: cast<VarDecl>(Val: *it), /*isBlock=*/false, /*isByref=*/false, |
4575 | /*isNested=*/false, Loc: VD->getLocation(), EllipsisLoc: SourceLocation(), |
4576 | CaptureType: VD->getType(), /*Invalid=*/false); |
4577 | } |
4578 | } |
4579 | |
4580 | bool Sema::addInstantiatedParametersToScope( |
4581 | FunctionDecl *Function, const FunctionDecl *PatternDecl, |
4582 | LocalInstantiationScope &Scope, |
4583 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
4584 | unsigned FParamIdx = 0; |
4585 | for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { |
4586 | const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(i: I); |
4587 | if (!PatternParam->isParameterPack()) { |
4588 | // Simple case: not a parameter pack. |
4589 | assert(FParamIdx < Function->getNumParams()); |
4590 | ParmVarDecl *FunctionParam = Function->getParamDecl(i: FParamIdx); |
4591 | FunctionParam->setDeclName(PatternParam->getDeclName()); |
4592 | // If the parameter's type is not dependent, update it to match the type |
4593 | // in the pattern. They can differ in top-level cv-qualifiers, and we want |
4594 | // the pattern's type here. If the type is dependent, they can't differ, |
4595 | // per core issue 1668. Substitute into the type from the pattern, in case |
4596 | // it's instantiation-dependent. |
4597 | // FIXME: Updating the type to work around this is at best fragile. |
4598 | if (!PatternDecl->getType()->isDependentType()) { |
4599 | QualType T = SubstType(T: PatternParam->getType(), TemplateArgs, |
4600 | Loc: FunctionParam->getLocation(), |
4601 | Entity: FunctionParam->getDeclName()); |
4602 | if (T.isNull()) |
4603 | return true; |
4604 | FunctionParam->setType(T); |
4605 | } |
4606 | |
4607 | Scope.InstantiatedLocal(D: PatternParam, Inst: FunctionParam); |
4608 | ++FParamIdx; |
4609 | continue; |
4610 | } |
4611 | |
4612 | // Expand the parameter pack. |
4613 | Scope.MakeInstantiatedLocalArgPack(D: PatternParam); |
4614 | std::optional<unsigned> NumArgumentsInExpansion = |
4615 | getNumArgumentsInExpansion(T: PatternParam->getType(), TemplateArgs); |
4616 | if (NumArgumentsInExpansion) { |
4617 | QualType PatternType = |
4618 | PatternParam->getType()->castAs<PackExpansionType>()->getPattern(); |
4619 | for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { |
4620 | ParmVarDecl *FunctionParam = Function->getParamDecl(i: FParamIdx); |
4621 | FunctionParam->setDeclName(PatternParam->getDeclName()); |
4622 | if (!PatternDecl->getType()->isDependentType()) { |
4623 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg); |
4624 | QualType T = |
4625 | SubstType(T: PatternType, TemplateArgs, Loc: FunctionParam->getLocation(), |
4626 | Entity: FunctionParam->getDeclName()); |
4627 | if (T.isNull()) |
4628 | return true; |
4629 | FunctionParam->setType(T); |
4630 | } |
4631 | |
4632 | Scope.InstantiatedLocalPackArg(D: PatternParam, Inst: FunctionParam); |
4633 | ++FParamIdx; |
4634 | } |
4635 | } |
4636 | } |
4637 | |
4638 | return false; |
4639 | } |
4640 | |
4641 | bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, |
4642 | ParmVarDecl *Param) { |
4643 | assert(Param->hasUninstantiatedDefaultArg()); |
4644 | |
4645 | // Instantiate the expression. |
4646 | // |
4647 | // FIXME: Pass in a correct Pattern argument, otherwise |
4648 | // getTemplateInstantiationArgs uses the lexical context of FD, e.g. |
4649 | // |
4650 | // template<typename T> |
4651 | // struct A { |
4652 | // static int FooImpl(); |
4653 | // |
4654 | // template<typename Tp> |
4655 | // // bug: default argument A<T>::FooImpl() is evaluated with 2-level |
4656 | // // template argument list [[T], [Tp]], should be [[Tp]]. |
4657 | // friend A<Tp> Foo(int a); |
4658 | // }; |
4659 | // |
4660 | // template<typename T> |
4661 | // A<T> Foo(int a = A<T>::FooImpl()); |
4662 | MultiLevelTemplateArgumentList TemplateArgs = |
4663 | getTemplateInstantiationArgs(D: FD, DC: FD->getLexicalDeclContext(), |
4664 | /*Final=*/false, /*Innermost=*/std::nullopt, |
4665 | /*RelativeToPrimary=*/true); |
4666 | |
4667 | if (SubstDefaultArgument(Loc: CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true)) |
4668 | return true; |
4669 | |
4670 | if (ASTMutationListener *L = getASTMutationListener()) |
4671 | L->DefaultArgumentInstantiated(D: Param); |
4672 | |
4673 | return false; |
4674 | } |
4675 | |
4676 | void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, |
4677 | FunctionDecl *Decl) { |
4678 | const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); |
4679 | if (Proto->getExceptionSpecType() != EST_Uninstantiated) |
4680 | return; |
4681 | |
4682 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, |
4683 | InstantiatingTemplate::ExceptionSpecification()); |
4684 | if (Inst.isInvalid()) { |
4685 | // We hit the instantiation depth limit. Clear the exception specification |
4686 | // so that our callers don't have to cope with EST_Uninstantiated. |
4687 | UpdateExceptionSpec(FD: Decl, ESI: EST_None); |
4688 | return; |
4689 | } |
4690 | if (Inst.isAlreadyInstantiating()) { |
4691 | // This exception specification indirectly depends on itself. Reject. |
4692 | // FIXME: Corresponding rule in the standard? |
4693 | Diag(Loc: PointOfInstantiation, DiagID: diag::err_exception_spec_cycle) << Decl; |
4694 | UpdateExceptionSpec(FD: Decl, ESI: EST_None); |
4695 | return; |
4696 | } |
4697 | |
4698 | // Enter the scope of this instantiation. We don't use |
4699 | // PushDeclContext because we don't have a scope. |
4700 | Sema::ContextRAII savedContext(*this, Decl); |
4701 | LocalInstantiationScope Scope(*this); |
4702 | |
4703 | MultiLevelTemplateArgumentList TemplateArgs = |
4704 | getTemplateInstantiationArgs(D: Decl, DC: Decl->getLexicalDeclContext(), |
4705 | /*Final=*/false, /*Innermost=*/std::nullopt, |
4706 | /*RelativeToPrimary*/ true); |
4707 | |
4708 | // FIXME: We can't use getTemplateInstantiationPattern(false) in general |
4709 | // here, because for a non-defining friend declaration in a class template, |
4710 | // we don't store enough information to map back to the friend declaration in |
4711 | // the template. |
4712 | FunctionDecl *Template = Proto->getExceptionSpecTemplate(); |
4713 | if (addInstantiatedParametersToScope(Function: Decl, PatternDecl: Template, Scope, TemplateArgs)) { |
4714 | UpdateExceptionSpec(FD: Decl, ESI: EST_None); |
4715 | return; |
4716 | } |
4717 | |
4718 | // The noexcept specification could reference any lambda captures. Ensure |
4719 | // those are added to the LocalInstantiationScope. |
4720 | LambdaScopeForCallOperatorInstantiationRAII PushLambdaCaptures( |
4721 | *this, Decl, TemplateArgs, Scope, |
4722 | /*ShouldAddDeclsFromParentScope=*/false); |
4723 | |
4724 | SubstExceptionSpec(New: Decl, Proto: Template->getType()->castAs<FunctionProtoType>(), |
4725 | Args: TemplateArgs); |
4726 | } |
4727 | |
4728 | /// Initializes the common fields of an instantiation function |
4729 | /// declaration (New) from the corresponding fields of its template (Tmpl). |
4730 | /// |
4731 | /// \returns true if there was an error |
4732 | bool |
4733 | TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, |
4734 | FunctionDecl *Tmpl) { |
4735 | New->setImplicit(Tmpl->isImplicit()); |
4736 | |
4737 | // Forward the mangling number from the template to the instantiated decl. |
4738 | SemaRef.Context.setManglingNumber(ND: New, |
4739 | Number: SemaRef.Context.getManglingNumber(ND: Tmpl)); |
4740 | |
4741 | // If we are performing substituting explicitly-specified template arguments |
4742 | // or deduced template arguments into a function template and we reach this |
4743 | // point, we are now past the point where SFINAE applies and have committed |
4744 | // to keeping the new function template specialization. We therefore |
4745 | // convert the active template instantiation for the function template |
4746 | // into a template instantiation for this specific function template |
4747 | // specialization, which is not a SFINAE context, so that we diagnose any |
4748 | // further errors in the declaration itself. |
4749 | // |
4750 | // FIXME: This is a hack. |
4751 | typedef Sema::CodeSynthesisContext ActiveInstType; |
4752 | ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back(); |
4753 | if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || |
4754 | ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { |
4755 | if (isa<FunctionTemplateDecl>(Val: ActiveInst.Entity)) { |
4756 | SemaRef.InstantiatingSpecializations.erase( |
4757 | V: {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind}); |
4758 | atTemplateEnd(Callbacks&: SemaRef.TemplateInstCallbacks, TheSema: SemaRef, Inst: ActiveInst); |
4759 | ActiveInst.Kind = ActiveInstType::TemplateInstantiation; |
4760 | ActiveInst.Entity = New; |
4761 | atTemplateBegin(Callbacks&: SemaRef.TemplateInstCallbacks, TheSema: SemaRef, Inst: ActiveInst); |
4762 | } |
4763 | } |
4764 | |
4765 | const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); |
4766 | assert(Proto && "Function template without prototype?" ); |
4767 | |
4768 | if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { |
4769 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); |
4770 | |
4771 | // DR1330: In C++11, defer instantiation of a non-trivial |
4772 | // exception specification. |
4773 | // DR1484: Local classes and their members are instantiated along with the |
4774 | // containing function. |
4775 | if (SemaRef.getLangOpts().CPlusPlus11 && |
4776 | EPI.ExceptionSpec.Type != EST_None && |
4777 | EPI.ExceptionSpec.Type != EST_DynamicNone && |
4778 | EPI.ExceptionSpec.Type != EST_BasicNoexcept && |
4779 | !Tmpl->isInLocalScopeForInstantiation()) { |
4780 | FunctionDecl *ExceptionSpecTemplate = Tmpl; |
4781 | if (EPI.ExceptionSpec.Type == EST_Uninstantiated) |
4782 | ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate; |
4783 | ExceptionSpecificationType NewEST = EST_Uninstantiated; |
4784 | if (EPI.ExceptionSpec.Type == EST_Unevaluated) |
4785 | NewEST = EST_Unevaluated; |
4786 | |
4787 | // Mark the function has having an uninstantiated exception specification. |
4788 | const FunctionProtoType *NewProto |
4789 | = New->getType()->getAs<FunctionProtoType>(); |
4790 | assert(NewProto && "Template instantiation without function prototype?" ); |
4791 | EPI = NewProto->getExtProtoInfo(); |
4792 | EPI.ExceptionSpec.Type = NewEST; |
4793 | EPI.ExceptionSpec.SourceDecl = New; |
4794 | EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate; |
4795 | New->setType(SemaRef.Context.getFunctionType( |
4796 | ResultTy: NewProto->getReturnType(), Args: NewProto->getParamTypes(), EPI)); |
4797 | } else { |
4798 | Sema::ContextRAII SwitchContext(SemaRef, New); |
4799 | SemaRef.SubstExceptionSpec(New, Proto, Args: TemplateArgs); |
4800 | } |
4801 | } |
4802 | |
4803 | // Get the definition. Leaves the variable unchanged if undefined. |
4804 | const FunctionDecl *Definition = Tmpl; |
4805 | Tmpl->isDefined(Definition); |
4806 | |
4807 | SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: Definition, New, |
4808 | LateAttrs, OuterMostScope: StartingScope); |
4809 | |
4810 | return false; |
4811 | } |
4812 | |
4813 | /// Initializes common fields of an instantiated method |
4814 | /// declaration (New) from the corresponding fields of its template |
4815 | /// (Tmpl). |
4816 | /// |
4817 | /// \returns true if there was an error |
4818 | bool |
4819 | TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, |
4820 | CXXMethodDecl *Tmpl) { |
4821 | if (InitFunctionInstantiation(New, Tmpl)) |
4822 | return true; |
4823 | |
4824 | if (isa<CXXDestructorDecl>(Val: New) && SemaRef.getLangOpts().CPlusPlus11) |
4825 | SemaRef.AdjustDestructorExceptionSpec(Destructor: cast<CXXDestructorDecl>(Val: New)); |
4826 | |
4827 | New->setAccess(Tmpl->getAccess()); |
4828 | if (Tmpl->isVirtualAsWritten()) |
4829 | New->setVirtualAsWritten(true); |
4830 | |
4831 | // FIXME: New needs a pointer to Tmpl |
4832 | return false; |
4833 | } |
4834 | |
4835 | bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New, |
4836 | FunctionDecl *Tmpl) { |
4837 | // Transfer across any unqualified lookups. |
4838 | if (auto *DFI = Tmpl->getDefalutedOrDeletedInfo()) { |
4839 | SmallVector<DeclAccessPair, 32> Lookups; |
4840 | Lookups.reserve(N: DFI->getUnqualifiedLookups().size()); |
4841 | bool AnyChanged = false; |
4842 | for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) { |
4843 | NamedDecl *D = SemaRef.FindInstantiatedDecl(Loc: New->getLocation(), |
4844 | D: DA.getDecl(), TemplateArgs); |
4845 | if (!D) |
4846 | return true; |
4847 | AnyChanged |= (D != DA.getDecl()); |
4848 | Lookups.push_back(Elt: DeclAccessPair::make(D, AS: DA.getAccess())); |
4849 | } |
4850 | |
4851 | // It's unlikely that substitution will change any declarations. Don't |
4852 | // store an unnecessary copy in that case. |
4853 | New->setDefaultedOrDeletedInfo( |
4854 | AnyChanged ? FunctionDecl::DefaultedOrDeletedFunctionInfo::Create( |
4855 | Context&: SemaRef.Context, Lookups) |
4856 | : DFI); |
4857 | } |
4858 | |
4859 | SemaRef.SetDeclDefaulted(dcl: New, DefaultLoc: Tmpl->getLocation()); |
4860 | return false; |
4861 | } |
4862 | |
4863 | FunctionDecl *Sema::InstantiateFunctionDeclaration( |
4864 | FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, |
4865 | SourceLocation Loc, CodeSynthesisContext::SynthesisKind CSC) { |
4866 | FunctionDecl *FD = FTD->getTemplatedDecl(); |
4867 | |
4868 | sema::TemplateDeductionInfo Info(Loc); |
4869 | InstantiatingTemplate Inst(*this, Loc, FTD, Args->asArray(), CSC, Info); |
4870 | if (Inst.isInvalid()) |
4871 | return nullptr; |
4872 | |
4873 | ContextRAII SavedContext(*this, FD); |
4874 | MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(), |
4875 | /*Final=*/false); |
4876 | |
4877 | return cast_or_null<FunctionDecl>(Val: SubstDecl(D: FD, Owner: FD->getParent(), TemplateArgs: MArgs)); |
4878 | } |
4879 | |
4880 | void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, |
4881 | FunctionDecl *Function, |
4882 | bool Recursive, |
4883 | bool DefinitionRequired, |
4884 | bool AtEndOfTU) { |
4885 | if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Val: Function)) |
4886 | return; |
4887 | |
4888 | // Never instantiate an explicit specialization except if it is a class scope |
4889 | // explicit specialization. |
4890 | TemplateSpecializationKind TSK = |
4891 | Function->getTemplateSpecializationKindForInstantiation(); |
4892 | if (TSK == TSK_ExplicitSpecialization) |
4893 | return; |
4894 | |
4895 | // Never implicitly instantiate a builtin; we don't actually need a function |
4896 | // body. |
4897 | if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation && |
4898 | !DefinitionRequired) |
4899 | return; |
4900 | |
4901 | // Don't instantiate a definition if we already have one. |
4902 | const FunctionDecl *ExistingDefn = nullptr; |
4903 | if (Function->isDefined(Definition&: ExistingDefn, |
4904 | /*CheckForPendingFriendDefinition=*/true)) { |
4905 | if (ExistingDefn->isThisDeclarationADefinition()) |
4906 | return; |
4907 | |
4908 | // If we're asked to instantiate a function whose body comes from an |
4909 | // instantiated friend declaration, attach the instantiated body to the |
4910 | // corresponding declaration of the function. |
4911 | assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition()); |
4912 | Function = const_cast<FunctionDecl*>(ExistingDefn); |
4913 | } |
4914 | |
4915 | // Find the function body that we'll be substituting. |
4916 | const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); |
4917 | assert(PatternDecl && "instantiating a non-template" ); |
4918 | |
4919 | const FunctionDecl *PatternDef = PatternDecl->getDefinition(); |
4920 | Stmt *Pattern = nullptr; |
4921 | if (PatternDef) { |
4922 | Pattern = PatternDef->getBody(Definition&: PatternDef); |
4923 | PatternDecl = PatternDef; |
4924 | if (PatternDef->willHaveBody()) |
4925 | PatternDef = nullptr; |
4926 | } |
4927 | |
4928 | // FIXME: We need to track the instantiation stack in order to know which |
4929 | // definitions should be visible within this instantiation. |
4930 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation: Function, |
4931 | InstantiatedFromMember: Function->getInstantiatedFromMemberFunction(), |
4932 | Pattern: PatternDecl, PatternDef, TSK, |
4933 | /*Complain*/DefinitionRequired)) { |
4934 | if (DefinitionRequired) |
4935 | Function->setInvalidDecl(); |
4936 | else if (TSK == TSK_ExplicitInstantiationDefinition || |
4937 | (Function->isConstexpr() && !Recursive)) { |
4938 | // Try again at the end of the translation unit (at which point a |
4939 | // definition will be required). |
4940 | assert(!Recursive); |
4941 | Function->setInstantiationIsPending(true); |
4942 | PendingInstantiations.push_back( |
4943 | x: std::make_pair(x&: Function, y&: PointOfInstantiation)); |
4944 | } else if (TSK == TSK_ImplicitInstantiation) { |
4945 | if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && |
4946 | !getSourceManager().isInSystemHeader(Loc: PatternDecl->getBeginLoc())) { |
4947 | Diag(Loc: PointOfInstantiation, DiagID: diag::warn_func_template_missing) |
4948 | << Function; |
4949 | Diag(Loc: PatternDecl->getLocation(), DiagID: diag::note_forward_template_decl); |
4950 | if (getLangOpts().CPlusPlus11) |
4951 | Diag(Loc: PointOfInstantiation, DiagID: diag::note_inst_declaration_hint) |
4952 | << Function; |
4953 | } |
4954 | } |
4955 | |
4956 | return; |
4957 | } |
4958 | |
4959 | // Postpone late parsed template instantiations. |
4960 | if (PatternDecl->isLateTemplateParsed() && |
4961 | !LateTemplateParser) { |
4962 | Function->setInstantiationIsPending(true); |
4963 | LateParsedInstantiations.push_back( |
4964 | Elt: std::make_pair(x&: Function, y&: PointOfInstantiation)); |
4965 | return; |
4966 | } |
4967 | |
4968 | llvm::TimeTraceScope TimeScope("InstantiateFunction" , [&]() { |
4969 | llvm::TimeTraceMetadata M; |
4970 | llvm::raw_string_ostream OS(M.Detail); |
4971 | Function->getNameForDiagnostic(OS, Policy: getPrintingPolicy(), |
4972 | /*Qualified=*/true); |
4973 | if (llvm::isTimeTraceVerbose()) { |
4974 | auto Loc = SourceMgr.getExpansionLoc(Loc: Function->getLocation()); |
4975 | M.File = SourceMgr.getFilename(SpellingLoc: Loc); |
4976 | M.Line = SourceMgr.getExpansionLineNumber(Loc); |
4977 | } |
4978 | return M; |
4979 | }); |
4980 | |
4981 | // If we're performing recursive template instantiation, create our own |
4982 | // queue of pending implicit instantiations that we will instantiate later, |
4983 | // while we're still within our own instantiation context. |
4984 | // This has to happen before LateTemplateParser below is called, so that |
4985 | // it marks vtables used in late parsed templates as used. |
4986 | GlobalEagerInstantiationScope GlobalInstantiations(*this, |
4987 | /*Enabled=*/Recursive); |
4988 | LocalEagerInstantiationScope LocalInstantiations(*this); |
4989 | |
4990 | // Call the LateTemplateParser callback if there is a need to late parse |
4991 | // a templated function definition. |
4992 | if (!Pattern && PatternDecl->isLateTemplateParsed() && |
4993 | LateTemplateParser) { |
4994 | // FIXME: Optimize to allow individual templates to be deserialized. |
4995 | if (PatternDecl->isFromASTFile()) |
4996 | ExternalSource->ReadLateParsedTemplates(LPTMap&: LateParsedTemplateMap); |
4997 | |
4998 | auto LPTIter = LateParsedTemplateMap.find(Key: PatternDecl); |
4999 | assert(LPTIter != LateParsedTemplateMap.end() && |
5000 | "missing LateParsedTemplate" ); |
5001 | LateTemplateParser(OpaqueParser, *LPTIter->second); |
5002 | Pattern = PatternDecl->getBody(Definition&: PatternDecl); |
5003 | updateAttrsForLateParsedTemplate(Pattern: PatternDecl, Inst: Function); |
5004 | } |
5005 | |
5006 | // Note, we should never try to instantiate a deleted function template. |
5007 | assert((Pattern || PatternDecl->isDefaulted() || |
5008 | PatternDecl->hasSkippedBody()) && |
5009 | "unexpected kind of function template definition" ); |
5010 | |
5011 | // C++1y [temp.explicit]p10: |
5012 | // Except for inline functions, declarations with types deduced from their |
5013 | // initializer or return value, and class template specializations, other |
5014 | // explicit instantiation declarations have the effect of suppressing the |
5015 | // implicit instantiation of the entity to which they refer. |
5016 | if (TSK == TSK_ExplicitInstantiationDeclaration && |
5017 | !PatternDecl->isInlined() && |
5018 | !PatternDecl->getReturnType()->getContainedAutoType()) |
5019 | return; |
5020 | |
5021 | if (PatternDecl->isInlined()) { |
5022 | // Function, and all later redeclarations of it (from imported modules, |
5023 | // for instance), are now implicitly inline. |
5024 | for (auto *D = Function->getMostRecentDecl(); /**/; |
5025 | D = D->getPreviousDecl()) { |
5026 | D->setImplicitlyInline(); |
5027 | if (D == Function) |
5028 | break; |
5029 | } |
5030 | } |
5031 | |
5032 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); |
5033 | if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) |
5034 | return; |
5035 | PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(), |
5036 | "instantiating function definition" ); |
5037 | |
5038 | // The instantiation is visible here, even if it was first declared in an |
5039 | // unimported module. |
5040 | Function->setVisibleDespiteOwningModule(); |
5041 | |
5042 | // Copy the source locations from the pattern. |
5043 | Function->setLocation(PatternDecl->getLocation()); |
5044 | Function->setInnerLocStart(PatternDecl->getInnerLocStart()); |
5045 | Function->setRangeEnd(PatternDecl->getEndLoc()); |
5046 | Function->setDeclarationNameLoc(PatternDecl->getNameInfo().getInfo()); |
5047 | |
5048 | EnterExpressionEvaluationContext EvalContext( |
5049 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
5050 | |
5051 | Qualifiers ThisTypeQuals; |
5052 | CXXRecordDecl *ThisContext = nullptr; |
5053 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: Function)) { |
5054 | ThisContext = Method->getParent(); |
5055 | ThisTypeQuals = Method->getMethodQualifiers(); |
5056 | } |
5057 | CXXThisScopeRAII ThisScope(*this, ThisContext, ThisTypeQuals); |
5058 | |
5059 | // Introduce a new scope where local variable instantiations will be |
5060 | // recorded, unless we're actually a member function within a local |
5061 | // class, in which case we need to merge our results with the parent |
5062 | // scope (of the enclosing function). The exception is instantiating |
5063 | // a function template specialization, since the template to be |
5064 | // instantiated already has references to locals properly substituted. |
5065 | bool MergeWithParentScope = false; |
5066 | if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Val: Function->getDeclContext())) |
5067 | MergeWithParentScope = |
5068 | Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization(); |
5069 | |
5070 | LocalInstantiationScope Scope(*this, MergeWithParentScope); |
5071 | auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() { |
5072 | // Special members might get their TypeSourceInfo set up w.r.t the |
5073 | // PatternDecl context, in which case parameters could still be pointing |
5074 | // back to the original class, make sure arguments are bound to the |
5075 | // instantiated record instead. |
5076 | assert(PatternDecl->isDefaulted() && |
5077 | "Special member needs to be defaulted" ); |
5078 | auto PatternSM = getDefaultedFunctionKind(FD: PatternDecl).asSpecialMember(); |
5079 | if (!(PatternSM == CXXSpecialMemberKind::CopyConstructor || |
5080 | PatternSM == CXXSpecialMemberKind::CopyAssignment || |
5081 | PatternSM == CXXSpecialMemberKind::MoveConstructor || |
5082 | PatternSM == CXXSpecialMemberKind::MoveAssignment)) |
5083 | return; |
5084 | |
5085 | auto *NewRec = dyn_cast<CXXRecordDecl>(Val: Function->getDeclContext()); |
5086 | const auto *PatternRec = |
5087 | dyn_cast<CXXRecordDecl>(Val: PatternDecl->getDeclContext()); |
5088 | if (!NewRec || !PatternRec) |
5089 | return; |
5090 | if (!PatternRec->isLambda()) |
5091 | return; |
5092 | |
5093 | struct SpecialMemberTypeInfoRebuilder |
5094 | : TreeTransform<SpecialMemberTypeInfoRebuilder> { |
5095 | using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>; |
5096 | const CXXRecordDecl *OldDecl; |
5097 | CXXRecordDecl *NewDecl; |
5098 | |
5099 | SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O, |
5100 | CXXRecordDecl *N) |
5101 | : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {} |
5102 | |
5103 | bool TransformExceptionSpec(SourceLocation Loc, |
5104 | FunctionProtoType::ExceptionSpecInfo &ESI, |
5105 | SmallVectorImpl<QualType> &Exceptions, |
5106 | bool &Changed) { |
5107 | return false; |
5108 | } |
5109 | |
5110 | QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) { |
5111 | const RecordType *T = TL.getTypePtr(); |
5112 | RecordDecl *Record = cast_or_null<RecordDecl>( |
5113 | Val: getDerived().TransformDecl(Loc: TL.getNameLoc(), D: T->getDecl())); |
5114 | if (Record != OldDecl) |
5115 | return Base::TransformRecordType(TLB, T: TL); |
5116 | |
5117 | QualType Result = getDerived().RebuildRecordType(Record: NewDecl); |
5118 | if (Result.isNull()) |
5119 | return QualType(); |
5120 | |
5121 | RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(T: Result); |
5122 | NewTL.setNameLoc(TL.getNameLoc()); |
5123 | return Result; |
5124 | } |
5125 | } IR{*this, PatternRec, NewRec}; |
5126 | |
5127 | TypeSourceInfo *NewSI = IR.TransformType(DI: Function->getTypeSourceInfo()); |
5128 | assert(NewSI && "Type Transform failed?" ); |
5129 | Function->setType(NewSI->getType()); |
5130 | Function->setTypeSourceInfo(NewSI); |
5131 | |
5132 | ParmVarDecl *Parm = Function->getParamDecl(i: 0); |
5133 | TypeSourceInfo *NewParmSI = IR.TransformType(DI: Parm->getTypeSourceInfo()); |
5134 | assert(NewParmSI && "Type transformation failed." ); |
5135 | Parm->setType(NewParmSI->getType()); |
5136 | Parm->setTypeSourceInfo(NewParmSI); |
5137 | }; |
5138 | |
5139 | if (PatternDecl->isDefaulted()) { |
5140 | RebuildTypeSourceInfoForDefaultSpecialMembers(); |
5141 | SetDeclDefaulted(dcl: Function, DefaultLoc: PatternDecl->getLocation()); |
5142 | } else { |
5143 | MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs( |
5144 | D: Function, DC: Function->getLexicalDeclContext(), /*Final=*/false, |
5145 | /*Innermost=*/std::nullopt, RelativeToPrimary: false, Pattern: PatternDecl); |
5146 | |
5147 | // Substitute into the qualifier; we can get a substitution failure here |
5148 | // through evil use of alias templates. |
5149 | // FIXME: Is CurContext correct for this? Should we go to the (instantiation |
5150 | // of the) lexical context of the pattern? |
5151 | SubstQualifier(SemaRef&: *this, OldDecl: PatternDecl, NewDecl: Function, TemplateArgs); |
5152 | |
5153 | ActOnStartOfFunctionDef(S: nullptr, D: Function); |
5154 | |
5155 | // Enter the scope of this instantiation. We don't use |
5156 | // PushDeclContext because we don't have a scope. |
5157 | Sema::ContextRAII savedContext(*this, Function); |
5158 | |
5159 | FPFeaturesStateRAII SavedFPFeatures(*this); |
5160 | CurFPFeatures = FPOptions(getLangOpts()); |
5161 | FpPragmaStack.CurrentValue = FPOptionsOverride(); |
5162 | |
5163 | if (addInstantiatedParametersToScope(Function, PatternDecl, Scope, |
5164 | TemplateArgs)) |
5165 | return; |
5166 | |
5167 | StmtResult Body; |
5168 | if (PatternDecl->hasSkippedBody()) { |
5169 | ActOnSkippedFunctionBody(Decl: Function); |
5170 | Body = nullptr; |
5171 | } else { |
5172 | if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: Function)) { |
5173 | // If this is a constructor, instantiate the member initializers. |
5174 | InstantiateMemInitializers(New: Ctor, Tmpl: cast<CXXConstructorDecl>(Val: PatternDecl), |
5175 | TemplateArgs); |
5176 | |
5177 | // If this is an MS ABI dllexport default constructor, instantiate any |
5178 | // default arguments. |
5179 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && |
5180 | Ctor->isDefaultConstructor()) { |
5181 | InstantiateDefaultCtorDefaultArgs(Ctor); |
5182 | } |
5183 | } |
5184 | |
5185 | // Instantiate the function body. |
5186 | Body = SubstStmt(S: Pattern, TemplateArgs); |
5187 | |
5188 | if (Body.isInvalid()) |
5189 | Function->setInvalidDecl(); |
5190 | } |
5191 | // FIXME: finishing the function body while in an expression evaluation |
5192 | // context seems wrong. Investigate more. |
5193 | ActOnFinishFunctionBody(Decl: Function, Body: Body.get(), /*IsInstantiation=*/true); |
5194 | |
5195 | PerformDependentDiagnostics(Pattern: PatternDecl, TemplateArgs); |
5196 | |
5197 | if (auto *Listener = getASTMutationListener()) |
5198 | Listener->FunctionDefinitionInstantiated(D: Function); |
5199 | |
5200 | savedContext.pop(); |
5201 | } |
5202 | |
5203 | DeclGroupRef DG(Function); |
5204 | Consumer.HandleTopLevelDecl(D: DG); |
5205 | |
5206 | // This class may have local implicit instantiations that need to be |
5207 | // instantiation within this scope. |
5208 | LocalInstantiations.perform(); |
5209 | Scope.Exit(); |
5210 | GlobalInstantiations.perform(); |
5211 | } |
5212 | |
5213 | VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( |
5214 | VarTemplateDecl *VarTemplate, VarDecl *FromVar, |
5215 | const TemplateArgumentList *PartialSpecArgs, |
5216 | const TemplateArgumentListInfo &TemplateArgsInfo, |
5217 | SmallVectorImpl<TemplateArgument> &Converted, |
5218 | SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs, |
5219 | LocalInstantiationScope *StartingScope) { |
5220 | if (FromVar->isInvalidDecl()) |
5221 | return nullptr; |
5222 | |
5223 | InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); |
5224 | if (Inst.isInvalid()) |
5225 | return nullptr; |
5226 | |
5227 | // Instantiate the first declaration of the variable template: for a partial |
5228 | // specialization of a static data member template, the first declaration may |
5229 | // or may not be the declaration in the class; if it's in the class, we want |
5230 | // to instantiate a member in the class (a declaration), and if it's outside, |
5231 | // we want to instantiate a definition. |
5232 | // |
5233 | // If we're instantiating an explicitly-specialized member template or member |
5234 | // partial specialization, don't do this. The member specialization completely |
5235 | // replaces the original declaration in this case. |
5236 | bool IsMemberSpec = false; |
5237 | MultiLevelTemplateArgumentList MultiLevelList; |
5238 | if (auto *PartialSpec = |
5239 | dyn_cast<VarTemplatePartialSpecializationDecl>(Val: FromVar)) { |
5240 | assert(PartialSpecArgs); |
5241 | IsMemberSpec = PartialSpec->isMemberSpecialization(); |
5242 | MultiLevelList.addOuterTemplateArguments( |
5243 | AssociatedDecl: PartialSpec, Args: PartialSpecArgs->asArray(), /*Final=*/false); |
5244 | } else { |
5245 | assert(VarTemplate == FromVar->getDescribedVarTemplate()); |
5246 | IsMemberSpec = VarTemplate->isMemberSpecialization(); |
5247 | MultiLevelList.addOuterTemplateArguments(AssociatedDecl: VarTemplate, Args: Converted, |
5248 | /*Final=*/false); |
5249 | } |
5250 | if (!IsMemberSpec) |
5251 | FromVar = FromVar->getFirstDecl(); |
5252 | |
5253 | TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), |
5254 | MultiLevelList); |
5255 | |
5256 | // TODO: Set LateAttrs and StartingScope ... |
5257 | |
5258 | return cast_or_null<VarTemplateSpecializationDecl>( |
5259 | Val: Instantiator.VisitVarTemplateSpecializationDecl( |
5260 | VarTemplate, D: FromVar, TemplateArgsInfo, Converted)); |
5261 | } |
5262 | |
5263 | VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( |
5264 | VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, |
5265 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
5266 | assert(PatternDecl->isThisDeclarationADefinition() && |
5267 | "don't have a definition to instantiate from" ); |
5268 | |
5269 | // Do substitution on the type of the declaration |
5270 | TypeSourceInfo *DI = |
5271 | SubstType(T: PatternDecl->getTypeSourceInfo(), TemplateArgs, |
5272 | Loc: PatternDecl->getTypeSpecStartLoc(), Entity: PatternDecl->getDeclName()); |
5273 | if (!DI) |
5274 | return nullptr; |
5275 | |
5276 | // Update the type of this variable template specialization. |
5277 | VarSpec->setType(DI->getType()); |
5278 | |
5279 | // Convert the declaration into a definition now. |
5280 | VarSpec->setCompleteDefinition(); |
5281 | |
5282 | // Instantiate the initializer. |
5283 | InstantiateVariableInitializer(Var: VarSpec, OldVar: PatternDecl, TemplateArgs); |
5284 | |
5285 | if (getLangOpts().OpenCL) |
5286 | deduceOpenCLAddressSpace(decl: VarSpec); |
5287 | |
5288 | return VarSpec; |
5289 | } |
5290 | |
5291 | void Sema::BuildVariableInstantiation( |
5292 | VarDecl *NewVar, VarDecl *OldVar, |
5293 | const MultiLevelTemplateArgumentList &TemplateArgs, |
5294 | LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, |
5295 | LocalInstantiationScope *StartingScope, |
5296 | bool InstantiatingVarTemplate, |
5297 | VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) { |
5298 | // Instantiating a partial specialization to produce a partial |
5299 | // specialization. |
5300 | bool InstantiatingVarTemplatePartialSpec = |
5301 | isa<VarTemplatePartialSpecializationDecl>(Val: OldVar) && |
5302 | isa<VarTemplatePartialSpecializationDecl>(Val: NewVar); |
5303 | // Instantiating from a variable template (or partial specialization) to |
5304 | // produce a variable template specialization. |
5305 | bool InstantiatingSpecFromTemplate = |
5306 | isa<VarTemplateSpecializationDecl>(Val: NewVar) && |
5307 | (OldVar->getDescribedVarTemplate() || |
5308 | isa<VarTemplatePartialSpecializationDecl>(Val: OldVar)); |
5309 | |
5310 | // If we are instantiating a local extern declaration, the |
5311 | // instantiation belongs lexically to the containing function. |
5312 | // If we are instantiating a static data member defined |
5313 | // out-of-line, the instantiation will have the same lexical |
5314 | // context (which will be a namespace scope) as the template. |
5315 | if (OldVar->isLocalExternDecl()) { |
5316 | NewVar->setLocalExternDecl(); |
5317 | NewVar->setLexicalDeclContext(Owner); |
5318 | } else if (OldVar->isOutOfLine()) |
5319 | NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); |
5320 | NewVar->setTSCSpec(OldVar->getTSCSpec()); |
5321 | NewVar->setInitStyle(OldVar->getInitStyle()); |
5322 | NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); |
5323 | NewVar->setObjCForDecl(OldVar->isObjCForDecl()); |
5324 | NewVar->setConstexpr(OldVar->isConstexpr()); |
5325 | NewVar->setInitCapture(OldVar->isInitCapture()); |
5326 | NewVar->setPreviousDeclInSameBlockScope( |
5327 | OldVar->isPreviousDeclInSameBlockScope()); |
5328 | NewVar->setAccess(OldVar->getAccess()); |
5329 | |
5330 | if (!OldVar->isStaticDataMember()) { |
5331 | if (OldVar->isUsed(CheckUsedAttr: false)) |
5332 | NewVar->setIsUsed(); |
5333 | NewVar->setReferenced(OldVar->isReferenced()); |
5334 | } |
5335 | |
5336 | InstantiateAttrs(TemplateArgs, Tmpl: OldVar, New: NewVar, LateAttrs, OuterMostScope: StartingScope); |
5337 | |
5338 | LookupResult Previous( |
5339 | *this, NewVar->getDeclName(), NewVar->getLocation(), |
5340 | NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage |
5341 | : Sema::LookupOrdinaryName, |
5342 | NewVar->isLocalExternDecl() ? RedeclarationKind::ForExternalRedeclaration |
5343 | : forRedeclarationInCurContext()); |
5344 | |
5345 | if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && |
5346 | (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || |
5347 | OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { |
5348 | // We have a previous declaration. Use that one, so we merge with the |
5349 | // right type. |
5350 | if (NamedDecl *NewPrev = FindInstantiatedDecl( |
5351 | Loc: NewVar->getLocation(), D: OldVar->getPreviousDecl(), TemplateArgs)) |
5352 | Previous.addDecl(D: NewPrev); |
5353 | } else if (!isa<VarTemplateSpecializationDecl>(Val: NewVar) && |
5354 | OldVar->hasLinkage()) { |
5355 | LookupQualifiedName(R&: Previous, LookupCtx: NewVar->getDeclContext(), InUnqualifiedLookup: false); |
5356 | } else if (PrevDeclForVarTemplateSpecialization) { |
5357 | Previous.addDecl(D: PrevDeclForVarTemplateSpecialization); |
5358 | } |
5359 | CheckVariableDeclaration(NewVD: NewVar, Previous); |
5360 | |
5361 | if (!InstantiatingVarTemplate) { |
5362 | NewVar->getLexicalDeclContext()->addHiddenDecl(D: NewVar); |
5363 | if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) |
5364 | NewVar->getDeclContext()->makeDeclVisibleInContext(D: NewVar); |
5365 | } |
5366 | |
5367 | if (!OldVar->isOutOfLine()) { |
5368 | if (NewVar->getDeclContext()->isFunctionOrMethod()) |
5369 | CurrentInstantiationScope->InstantiatedLocal(D: OldVar, Inst: NewVar); |
5370 | } |
5371 | |
5372 | // Link instantiations of static data members back to the template from |
5373 | // which they were instantiated. |
5374 | // |
5375 | // Don't do this when instantiating a template (we link the template itself |
5376 | // back in that case) nor when instantiating a static data member template |
5377 | // (that's not a member specialization). |
5378 | if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate && |
5379 | !InstantiatingSpecFromTemplate) |
5380 | NewVar->setInstantiationOfStaticDataMember(VD: OldVar, |
5381 | TSK: TSK_ImplicitInstantiation); |
5382 | |
5383 | // If the pattern is an (in-class) explicit specialization, then the result |
5384 | // is also an explicit specialization. |
5385 | if (VarTemplateSpecializationDecl *OldVTSD = |
5386 | dyn_cast<VarTemplateSpecializationDecl>(Val: OldVar)) { |
5387 | if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization && |
5388 | !isa<VarTemplatePartialSpecializationDecl>(Val: OldVTSD)) |
5389 | cast<VarTemplateSpecializationDecl>(Val: NewVar)->setSpecializationKind( |
5390 | TSK_ExplicitSpecialization); |
5391 | } |
5392 | |
5393 | // Forward the mangling number from the template to the instantiated decl. |
5394 | Context.setManglingNumber(ND: NewVar, Number: Context.getManglingNumber(ND: OldVar)); |
5395 | Context.setStaticLocalNumber(VD: NewVar, Number: Context.getStaticLocalNumber(VD: OldVar)); |
5396 | |
5397 | // Figure out whether to eagerly instantiate the initializer. |
5398 | if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) { |
5399 | // We're producing a template. Don't instantiate the initializer yet. |
5400 | } else if (NewVar->getType()->isUndeducedType()) { |
5401 | // We need the type to complete the declaration of the variable. |
5402 | InstantiateVariableInitializer(Var: NewVar, OldVar, TemplateArgs); |
5403 | } else if (InstantiatingSpecFromTemplate || |
5404 | (OldVar->isInline() && OldVar->isThisDeclarationADefinition() && |
5405 | !NewVar->isThisDeclarationADefinition())) { |
5406 | // Delay instantiation of the initializer for variable template |
5407 | // specializations or inline static data members until a definition of the |
5408 | // variable is needed. |
5409 | } else { |
5410 | InstantiateVariableInitializer(Var: NewVar, OldVar, TemplateArgs); |
5411 | } |
5412 | |
5413 | // Diagnose unused local variables with dependent types, where the diagnostic |
5414 | // will have been deferred. |
5415 | if (!NewVar->isInvalidDecl() && |
5416 | NewVar->getDeclContext()->isFunctionOrMethod() && |
5417 | OldVar->getType()->isDependentType()) |
5418 | DiagnoseUnusedDecl(ND: NewVar); |
5419 | } |
5420 | |
5421 | void Sema::InstantiateVariableInitializer( |
5422 | VarDecl *Var, VarDecl *OldVar, |
5423 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
5424 | if (ASTMutationListener *L = getASTContext().getASTMutationListener()) |
5425 | L->VariableDefinitionInstantiated(D: Var); |
5426 | |
5427 | // We propagate the 'inline' flag with the initializer, because it |
5428 | // would otherwise imply that the variable is a definition for a |
5429 | // non-static data member. |
5430 | if (OldVar->isInlineSpecified()) |
5431 | Var->setInlineSpecified(); |
5432 | else if (OldVar->isInline()) |
5433 | Var->setImplicitlyInline(); |
5434 | |
5435 | if (OldVar->getInit()) { |
5436 | EnterExpressionEvaluationContext Evaluated( |
5437 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var); |
5438 | |
5439 | keepInLifetimeExtendingContext(); |
5440 | // Instantiate the initializer. |
5441 | ExprResult Init; |
5442 | |
5443 | { |
5444 | ContextRAII SwitchContext(*this, Var->getDeclContext()); |
5445 | Init = SubstInitializer(E: OldVar->getInit(), TemplateArgs, |
5446 | CXXDirectInit: OldVar->getInitStyle() == VarDecl::CallInit); |
5447 | } |
5448 | |
5449 | if (!Init.isInvalid()) { |
5450 | Expr *InitExpr = Init.get(); |
5451 | |
5452 | if (Var->hasAttr<DLLImportAttr>() && |
5453 | (!InitExpr || |
5454 | !InitExpr->isConstantInitializer(Ctx&: getASTContext(), ForRef: false))) { |
5455 | // Do not dynamically initialize dllimport variables. |
5456 | } else if (InitExpr) { |
5457 | bool DirectInit = OldVar->isDirectInit(); |
5458 | AddInitializerToDecl(dcl: Var, init: InitExpr, DirectInit); |
5459 | } else |
5460 | ActOnUninitializedDecl(dcl: Var); |
5461 | } else { |
5462 | // FIXME: Not too happy about invalidating the declaration |
5463 | // because of a bogus initializer. |
5464 | Var->setInvalidDecl(); |
5465 | } |
5466 | } else { |
5467 | // `inline` variables are a definition and declaration all in one; we won't |
5468 | // pick up an initializer from anywhere else. |
5469 | if (Var->isStaticDataMember() && !Var->isInline()) { |
5470 | if (!Var->isOutOfLine()) |
5471 | return; |
5472 | |
5473 | // If the declaration inside the class had an initializer, don't add |
5474 | // another one to the out-of-line definition. |
5475 | if (OldVar->getFirstDecl()->hasInit()) |
5476 | return; |
5477 | } |
5478 | |
5479 | // We'll add an initializer to a for-range declaration later. |
5480 | if (Var->isCXXForRangeDecl() || Var->isObjCForDecl()) |
5481 | return; |
5482 | |
5483 | ActOnUninitializedDecl(dcl: Var); |
5484 | } |
5485 | |
5486 | if (getLangOpts().CUDA) |
5487 | CUDA().checkAllowedInitializer(VD: Var); |
5488 | } |
5489 | |
5490 | void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, |
5491 | VarDecl *Var, bool Recursive, |
5492 | bool DefinitionRequired, bool AtEndOfTU) { |
5493 | if (Var->isInvalidDecl()) |
5494 | return; |
5495 | |
5496 | // Never instantiate an explicitly-specialized entity. |
5497 | TemplateSpecializationKind TSK = |
5498 | Var->getTemplateSpecializationKindForInstantiation(); |
5499 | if (TSK == TSK_ExplicitSpecialization) |
5500 | return; |
5501 | |
5502 | // Find the pattern and the arguments to substitute into it. |
5503 | VarDecl *PatternDecl = Var->getTemplateInstantiationPattern(); |
5504 | assert(PatternDecl && "no pattern for templated variable" ); |
5505 | MultiLevelTemplateArgumentList TemplateArgs = |
5506 | getTemplateInstantiationArgs(D: Var); |
5507 | |
5508 | VarTemplateSpecializationDecl *VarSpec = |
5509 | dyn_cast<VarTemplateSpecializationDecl>(Val: Var); |
5510 | if (VarSpec) { |
5511 | // If this is a static data member template, there might be an |
5512 | // uninstantiated initializer on the declaration. If so, instantiate |
5513 | // it now. |
5514 | // |
5515 | // FIXME: This largely duplicates what we would do below. The difference |
5516 | // is that along this path we may instantiate an initializer from an |
5517 | // in-class declaration of the template and instantiate the definition |
5518 | // from a separate out-of-class definition. |
5519 | if (PatternDecl->isStaticDataMember() && |
5520 | (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && |
5521 | !Var->hasInit()) { |
5522 | // FIXME: Factor out the duplicated instantiation context setup/tear down |
5523 | // code here. |
5524 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); |
5525 | if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) |
5526 | return; |
5527 | PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), |
5528 | "instantiating variable initializer" ); |
5529 | |
5530 | // The instantiation is visible here, even if it was first declared in an |
5531 | // unimported module. |
5532 | Var->setVisibleDespiteOwningModule(); |
5533 | |
5534 | // If we're performing recursive template instantiation, create our own |
5535 | // queue of pending implicit instantiations that we will instantiate |
5536 | // later, while we're still within our own instantiation context. |
5537 | GlobalEagerInstantiationScope GlobalInstantiations(*this, |
5538 | /*Enabled=*/Recursive); |
5539 | LocalInstantiationScope Local(*this); |
5540 | LocalEagerInstantiationScope LocalInstantiations(*this); |
5541 | |
5542 | // Enter the scope of this instantiation. We don't use |
5543 | // PushDeclContext because we don't have a scope. |
5544 | ContextRAII PreviousContext(*this, Var->getDeclContext()); |
5545 | InstantiateVariableInitializer(Var, OldVar: PatternDecl, TemplateArgs); |
5546 | PreviousContext.pop(); |
5547 | |
5548 | // This variable may have local implicit instantiations that need to be |
5549 | // instantiated within this scope. |
5550 | LocalInstantiations.perform(); |
5551 | Local.Exit(); |
5552 | GlobalInstantiations.perform(); |
5553 | } |
5554 | } else { |
5555 | assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && |
5556 | "not a static data member?" ); |
5557 | } |
5558 | |
5559 | VarDecl *Def = PatternDecl->getDefinition(getASTContext()); |
5560 | |
5561 | // If we don't have a definition of the variable template, we won't perform |
5562 | // any instantiation. Rather, we rely on the user to instantiate this |
5563 | // definition (or provide a specialization for it) in another translation |
5564 | // unit. |
5565 | if (!Def && !DefinitionRequired) { |
5566 | if (TSK == TSK_ExplicitInstantiationDefinition) { |
5567 | PendingInstantiations.push_back( |
5568 | x: std::make_pair(x&: Var, y&: PointOfInstantiation)); |
5569 | } else if (TSK == TSK_ImplicitInstantiation) { |
5570 | // Warn about missing definition at the end of translation unit. |
5571 | if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && |
5572 | !getSourceManager().isInSystemHeader(Loc: PatternDecl->getBeginLoc())) { |
5573 | Diag(Loc: PointOfInstantiation, DiagID: diag::warn_var_template_missing) |
5574 | << Var; |
5575 | Diag(Loc: PatternDecl->getLocation(), DiagID: diag::note_forward_template_decl); |
5576 | if (getLangOpts().CPlusPlus11) |
5577 | Diag(Loc: PointOfInstantiation, DiagID: diag::note_inst_declaration_hint) << Var; |
5578 | } |
5579 | return; |
5580 | } |
5581 | } |
5582 | |
5583 | // FIXME: We need to track the instantiation stack in order to know which |
5584 | // definitions should be visible within this instantiation. |
5585 | // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember(). |
5586 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation: Var, |
5587 | /*InstantiatedFromMember*/false, |
5588 | Pattern: PatternDecl, PatternDef: Def, TSK, |
5589 | /*Complain*/DefinitionRequired)) |
5590 | return; |
5591 | |
5592 | // C++11 [temp.explicit]p10: |
5593 | // Except for inline functions, const variables of literal types, variables |
5594 | // of reference types, [...] explicit instantiation declarations |
5595 | // have the effect of suppressing the implicit instantiation of the entity |
5596 | // to which they refer. |
5597 | // |
5598 | // FIXME: That's not exactly the same as "might be usable in constant |
5599 | // expressions", which only allows constexpr variables and const integral |
5600 | // types, not arbitrary const literal types. |
5601 | if (TSK == TSK_ExplicitInstantiationDeclaration && |
5602 | !Var->mightBeUsableInConstantExpressions(C: getASTContext())) |
5603 | return; |
5604 | |
5605 | // Make sure to pass the instantiated variable to the consumer at the end. |
5606 | struct PassToConsumerRAII { |
5607 | ASTConsumer &Consumer; |
5608 | VarDecl *Var; |
5609 | |
5610 | PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) |
5611 | : Consumer(Consumer), Var(Var) { } |
5612 | |
5613 | ~PassToConsumerRAII() { |
5614 | Consumer.HandleCXXStaticMemberVarInstantiation(D: Var); |
5615 | } |
5616 | } PassToConsumerRAII(Consumer, Var); |
5617 | |
5618 | // If we already have a definition, we're done. |
5619 | if (VarDecl *Def = Var->getDefinition()) { |
5620 | // We may be explicitly instantiating something we've already implicitly |
5621 | // instantiated. |
5622 | Def->setTemplateSpecializationKind(TSK: Var->getTemplateSpecializationKind(), |
5623 | PointOfInstantiation); |
5624 | return; |
5625 | } |
5626 | |
5627 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); |
5628 | if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) |
5629 | return; |
5630 | PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), |
5631 | "instantiating variable definition" ); |
5632 | |
5633 | // If we're performing recursive template instantiation, create our own |
5634 | // queue of pending implicit instantiations that we will instantiate later, |
5635 | // while we're still within our own instantiation context. |
5636 | GlobalEagerInstantiationScope GlobalInstantiations(*this, |
5637 | /*Enabled=*/Recursive); |
5638 | |
5639 | // Enter the scope of this instantiation. We don't use |
5640 | // PushDeclContext because we don't have a scope. |
5641 | ContextRAII PreviousContext(*this, Var->getDeclContext()); |
5642 | LocalInstantiationScope Local(*this); |
5643 | |
5644 | LocalEagerInstantiationScope LocalInstantiations(*this); |
5645 | |
5646 | VarDecl *OldVar = Var; |
5647 | if (Def->isStaticDataMember() && !Def->isOutOfLine()) { |
5648 | // We're instantiating an inline static data member whose definition was |
5649 | // provided inside the class. |
5650 | InstantiateVariableInitializer(Var, OldVar: Def, TemplateArgs); |
5651 | } else if (!VarSpec) { |
5652 | Var = cast_or_null<VarDecl>(Val: SubstDecl(D: Def, Owner: Var->getDeclContext(), |
5653 | TemplateArgs)); |
5654 | } else if (Var->isStaticDataMember() && |
5655 | Var->getLexicalDeclContext()->isRecord()) { |
5656 | // We need to instantiate the definition of a static data member template, |
5657 | // and all we have is the in-class declaration of it. Instantiate a separate |
5658 | // declaration of the definition. |
5659 | TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), |
5660 | TemplateArgs); |
5661 | |
5662 | TemplateArgumentListInfo TemplateArgInfo; |
5663 | if (const ASTTemplateArgumentListInfo *ArgInfo = |
5664 | VarSpec->getTemplateArgsAsWritten()) { |
5665 | TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc()); |
5666 | TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc()); |
5667 | for (const TemplateArgumentLoc &Arg : ArgInfo->arguments()) |
5668 | TemplateArgInfo.addArgument(Loc: Arg); |
5669 | } |
5670 | |
5671 | Var = cast_or_null<VarDecl>(Val: Instantiator.VisitVarTemplateSpecializationDecl( |
5672 | VarTemplate: VarSpec->getSpecializedTemplate(), D: Def, TemplateArgsInfo: TemplateArgInfo, |
5673 | Converted: VarSpec->getTemplateArgs().asArray(), PrevDecl: VarSpec)); |
5674 | if (Var) { |
5675 | llvm::PointerUnion<VarTemplateDecl *, |
5676 | VarTemplatePartialSpecializationDecl *> PatternPtr = |
5677 | VarSpec->getSpecializedTemplateOrPartial(); |
5678 | if (VarTemplatePartialSpecializationDecl *Partial = |
5679 | PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) |
5680 | cast<VarTemplateSpecializationDecl>(Val: Var)->setInstantiationOf( |
5681 | PartialSpec: Partial, TemplateArgs: &VarSpec->getTemplateInstantiationArgs()); |
5682 | |
5683 | // Attach the initializer. |
5684 | InstantiateVariableInitializer(Var, OldVar: Def, TemplateArgs); |
5685 | } |
5686 | } else |
5687 | // Complete the existing variable's definition with an appropriately |
5688 | // substituted type and initializer. |
5689 | Var = CompleteVarTemplateSpecializationDecl(VarSpec, PatternDecl: Def, TemplateArgs); |
5690 | |
5691 | PreviousContext.pop(); |
5692 | |
5693 | if (Var) { |
5694 | PassToConsumerRAII.Var = Var; |
5695 | Var->setTemplateSpecializationKind(TSK: OldVar->getTemplateSpecializationKind(), |
5696 | PointOfInstantiation: OldVar->getPointOfInstantiation()); |
5697 | } |
5698 | |
5699 | // This variable may have local implicit instantiations that need to be |
5700 | // instantiated within this scope. |
5701 | LocalInstantiations.perform(); |
5702 | Local.Exit(); |
5703 | GlobalInstantiations.perform(); |
5704 | } |
5705 | |
5706 | void |
5707 | Sema::InstantiateMemInitializers(CXXConstructorDecl *New, |
5708 | const CXXConstructorDecl *Tmpl, |
5709 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
5710 | |
5711 | SmallVector<CXXCtorInitializer*, 4> NewInits; |
5712 | bool AnyErrors = Tmpl->isInvalidDecl(); |
5713 | |
5714 | // Instantiate all the initializers. |
5715 | for (const auto *Init : Tmpl->inits()) { |
5716 | // Only instantiate written initializers, let Sema re-construct implicit |
5717 | // ones. |
5718 | if (!Init->isWritten()) |
5719 | continue; |
5720 | |
5721 | SourceLocation EllipsisLoc; |
5722 | |
5723 | if (Init->isPackExpansion()) { |
5724 | // This is a pack expansion. We should expand it now. |
5725 | TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); |
5726 | SmallVector<UnexpandedParameterPack, 4> Unexpanded; |
5727 | collectUnexpandedParameterPacks(TL: BaseTL, Unexpanded); |
5728 | collectUnexpandedParameterPacks(E: Init->getInit(), Unexpanded); |
5729 | bool ShouldExpand = false; |
5730 | bool RetainExpansion = false; |
5731 | std::optional<unsigned> NumExpansions; |
5732 | if (CheckParameterPacksForExpansion(EllipsisLoc: Init->getEllipsisLoc(), |
5733 | PatternRange: BaseTL.getSourceRange(), |
5734 | Unexpanded, |
5735 | TemplateArgs, ShouldExpand, |
5736 | RetainExpansion, |
5737 | NumExpansions)) { |
5738 | AnyErrors = true; |
5739 | New->setInvalidDecl(); |
5740 | continue; |
5741 | } |
5742 | assert(ShouldExpand && "Partial instantiation of base initializer?" ); |
5743 | |
5744 | // Loop over all of the arguments in the argument pack(s), |
5745 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
5746 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); |
5747 | |
5748 | // Instantiate the initializer. |
5749 | ExprResult TempInit = SubstInitializer(E: Init->getInit(), TemplateArgs, |
5750 | /*CXXDirectInit=*/true); |
5751 | if (TempInit.isInvalid()) { |
5752 | AnyErrors = true; |
5753 | break; |
5754 | } |
5755 | |
5756 | // Instantiate the base type. |
5757 | TypeSourceInfo *BaseTInfo = SubstType(T: Init->getTypeSourceInfo(), |
5758 | TemplateArgs, |
5759 | Loc: Init->getSourceLocation(), |
5760 | Entity: New->getDeclName()); |
5761 | if (!BaseTInfo) { |
5762 | AnyErrors = true; |
5763 | break; |
5764 | } |
5765 | |
5766 | // Build the initializer. |
5767 | MemInitResult NewInit = BuildBaseInitializer(BaseType: BaseTInfo->getType(), |
5768 | BaseTInfo, Init: TempInit.get(), |
5769 | ClassDecl: New->getParent(), |
5770 | EllipsisLoc: SourceLocation()); |
5771 | if (NewInit.isInvalid()) { |
5772 | AnyErrors = true; |
5773 | break; |
5774 | } |
5775 | |
5776 | NewInits.push_back(Elt: NewInit.get()); |
5777 | } |
5778 | |
5779 | continue; |
5780 | } |
5781 | |
5782 | // Instantiate the initializer. |
5783 | ExprResult TempInit = SubstInitializer(E: Init->getInit(), TemplateArgs, |
5784 | /*CXXDirectInit=*/true); |
5785 | if (TempInit.isInvalid()) { |
5786 | AnyErrors = true; |
5787 | continue; |
5788 | } |
5789 | |
5790 | MemInitResult NewInit; |
5791 | if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { |
5792 | TypeSourceInfo *TInfo = SubstType(T: Init->getTypeSourceInfo(), |
5793 | TemplateArgs, |
5794 | Loc: Init->getSourceLocation(), |
5795 | Entity: New->getDeclName()); |
5796 | if (!TInfo) { |
5797 | AnyErrors = true; |
5798 | New->setInvalidDecl(); |
5799 | continue; |
5800 | } |
5801 | |
5802 | if (Init->isBaseInitializer()) |
5803 | NewInit = BuildBaseInitializer(BaseType: TInfo->getType(), BaseTInfo: TInfo, Init: TempInit.get(), |
5804 | ClassDecl: New->getParent(), EllipsisLoc); |
5805 | else |
5806 | NewInit = BuildDelegatingInitializer(TInfo, Init: TempInit.get(), |
5807 | ClassDecl: cast<CXXRecordDecl>(Val: CurContext->getParent())); |
5808 | } else if (Init->isMemberInitializer()) { |
5809 | FieldDecl *Member = cast_or_null<FieldDecl>(Val: FindInstantiatedDecl( |
5810 | Loc: Init->getMemberLocation(), |
5811 | D: Init->getMember(), |
5812 | TemplateArgs)); |
5813 | if (!Member) { |
5814 | AnyErrors = true; |
5815 | New->setInvalidDecl(); |
5816 | continue; |
5817 | } |
5818 | |
5819 | NewInit = BuildMemberInitializer(Member, Init: TempInit.get(), |
5820 | IdLoc: Init->getSourceLocation()); |
5821 | } else if (Init->isIndirectMemberInitializer()) { |
5822 | IndirectFieldDecl *IndirectMember = |
5823 | cast_or_null<IndirectFieldDecl>(Val: FindInstantiatedDecl( |
5824 | Loc: Init->getMemberLocation(), |
5825 | D: Init->getIndirectMember(), TemplateArgs)); |
5826 | |
5827 | if (!IndirectMember) { |
5828 | AnyErrors = true; |
5829 | New->setInvalidDecl(); |
5830 | continue; |
5831 | } |
5832 | |
5833 | NewInit = BuildMemberInitializer(Member: IndirectMember, Init: TempInit.get(), |
5834 | IdLoc: Init->getSourceLocation()); |
5835 | } |
5836 | |
5837 | if (NewInit.isInvalid()) { |
5838 | AnyErrors = true; |
5839 | New->setInvalidDecl(); |
5840 | } else { |
5841 | NewInits.push_back(Elt: NewInit.get()); |
5842 | } |
5843 | } |
5844 | |
5845 | // Assign all the initializers to the new constructor. |
5846 | ActOnMemInitializers(ConstructorDecl: New, |
5847 | /*FIXME: ColonLoc */ |
5848 | ColonLoc: SourceLocation(), |
5849 | MemInits: NewInits, |
5850 | AnyErrors); |
5851 | } |
5852 | |
5853 | // TODO: this could be templated if the various decl types used the |
5854 | // same method name. |
5855 | static bool isInstantiationOf(ClassTemplateDecl *Pattern, |
5856 | ClassTemplateDecl *Instance) { |
5857 | Pattern = Pattern->getCanonicalDecl(); |
5858 | |
5859 | do { |
5860 | Instance = Instance->getCanonicalDecl(); |
5861 | if (Pattern == Instance) return true; |
5862 | Instance = Instance->getInstantiatedFromMemberTemplate(); |
5863 | } while (Instance); |
5864 | |
5865 | return false; |
5866 | } |
5867 | |
5868 | static bool isInstantiationOf(FunctionTemplateDecl *Pattern, |
5869 | FunctionTemplateDecl *Instance) { |
5870 | Pattern = Pattern->getCanonicalDecl(); |
5871 | |
5872 | do { |
5873 | Instance = Instance->getCanonicalDecl(); |
5874 | if (Pattern == Instance) return true; |
5875 | Instance = Instance->getInstantiatedFromMemberTemplate(); |
5876 | } while (Instance); |
5877 | |
5878 | return false; |
5879 | } |
5880 | |
5881 | static bool |
5882 | isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, |
5883 | ClassTemplatePartialSpecializationDecl *Instance) { |
5884 | Pattern |
5885 | = cast<ClassTemplatePartialSpecializationDecl>(Val: Pattern->getCanonicalDecl()); |
5886 | do { |
5887 | Instance = cast<ClassTemplatePartialSpecializationDecl>( |
5888 | Val: Instance->getCanonicalDecl()); |
5889 | if (Pattern == Instance) |
5890 | return true; |
5891 | Instance = Instance->getInstantiatedFromMember(); |
5892 | } while (Instance); |
5893 | |
5894 | return false; |
5895 | } |
5896 | |
5897 | static bool isInstantiationOf(CXXRecordDecl *Pattern, |
5898 | CXXRecordDecl *Instance) { |
5899 | Pattern = Pattern->getCanonicalDecl(); |
5900 | |
5901 | do { |
5902 | Instance = Instance->getCanonicalDecl(); |
5903 | if (Pattern == Instance) return true; |
5904 | Instance = Instance->getInstantiatedFromMemberClass(); |
5905 | } while (Instance); |
5906 | |
5907 | return false; |
5908 | } |
5909 | |
5910 | static bool isInstantiationOf(FunctionDecl *Pattern, |
5911 | FunctionDecl *Instance) { |
5912 | Pattern = Pattern->getCanonicalDecl(); |
5913 | |
5914 | do { |
5915 | Instance = Instance->getCanonicalDecl(); |
5916 | if (Pattern == Instance) return true; |
5917 | Instance = Instance->getInstantiatedFromMemberFunction(); |
5918 | } while (Instance); |
5919 | |
5920 | return false; |
5921 | } |
5922 | |
5923 | static bool isInstantiationOf(EnumDecl *Pattern, |
5924 | EnumDecl *Instance) { |
5925 | Pattern = Pattern->getCanonicalDecl(); |
5926 | |
5927 | do { |
5928 | Instance = Instance->getCanonicalDecl(); |
5929 | if (Pattern == Instance) return true; |
5930 | Instance = Instance->getInstantiatedFromMemberEnum(); |
5931 | } while (Instance); |
5932 | |
5933 | return false; |
5934 | } |
5935 | |
5936 | static bool isInstantiationOf(UsingShadowDecl *Pattern, |
5937 | UsingShadowDecl *Instance, |
5938 | ASTContext &C) { |
5939 | return declaresSameEntity(D1: C.getInstantiatedFromUsingShadowDecl(Inst: Instance), |
5940 | D2: Pattern); |
5941 | } |
5942 | |
5943 | static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance, |
5944 | ASTContext &C) { |
5945 | return declaresSameEntity(D1: C.getInstantiatedFromUsingDecl(Inst: Instance), D2: Pattern); |
5946 | } |
5947 | |
5948 | template<typename T> |
5949 | static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other, |
5950 | ASTContext &Ctx) { |
5951 | // An unresolved using declaration can instantiate to an unresolved using |
5952 | // declaration, or to a using declaration or a using declaration pack. |
5953 | // |
5954 | // Multiple declarations can claim to be instantiated from an unresolved |
5955 | // using declaration if it's a pack expansion. We want the UsingPackDecl |
5956 | // in that case, not the individual UsingDecls within the pack. |
5957 | bool OtherIsPackExpansion; |
5958 | NamedDecl *OtherFrom; |
5959 | if (auto *OtherUUD = dyn_cast<T>(Other)) { |
5960 | OtherIsPackExpansion = OtherUUD->isPackExpansion(); |
5961 | OtherFrom = Ctx.getInstantiatedFromUsingDecl(Inst: OtherUUD); |
5962 | } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Val: Other)) { |
5963 | OtherIsPackExpansion = true; |
5964 | OtherFrom = OtherUPD->getInstantiatedFromUsingDecl(); |
5965 | } else if (auto *OtherUD = dyn_cast<UsingDecl>(Val: Other)) { |
5966 | OtherIsPackExpansion = false; |
5967 | OtherFrom = Ctx.getInstantiatedFromUsingDecl(Inst: OtherUD); |
5968 | } else { |
5969 | return false; |
5970 | } |
5971 | return Pattern->isPackExpansion() == OtherIsPackExpansion && |
5972 | declaresSameEntity(OtherFrom, Pattern); |
5973 | } |
5974 | |
5975 | static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, |
5976 | VarDecl *Instance) { |
5977 | assert(Instance->isStaticDataMember()); |
5978 | |
5979 | Pattern = Pattern->getCanonicalDecl(); |
5980 | |
5981 | do { |
5982 | Instance = Instance->getCanonicalDecl(); |
5983 | if (Pattern == Instance) return true; |
5984 | Instance = Instance->getInstantiatedFromStaticDataMember(); |
5985 | } while (Instance); |
5986 | |
5987 | return false; |
5988 | } |
5989 | |
5990 | // Other is the prospective instantiation |
5991 | // D is the prospective pattern |
5992 | static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { |
5993 | if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) |
5994 | return isInstantiationOfUnresolvedUsingDecl(Pattern: UUD, Other, Ctx); |
5995 | |
5996 | if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) |
5997 | return isInstantiationOfUnresolvedUsingDecl(Pattern: UUD, Other, Ctx); |
5998 | |
5999 | if (D->getKind() != Other->getKind()) |
6000 | return false; |
6001 | |
6002 | if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Other)) |
6003 | return isInstantiationOf(Pattern: cast<CXXRecordDecl>(Val: D), Instance: Record); |
6004 | |
6005 | if (auto *Function = dyn_cast<FunctionDecl>(Val: Other)) |
6006 | return isInstantiationOf(Pattern: cast<FunctionDecl>(Val: D), Instance: Function); |
6007 | |
6008 | if (auto *Enum = dyn_cast<EnumDecl>(Val: Other)) |
6009 | return isInstantiationOf(Pattern: cast<EnumDecl>(Val: D), Instance: Enum); |
6010 | |
6011 | if (auto *Var = dyn_cast<VarDecl>(Val: Other)) |
6012 | if (Var->isStaticDataMember()) |
6013 | return isInstantiationOfStaticDataMember(Pattern: cast<VarDecl>(Val: D), Instance: Var); |
6014 | |
6015 | if (auto *Temp = dyn_cast<ClassTemplateDecl>(Val: Other)) |
6016 | return isInstantiationOf(Pattern: cast<ClassTemplateDecl>(Val: D), Instance: Temp); |
6017 | |
6018 | if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Val: Other)) |
6019 | return isInstantiationOf(Pattern: cast<FunctionTemplateDecl>(Val: D), Instance: Temp); |
6020 | |
6021 | if (auto *PartialSpec = |
6022 | dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Other)) |
6023 | return isInstantiationOf(Pattern: cast<ClassTemplatePartialSpecializationDecl>(Val: D), |
6024 | Instance: PartialSpec); |
6025 | |
6026 | if (auto *Field = dyn_cast<FieldDecl>(Val: Other)) { |
6027 | if (!Field->getDeclName()) { |
6028 | // This is an unnamed field. |
6029 | return declaresSameEntity(D1: Ctx.getInstantiatedFromUnnamedFieldDecl(Field), |
6030 | D2: cast<FieldDecl>(Val: D)); |
6031 | } |
6032 | } |
6033 | |
6034 | if (auto *Using = dyn_cast<UsingDecl>(Val: Other)) |
6035 | return isInstantiationOf(Pattern: cast<UsingDecl>(Val: D), Instance: Using, C&: Ctx); |
6036 | |
6037 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: Other)) |
6038 | return isInstantiationOf(Pattern: cast<UsingShadowDecl>(Val: D), Instance: Shadow, C&: Ctx); |
6039 | |
6040 | return D->getDeclName() && |
6041 | D->getDeclName() == cast<NamedDecl>(Val: Other)->getDeclName(); |
6042 | } |
6043 | |
6044 | template<typename ForwardIterator> |
6045 | static NamedDecl *findInstantiationOf(ASTContext &Ctx, |
6046 | NamedDecl *D, |
6047 | ForwardIterator first, |
6048 | ForwardIterator last) { |
6049 | for (; first != last; ++first) |
6050 | if (isInstantiationOf(Ctx, D, *first)) |
6051 | return cast<NamedDecl>(*first); |
6052 | |
6053 | return nullptr; |
6054 | } |
6055 | |
6056 | DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, |
6057 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
6058 | if (NamedDecl *D = dyn_cast<NamedDecl>(Val: DC)) { |
6059 | Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, FindingInstantiatedContext: true); |
6060 | return cast_or_null<DeclContext>(Val: ID); |
6061 | } else return DC; |
6062 | } |
6063 | |
6064 | /// Determine whether the given context is dependent on template parameters at |
6065 | /// level \p Level or below. |
6066 | /// |
6067 | /// Sometimes we only substitute an inner set of template arguments and leave |
6068 | /// the outer templates alone. In such cases, contexts dependent only on the |
6069 | /// outer levels are not effectively dependent. |
6070 | static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) { |
6071 | if (!DC->isDependentContext()) |
6072 | return false; |
6073 | if (!Level) |
6074 | return true; |
6075 | return cast<Decl>(Val: DC)->getTemplateDepth() > Level; |
6076 | } |
6077 | |
6078 | NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, |
6079 | const MultiLevelTemplateArgumentList &TemplateArgs, |
6080 | bool FindingInstantiatedContext) { |
6081 | DeclContext *ParentDC = D->getDeclContext(); |
6082 | // Determine whether our parent context depends on any of the template |
6083 | // arguments we're currently substituting. |
6084 | bool ParentDependsOnArgs = isDependentContextAtLevel( |
6085 | DC: ParentDC, Level: TemplateArgs.getNumRetainedOuterLevels()); |
6086 | // FIXME: Parameters of pointer to functions (y below) that are themselves |
6087 | // parameters (p below) can have their ParentDC set to the translation-unit |
6088 | // - thus we can not consistently check if the ParentDC of such a parameter |
6089 | // is Dependent or/and a FunctionOrMethod. |
6090 | // For e.g. this code, during Template argument deduction tries to |
6091 | // find an instantiated decl for (T y) when the ParentDC for y is |
6092 | // the translation unit. |
6093 | // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} |
6094 | // float baz(float(*)()) { return 0.0; } |
6095 | // Foo(baz); |
6096 | // The better fix here is perhaps to ensure that a ParmVarDecl, by the time |
6097 | // it gets here, always has a FunctionOrMethod as its ParentDC?? |
6098 | // For now: |
6099 | // - as long as we have a ParmVarDecl whose parent is non-dependent and |
6100 | // whose type is not instantiation dependent, do nothing to the decl |
6101 | // - otherwise find its instantiated decl. |
6102 | if (isa<ParmVarDecl>(Val: D) && !ParentDependsOnArgs && |
6103 | !cast<ParmVarDecl>(Val: D)->getType()->isInstantiationDependentType()) |
6104 | return D; |
6105 | if (isa<ParmVarDecl>(Val: D) || isa<NonTypeTemplateParmDecl>(Val: D) || |
6106 | isa<TemplateTypeParmDecl>(Val: D) || isa<TemplateTemplateParmDecl>(Val: D) || |
6107 | (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() || |
6108 | isa<OMPDeclareReductionDecl>(Val: ParentDC) || |
6109 | isa<OMPDeclareMapperDecl>(Val: ParentDC))) || |
6110 | (isa<CXXRecordDecl>(Val: D) && cast<CXXRecordDecl>(Val: D)->isLambda() && |
6111 | cast<CXXRecordDecl>(Val: D)->getTemplateDepth() > |
6112 | TemplateArgs.getNumRetainedOuterLevels())) { |
6113 | // D is a local of some kind. Look into the map of local |
6114 | // declarations to their instantiations. |
6115 | if (CurrentInstantiationScope) { |
6116 | if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) { |
6117 | if (Decl *FD = Found->dyn_cast<Decl *>()) |
6118 | return cast<NamedDecl>(Val: FD); |
6119 | |
6120 | int PackIdx = ArgumentPackSubstitutionIndex; |
6121 | assert(PackIdx != -1 && |
6122 | "found declaration pack but not pack expanding" ); |
6123 | typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; |
6124 | return cast<NamedDecl>(Val: (*Found->get<DeclArgumentPack *>())[PackIdx]); |
6125 | } |
6126 | } |
6127 | |
6128 | // If we're performing a partial substitution during template argument |
6129 | // deduction, we may not have values for template parameters yet. They |
6130 | // just map to themselves. |
6131 | if (isa<NonTypeTemplateParmDecl>(Val: D) || isa<TemplateTypeParmDecl>(Val: D) || |
6132 | isa<TemplateTemplateParmDecl>(Val: D)) |
6133 | return D; |
6134 | |
6135 | if (D->isInvalidDecl()) |
6136 | return nullptr; |
6137 | |
6138 | // Normally this function only searches for already instantiated declaration |
6139 | // however we have to make an exclusion for local types used before |
6140 | // definition as in the code: |
6141 | // |
6142 | // template<typename T> void f1() { |
6143 | // void g1(struct x1); |
6144 | // struct x1 {}; |
6145 | // } |
6146 | // |
6147 | // In this case instantiation of the type of 'g1' requires definition of |
6148 | // 'x1', which is defined later. Error recovery may produce an enum used |
6149 | // before definition. In these cases we need to instantiate relevant |
6150 | // declarations here. |
6151 | bool NeedInstantiate = false; |
6152 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D)) |
6153 | NeedInstantiate = RD->isLocalClass(); |
6154 | else if (isa<TypedefNameDecl>(Val: D) && |
6155 | isa<CXXDeductionGuideDecl>(Val: D->getDeclContext())) |
6156 | NeedInstantiate = true; |
6157 | else |
6158 | NeedInstantiate = isa<EnumDecl>(Val: D); |
6159 | if (NeedInstantiate) { |
6160 | Decl *Inst = SubstDecl(D, Owner: CurContext, TemplateArgs); |
6161 | CurrentInstantiationScope->InstantiatedLocal(D, Inst); |
6162 | return cast<TypeDecl>(Val: Inst); |
6163 | } |
6164 | |
6165 | // If we didn't find the decl, then we must have a label decl that hasn't |
6166 | // been found yet. Lazily instantiate it and return it now. |
6167 | assert(isa<LabelDecl>(D)); |
6168 | |
6169 | Decl *Inst = SubstDecl(D, Owner: CurContext, TemplateArgs); |
6170 | assert(Inst && "Failed to instantiate label??" ); |
6171 | |
6172 | CurrentInstantiationScope->InstantiatedLocal(D, Inst); |
6173 | return cast<LabelDecl>(Val: Inst); |
6174 | } |
6175 | |
6176 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D)) { |
6177 | if (!Record->isDependentContext()) |
6178 | return D; |
6179 | |
6180 | // Determine whether this record is the "templated" declaration describing |
6181 | // a class template or class template specialization. |
6182 | ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); |
6183 | if (ClassTemplate) |
6184 | ClassTemplate = ClassTemplate->getCanonicalDecl(); |
6185 | else if (ClassTemplateSpecializationDecl *Spec = |
6186 | dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) |
6187 | ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl(); |
6188 | |
6189 | // Walk the current context to find either the record or an instantiation of |
6190 | // it. |
6191 | DeclContext *DC = CurContext; |
6192 | while (!DC->isFileContext()) { |
6193 | // If we're performing substitution while we're inside the template |
6194 | // definition, we'll find our own context. We're done. |
6195 | if (DC->Equals(DC: Record)) |
6196 | return Record; |
6197 | |
6198 | if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(Val: DC)) { |
6199 | // Check whether we're in the process of instantiating a class template |
6200 | // specialization of the template we're mapping. |
6201 | if (ClassTemplateSpecializationDecl *InstSpec |
6202 | = dyn_cast<ClassTemplateSpecializationDecl>(Val: InstRecord)){ |
6203 | ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); |
6204 | if (ClassTemplate && isInstantiationOf(Pattern: ClassTemplate, Instance: SpecTemplate)) |
6205 | return InstRecord; |
6206 | } |
6207 | |
6208 | // Check whether we're in the process of instantiating a member class. |
6209 | if (isInstantiationOf(Pattern: Record, Instance: InstRecord)) |
6210 | return InstRecord; |
6211 | } |
6212 | |
6213 | // Move to the outer template scope. |
6214 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: DC)) { |
6215 | if (FD->getFriendObjectKind() && |
6216 | FD->getNonTransparentDeclContext()->isFileContext()) { |
6217 | DC = FD->getLexicalDeclContext(); |
6218 | continue; |
6219 | } |
6220 | // An implicit deduction guide acts as if it's within the class template |
6221 | // specialization described by its name and first N template params. |
6222 | auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: FD); |
6223 | if (Guide && Guide->isImplicit()) { |
6224 | TemplateDecl *TD = Guide->getDeducedTemplate(); |
6225 | // Convert the arguments to an "as-written" list. |
6226 | TemplateArgumentListInfo Args(Loc, Loc); |
6227 | for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front( |
6228 | N: TD->getTemplateParameters()->size())) { |
6229 | ArrayRef<TemplateArgument> Unpacked(Arg); |
6230 | if (Arg.getKind() == TemplateArgument::Pack) |
6231 | Unpacked = Arg.pack_elements(); |
6232 | for (TemplateArgument UnpackedArg : Unpacked) |
6233 | Args.addArgument( |
6234 | Loc: getTrivialTemplateArgumentLoc(Arg: UnpackedArg, NTTPType: QualType(), Loc)); |
6235 | } |
6236 | QualType T = CheckTemplateIdType(Template: TemplateName(TD), TemplateLoc: Loc, TemplateArgs&: Args); |
6237 | // We may get a non-null type with errors, in which case |
6238 | // `getAsCXXRecordDecl` will return `nullptr`. For instance, this |
6239 | // happens when one of the template arguments is an invalid |
6240 | // expression. We return early to avoid triggering the assertion |
6241 | // about the `CodeSynthesisContext`. |
6242 | if (T.isNull() || T->containsErrors()) |
6243 | return nullptr; |
6244 | CXXRecordDecl *SubstRecord = T->getAsCXXRecordDecl(); |
6245 | |
6246 | if (!SubstRecord) { |
6247 | // T can be a dependent TemplateSpecializationType when performing a |
6248 | // substitution for building a deduction guide. |
6249 | assert(CodeSynthesisContexts.back().Kind == |
6250 | CodeSynthesisContext::BuildingDeductionGuides); |
6251 | // Return a nullptr as a sentinel value, we handle it properly in |
6252 | // the TemplateInstantiator::TransformInjectedClassNameType |
6253 | // override, which we transform it to a TemplateSpecializationType. |
6254 | return nullptr; |
6255 | } |
6256 | // Check that this template-id names the primary template and not a |
6257 | // partial or explicit specialization. (In the latter cases, it's |
6258 | // meaningless to attempt to find an instantiation of D within the |
6259 | // specialization.) |
6260 | // FIXME: The standard doesn't say what should happen here. |
6261 | if (FindingInstantiatedContext && |
6262 | usesPartialOrExplicitSpecialization( |
6263 | Loc, ClassTemplateSpec: cast<ClassTemplateSpecializationDecl>(Val: SubstRecord))) { |
6264 | Diag(Loc, DiagID: diag::err_specialization_not_primary_template) |
6265 | << T << (SubstRecord->getTemplateSpecializationKind() == |
6266 | TSK_ExplicitSpecialization); |
6267 | return nullptr; |
6268 | } |
6269 | DC = SubstRecord; |
6270 | continue; |
6271 | } |
6272 | } |
6273 | |
6274 | DC = DC->getParent(); |
6275 | } |
6276 | |
6277 | // Fall through to deal with other dependent record types (e.g., |
6278 | // anonymous unions in class templates). |
6279 | } |
6280 | |
6281 | if (!ParentDependsOnArgs) |
6282 | return D; |
6283 | |
6284 | ParentDC = FindInstantiatedContext(Loc, DC: ParentDC, TemplateArgs); |
6285 | if (!ParentDC) |
6286 | return nullptr; |
6287 | |
6288 | if (ParentDC != D->getDeclContext()) { |
6289 | // We performed some kind of instantiation in the parent context, |
6290 | // so now we need to look into the instantiated parent context to |
6291 | // find the instantiation of the declaration D. |
6292 | |
6293 | // If our context used to be dependent, we may need to instantiate |
6294 | // it before performing lookup into that context. |
6295 | bool IsBeingInstantiated = false; |
6296 | if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(Val: ParentDC)) { |
6297 | if (!Spec->isDependentContext()) { |
6298 | QualType T = Context.getTypeDeclType(Decl: Spec); |
6299 | const RecordType *Tag = T->getAs<RecordType>(); |
6300 | assert(Tag && "type of non-dependent record is not a RecordType" ); |
6301 | if (Tag->isBeingDefined()) |
6302 | IsBeingInstantiated = true; |
6303 | if (!Tag->isBeingDefined() && |
6304 | RequireCompleteType(Loc, T, DiagID: diag::err_incomplete_type)) |
6305 | return nullptr; |
6306 | |
6307 | ParentDC = Tag->getDecl(); |
6308 | } |
6309 | } |
6310 | |
6311 | NamedDecl *Result = nullptr; |
6312 | // FIXME: If the name is a dependent name, this lookup won't necessarily |
6313 | // find it. Does that ever matter? |
6314 | if (auto Name = D->getDeclName()) { |
6315 | DeclarationNameInfo NameInfo(Name, D->getLocation()); |
6316 | DeclarationNameInfo NewNameInfo = |
6317 | SubstDeclarationNameInfo(NameInfo, TemplateArgs); |
6318 | Name = NewNameInfo.getName(); |
6319 | if (!Name) |
6320 | return nullptr; |
6321 | DeclContext::lookup_result Found = ParentDC->lookup(Name); |
6322 | |
6323 | Result = findInstantiationOf(Ctx&: Context, D, first: Found.begin(), last: Found.end()); |
6324 | } else { |
6325 | // Since we don't have a name for the entity we're looking for, |
6326 | // our only option is to walk through all of the declarations to |
6327 | // find that name. This will occur in a few cases: |
6328 | // |
6329 | // - anonymous struct/union within a template |
6330 | // - unnamed class/struct/union/enum within a template |
6331 | // |
6332 | // FIXME: Find a better way to find these instantiations! |
6333 | Result = findInstantiationOf(Ctx&: Context, D, |
6334 | first: ParentDC->decls_begin(), |
6335 | last: ParentDC->decls_end()); |
6336 | } |
6337 | |
6338 | if (!Result) { |
6339 | if (isa<UsingShadowDecl>(Val: D)) { |
6340 | // UsingShadowDecls can instantiate to nothing because of using hiding. |
6341 | } else if (hasUncompilableErrorOccurred()) { |
6342 | // We've already complained about some ill-formed code, so most likely |
6343 | // this declaration failed to instantiate. There's no point in |
6344 | // complaining further, since this is normal in invalid code. |
6345 | // FIXME: Use more fine-grained 'invalid' tracking for this. |
6346 | } else if (IsBeingInstantiated) { |
6347 | // The class in which this member exists is currently being |
6348 | // instantiated, and we haven't gotten around to instantiating this |
6349 | // member yet. This can happen when the code uses forward declarations |
6350 | // of member classes, and introduces ordering dependencies via |
6351 | // template instantiation. |
6352 | Diag(Loc, DiagID: diag::err_member_not_yet_instantiated) |
6353 | << D->getDeclName() |
6354 | << Context.getTypeDeclType(Decl: cast<CXXRecordDecl>(Val: ParentDC)); |
6355 | Diag(Loc: D->getLocation(), DiagID: diag::note_non_instantiated_member_here); |
6356 | } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(Val: D)) { |
6357 | // This enumeration constant was found when the template was defined, |
6358 | // but can't be found in the instantiation. This can happen if an |
6359 | // unscoped enumeration member is explicitly specialized. |
6360 | EnumDecl *Enum = cast<EnumDecl>(Val: ED->getLexicalDeclContext()); |
6361 | EnumDecl *Spec = cast<EnumDecl>(Val: FindInstantiatedDecl(Loc, D: Enum, |
6362 | TemplateArgs)); |
6363 | assert(Spec->getTemplateSpecializationKind() == |
6364 | TSK_ExplicitSpecialization); |
6365 | Diag(Loc, DiagID: diag::err_enumerator_does_not_exist) |
6366 | << D->getDeclName() |
6367 | << Context.getTypeDeclType(Decl: cast<TypeDecl>(Val: Spec->getDeclContext())); |
6368 | Diag(Loc: Spec->getLocation(), DiagID: diag::note_enum_specialized_here) |
6369 | << Context.getTypeDeclType(Decl: Spec); |
6370 | } else { |
6371 | // We should have found something, but didn't. |
6372 | llvm_unreachable("Unable to find instantiation of declaration!" ); |
6373 | } |
6374 | } |
6375 | |
6376 | D = Result; |
6377 | } |
6378 | |
6379 | return D; |
6380 | } |
6381 | |
6382 | void Sema::PerformPendingInstantiations(bool LocalOnly) { |
6383 | std::deque<PendingImplicitInstantiation> delayedPCHInstantiations; |
6384 | while (!PendingLocalImplicitInstantiations.empty() || |
6385 | (!LocalOnly && !PendingInstantiations.empty())) { |
6386 | PendingImplicitInstantiation Inst; |
6387 | |
6388 | if (PendingLocalImplicitInstantiations.empty()) { |
6389 | Inst = PendingInstantiations.front(); |
6390 | PendingInstantiations.pop_front(); |
6391 | } else { |
6392 | Inst = PendingLocalImplicitInstantiations.front(); |
6393 | PendingLocalImplicitInstantiations.pop_front(); |
6394 | } |
6395 | |
6396 | // Instantiate function definitions |
6397 | if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Inst.first)) { |
6398 | bool DefinitionRequired = Function->getTemplateSpecializationKind() == |
6399 | TSK_ExplicitInstantiationDefinition; |
6400 | if (Function->isMultiVersion()) { |
6401 | getASTContext().forEachMultiversionedFunctionVersion( |
6402 | FD: Function, Pred: [this, Inst, DefinitionRequired](FunctionDecl *CurFD) { |
6403 | InstantiateFunctionDefinition(/*FIXME:*/ PointOfInstantiation: Inst.second, Function: CurFD, Recursive: true, |
6404 | DefinitionRequired, AtEndOfTU: true); |
6405 | if (CurFD->isDefined()) |
6406 | CurFD->setInstantiationIsPending(false); |
6407 | }); |
6408 | } else { |
6409 | InstantiateFunctionDefinition(/*FIXME:*/ PointOfInstantiation: Inst.second, Function, Recursive: true, |
6410 | DefinitionRequired, AtEndOfTU: true); |
6411 | if (Function->isDefined()) |
6412 | Function->setInstantiationIsPending(false); |
6413 | } |
6414 | // Definition of a PCH-ed template declaration may be available only in the TU. |
6415 | if (!LocalOnly && LangOpts.PCHInstantiateTemplates && |
6416 | TUKind == TU_Prefix && Function->instantiationIsPending()) |
6417 | delayedPCHInstantiations.push_back(x: Inst); |
6418 | continue; |
6419 | } |
6420 | |
6421 | // Instantiate variable definitions |
6422 | VarDecl *Var = cast<VarDecl>(Val: Inst.first); |
6423 | |
6424 | assert((Var->isStaticDataMember() || |
6425 | isa<VarTemplateSpecializationDecl>(Var)) && |
6426 | "Not a static data member, nor a variable template" |
6427 | " specialization?" ); |
6428 | |
6429 | // Don't try to instantiate declarations if the most recent redeclaration |
6430 | // is invalid. |
6431 | if (Var->getMostRecentDecl()->isInvalidDecl()) |
6432 | continue; |
6433 | |
6434 | // Check if the most recent declaration has changed the specialization kind |
6435 | // and removed the need for implicit instantiation. |
6436 | switch (Var->getMostRecentDecl() |
6437 | ->getTemplateSpecializationKindForInstantiation()) { |
6438 | case TSK_Undeclared: |
6439 | llvm_unreachable("Cannot instantitiate an undeclared specialization." ); |
6440 | case TSK_ExplicitInstantiationDeclaration: |
6441 | case TSK_ExplicitSpecialization: |
6442 | continue; // No longer need to instantiate this type. |
6443 | case TSK_ExplicitInstantiationDefinition: |
6444 | // We only need an instantiation if the pending instantiation *is* the |
6445 | // explicit instantiation. |
6446 | if (Var != Var->getMostRecentDecl()) |
6447 | continue; |
6448 | break; |
6449 | case TSK_ImplicitInstantiation: |
6450 | break; |
6451 | } |
6452 | |
6453 | PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), |
6454 | "instantiating variable definition" ); |
6455 | bool DefinitionRequired = Var->getTemplateSpecializationKind() == |
6456 | TSK_ExplicitInstantiationDefinition; |
6457 | |
6458 | // Instantiate static data member definitions or variable template |
6459 | // specializations. |
6460 | InstantiateVariableDefinition(/*FIXME:*/ PointOfInstantiation: Inst.second, Var, Recursive: true, |
6461 | DefinitionRequired, AtEndOfTU: true); |
6462 | } |
6463 | |
6464 | if (!LocalOnly && LangOpts.PCHInstantiateTemplates) |
6465 | PendingInstantiations.swap(x&: delayedPCHInstantiations); |
6466 | } |
6467 | |
6468 | void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, |
6469 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
6470 | for (auto *DD : Pattern->ddiags()) { |
6471 | switch (DD->getKind()) { |
6472 | case DependentDiagnostic::Access: |
6473 | HandleDependentAccessCheck(DD: *DD, TemplateArgs); |
6474 | break; |
6475 | } |
6476 | } |
6477 | } |
6478 | |