Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 5560, 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/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/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-16/lib/clang/16.0.0/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/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -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/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -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-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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