Bug Summary

File:build/source/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 5582, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiateDecl.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1680300532 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-04-01-083001-16331-1 -x c++ /build/source/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

/build/source/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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