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