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