Bug Summary

File:tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 1845, column 33
Access to field 'TypeAsWritten' results in a dereference of a null pointer (loaded from field 'ExplicitInfo')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiateDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn326061/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326061/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326061/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326061/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326061/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn326061/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-02-26-041543-15277-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326061/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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

/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h

1//===- DeclTemplate.h - Classes for representing C++ templates --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// \brief Defines the C++ template declaration subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
16#define LLVM_CLANG_AST_DECLTEMPLATE_H
17
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/TemplateBase.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/LLVM.h"
26#include "clang/Basic/SourceLocation.h"
27#include "clang/Basic/Specifiers.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/PointerIntPair.h"
31#include "llvm/ADT/PointerUnion.h"
32#include "llvm/ADT/iterator.h"
33#include "llvm/ADT/iterator_range.h"
34#include "llvm/Support/Casting.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/TrailingObjects.h"
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <iterator>
41#include <utility>
42
43namespace clang {
44
45enum BuiltinTemplateKind : int;
46class ClassTemplateDecl;
47class ClassTemplatePartialSpecializationDecl;
48class Expr;
49class FunctionTemplateDecl;
50class IdentifierInfo;
51class NonTypeTemplateParmDecl;
52class TemplateDecl;
53class TemplateTemplateParmDecl;
54class TemplateTypeParmDecl;
55class UnresolvedSetImpl;
56class VarTemplateDecl;
57class VarTemplatePartialSpecializationDecl;
58
59/// \brief Stores a template parameter of any kind.
60using TemplateParameter =
61 llvm::PointerUnion3<TemplateTypeParmDecl *, NonTypeTemplateParmDecl *,
62 TemplateTemplateParmDecl *>;
63
64NamedDecl *getAsNamedDecl(TemplateParameter P);
65
66/// \brief Stores a list of template parameters for a TemplateDecl and its
67/// derived classes.
68class TemplateParameterList final
69 : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *,
70 Expr *> {
71 /// The location of the 'template' keyword.
72 SourceLocation TemplateLoc;
73
74 /// The locations of the '<' and '>' angle brackets.
75 SourceLocation LAngleLoc, RAngleLoc;
76
77 /// The number of template parameters in this template
78 /// parameter list.
79 unsigned NumParams : 30;
80
81 /// Whether this template parameter list contains an unexpanded parameter
82 /// pack.
83 unsigned ContainsUnexpandedParameterPack : 1;
84
85 /// Whether this template parameter list has an associated requires-clause
86 unsigned HasRequiresClause : 1;
87
88protected:
89 TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
90 ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc,
91 Expr *RequiresClause);
92
93 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
94 return NumParams;
95 }
96
97 size_t numTrailingObjects(OverloadToken<Expr *>) const {
98 return HasRequiresClause;
99 }
100
101public:
102 template <size_t N, bool HasRequiresClause>
103 friend class FixedSizeTemplateParameterListStorage;
104 friend TrailingObjects;
105
106 static TemplateParameterList *Create(const ASTContext &C,
107 SourceLocation TemplateLoc,
108 SourceLocation LAngleLoc,
109 ArrayRef<NamedDecl *> Params,
110 SourceLocation RAngleLoc,
111 Expr *RequiresClause);
112
113 /// \brief Iterates through the template parameters in this list.
114 using iterator = NamedDecl **;
115
116 /// \brief Iterates through the template parameters in this list.
117 using const_iterator = NamedDecl * const *;
118
119 iterator begin() { return getTrailingObjects<NamedDecl *>(); }
120 const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
121 iterator end() { return begin() + NumParams; }
122 const_iterator end() const { return begin() + NumParams; }
123
124 unsigned size() const { return NumParams; }
125
126 ArrayRef<NamedDecl*> asArray() {
127 return llvm::makeArrayRef(begin(), end());
128 }
129 ArrayRef<const NamedDecl*> asArray() const {
130 return llvm::makeArrayRef(begin(), size());
131 }
132
133 NamedDecl* getParam(unsigned Idx) {
134 assert(Idx < size() && "Template parameter index out-of-range")(static_cast <bool> (Idx < size() && "Template parameter index out-of-range"
) ? void (0) : __assert_fail ("Idx < size() && \"Template parameter index out-of-range\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 134, __extension__ __PRETTY_FUNCTION__))
;
135 return begin()[Idx];
136 }
137 const NamedDecl* getParam(unsigned Idx) const {
138 assert(Idx < size() && "Template parameter index out-of-range")(static_cast <bool> (Idx < size() && "Template parameter index out-of-range"
) ? void (0) : __assert_fail ("Idx < size() && \"Template parameter index out-of-range\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 138, __extension__ __PRETTY_FUNCTION__))
;
139 return begin()[Idx];
140 }
141
142 /// \brief Returns the minimum number of arguments needed to form a
143 /// template specialization.
144 ///
145 /// This may be fewer than the number of template parameters, if some of
146 /// the parameters have default arguments or if there is a parameter pack.
147 unsigned getMinRequiredArguments() const;
148
149 /// \brief Get the depth of this template parameter list in the set of
150 /// template parameter lists.
151 ///
152 /// The first template parameter list in a declaration will have depth 0,
153 /// the second template parameter list will have depth 1, etc.
154 unsigned getDepth() const;
155
156 /// \brief Determine whether this template parameter list contains an
157 /// unexpanded parameter pack.
158 bool containsUnexpandedParameterPack() const {
159 return ContainsUnexpandedParameterPack;
160 }
161
162 /// \brief The constraint-expression of the associated requires-clause.
163 Expr *getRequiresClause() {
164 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
165 }
166
167 /// \brief The constraint-expression of the associated requires-clause.
168 const Expr *getRequiresClause() const {
169 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
170 }
171
172 SourceLocation getTemplateLoc() const { return TemplateLoc; }
173 SourceLocation getLAngleLoc() const { return LAngleLoc; }
174 SourceLocation getRAngleLoc() const { return RAngleLoc; }
175
176 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
177 return SourceRange(TemplateLoc, RAngleLoc);
178 }
179
180public:
181 // FIXME: workaround for MSVC 2013; remove when no longer needed
182 using FixedSizeStorageOwner = TrailingObjects::FixedSizeStorageOwner;
183};
184
185/// \brief Stores a list of template parameters and the associated
186/// requires-clause (if any) for a TemplateDecl and its derived classes.
187/// Suitable for creating on the stack.
188template <size_t N, bool HasRequiresClause>
189class FixedSizeTemplateParameterListStorage
190 : public TemplateParameterList::FixedSizeStorageOwner {
191 typename TemplateParameterList::FixedSizeStorage<
192 NamedDecl *, Expr *>::with_counts<
193 N, HasRequiresClause ? 1u : 0u
194 >::type storage;
195
196public:
197 FixedSizeTemplateParameterListStorage(SourceLocation TemplateLoc,
198 SourceLocation LAngleLoc,
199 ArrayRef<NamedDecl *> Params,
200 SourceLocation RAngleLoc,
201 Expr *RequiresClause)
202 : FixedSizeStorageOwner(
203 (assert(N == Params.size())(static_cast <bool> (N == Params.size()) ? void (0) : __assert_fail
("N == Params.size()", "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 203, __extension__ __PRETTY_FUNCTION__))
,
204 assert(HasRequiresClause == static_cast<bool>(RequiresClause))(static_cast <bool> (HasRequiresClause == static_cast<
bool>(RequiresClause)) ? void (0) : __assert_fail ("HasRequiresClause == static_cast<bool>(RequiresClause)"
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 204, __extension__ __PRETTY_FUNCTION__))
,
205 new (static_cast<void *>(&storage)) TemplateParameterList(
206 TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause))) {}
207};
208
209/// \brief A template argument list.
210class TemplateArgumentList final
211 : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
212 /// \brief The template argument list.
213 const TemplateArgument *Arguments;
214
215 /// \brief The number of template arguments in this template
216 /// argument list.
217 unsigned NumArguments;
218
219 // Constructs an instance with an internal Argument list, containing
220 // a copy of the Args array. (Called by CreateCopy)
221 TemplateArgumentList(ArrayRef<TemplateArgument> Args);
222
223public:
224 friend TrailingObjects;
225
226 TemplateArgumentList(const TemplateArgumentList &) = delete;
227 TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
228
229 /// \brief Type used to indicate that the template argument list itself is a
230 /// stack object. It does not own its template arguments.
231 enum OnStackType { OnStack };
232
233 /// \brief Create a new template argument list that copies the given set of
234 /// template arguments.
235 static TemplateArgumentList *CreateCopy(ASTContext &Context,
236 ArrayRef<TemplateArgument> Args);
237
238 /// \brief Construct a new, temporary template argument list on the stack.
239 ///
240 /// The template argument list does not own the template arguments
241 /// provided.
242 explicit TemplateArgumentList(OnStackType, ArrayRef<TemplateArgument> Args)
243 : Arguments(Args.data()), NumArguments(Args.size()) {}
244
245 /// \brief Produces a shallow copy of the given template argument list.
246 ///
247 /// This operation assumes that the input argument list outlives it.
248 /// This takes the list as a pointer to avoid looking like a copy
249 /// constructor, since this really really isn't safe to use that
250 /// way.
251 explicit TemplateArgumentList(const TemplateArgumentList *Other)
252 : Arguments(Other->data()), NumArguments(Other->size()) {}
253
254 /// \brief Retrieve the template argument at a given index.
255 const TemplateArgument &get(unsigned Idx) const {
256 assert(Idx < NumArguments && "Invalid template argument index")(static_cast <bool> (Idx < NumArguments && "Invalid template argument index"
) ? void (0) : __assert_fail ("Idx < NumArguments && \"Invalid template argument index\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 256, __extension__ __PRETTY_FUNCTION__))
;
257 return data()[Idx];
258 }
259
260 /// \brief Retrieve the template argument at a given index.
261 const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
262
263 /// \brief Produce this as an array ref.
264 ArrayRef<TemplateArgument> asArray() const {
265 return llvm::makeArrayRef(data(), size());
266 }
267
268 /// \brief Retrieve the number of template arguments in this
269 /// template argument list.
270 unsigned size() const { return NumArguments; }
271
272 /// \brief Retrieve a pointer to the template argument list.
273 const TemplateArgument *data() const { return Arguments; }
274};
275
276void *allocateDefaultArgStorageChain(const ASTContext &C);
277
278/// Storage for a default argument. This is conceptually either empty, or an
279/// argument value, or a pointer to a previous declaration that had a default
280/// argument.
281///
282/// However, this is complicated by modules: while we require all the default
283/// arguments for a template to be equivalent, there may be more than one, and
284/// we need to track all the originating parameters to determine if the default
285/// argument is visible.
286template<typename ParmDecl, typename ArgType>
287class DefaultArgStorage {
288 /// Storage for both the value *and* another parameter from which we inherit
289 /// the default argument. This is used when multiple default arguments for a
290 /// parameter are merged together from different modules.
291 struct Chain {
292 ParmDecl *PrevDeclWithDefaultArg;
293 ArgType Value;
294 };
295 static_assert(sizeof(Chain) == sizeof(void *) * 2,
296 "non-pointer argument type?");
297
298 llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
299
300 static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
301 const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
302 if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl*>())
303 Parm = Prev;
304 assert(!Parm->getDefaultArgStorage()(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
305 .ValueOrInherited.template is<ParmDecl *>() &&(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
306 "should only be one level of indirection")(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
;
307 return Parm;
308 }
309
310public:
311 DefaultArgStorage() : ValueOrInherited(ArgType()) {}
312
313 /// Determine whether there is a default argument for this parameter.
314 bool isSet() const { return !ValueOrInherited.isNull(); }
315
316 /// Determine whether the default argument for this parameter was inherited
317 /// from a previous declaration of the same entity.
318 bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
319
320 /// Get the default argument's value. This does not consider whether the
321 /// default argument is visible.
322 ArgType get() const {
323 const DefaultArgStorage *Storage = this;
324 if (auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl*>())
325 Storage = &Prev->getDefaultArgStorage();
326 if (auto *C = Storage->ValueOrInherited.template dyn_cast<Chain*>())
327 return C->Value;
328 return Storage->ValueOrInherited.template get<ArgType>();
329 }
330
331 /// Get the parameter from which we inherit the default argument, if any.
332 /// This is the parameter on which the default argument was actually written.
333 const ParmDecl *getInheritedFrom() const {
334 if (auto *D = ValueOrInherited.template dyn_cast<ParmDecl*>())
335 return D;
336 if (auto *C = ValueOrInherited.template dyn_cast<Chain*>())
337 return C->PrevDeclWithDefaultArg;
338 return nullptr;
339 }
340
341 /// Set the default argument.
342 void set(ArgType Arg) {
343 assert(!isSet() && "default argument already set")(static_cast <bool> (!isSet() && "default argument already set"
) ? void (0) : __assert_fail ("!isSet() && \"default argument already set\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 343, __extension__ __PRETTY_FUNCTION__))
;
344 ValueOrInherited = Arg;
345 }
346
347 /// Set that the default argument was inherited from another parameter.
348 void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
349 assert(!isInherited() && "default argument already inherited")(static_cast <bool> (!isInherited() && "default argument already inherited"
) ? void (0) : __assert_fail ("!isInherited() && \"default argument already inherited\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 349, __extension__ __PRETTY_FUNCTION__))
;
350 InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
351 if (!isSet())
352 ValueOrInherited = InheritedFrom;
353 else
354 ValueOrInherited = new (allocateDefaultArgStorageChain(C))
355 Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
356 }
357
358 /// Remove the default argument, even if it was inherited.
359 void clear() {
360 ValueOrInherited = ArgType();
361 }
362};
363
364//===----------------------------------------------------------------------===//
365// Kinds of Templates
366//===----------------------------------------------------------------------===//
367
368/// \brief Stores the template parameter list and associated constraints for
369/// \c TemplateDecl objects that track associated constraints.
370class ConstrainedTemplateDeclInfo {
371 friend TemplateDecl;
372
373public:
374 ConstrainedTemplateDeclInfo() = default;
375
376 TemplateParameterList *getTemplateParameters() const {
377 return TemplateParams;
378 }
379
380 Expr *getAssociatedConstraints() const { return AssociatedConstraints; }
381
382protected:
383 void setTemplateParameters(TemplateParameterList *TParams) {
384 TemplateParams = TParams;
385 }
386
387 void setAssociatedConstraints(Expr *AC) { AssociatedConstraints = AC; }
388
389 TemplateParameterList *TemplateParams = nullptr;
390 Expr *AssociatedConstraints = nullptr;
391};
392
393
394/// \brief The base class of all kinds of template declarations (e.g.,
395/// class, function, etc.).
396///
397/// The TemplateDecl class stores the list of template parameters and a
398/// reference to the templated scoped declaration: the underlying AST node.
399class TemplateDecl : public NamedDecl {
400 void anchor() override;
401
402protected:
403 // Construct a template decl with the given name and parameters.
404 // Used when there is no templated element (e.g., for tt-params).
405 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
406 SourceLocation L, DeclarationName Name,
407 TemplateParameterList *Params)
408 : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
409 TemplateParams(CTDI) {
410 this->setTemplateParameters(Params);
411 }
412
413 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
414 TemplateParameterList *Params)
415 : TemplateDecl(nullptr, DK, DC, L, Name, Params) {}
416
417 // Construct a template decl with name, parameters, and templated element.
418 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
419 SourceLocation L, DeclarationName Name,
420 TemplateParameterList *Params, NamedDecl *Decl)
421 : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
422 TemplateParams(CTDI) {
423 this->setTemplateParameters(Params);
424 }
425
426 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
427 TemplateParameterList *Params, NamedDecl *Decl)
428 : TemplateDecl(nullptr, DK, DC, L, Name, Params, Decl) {}
429
430public:
431 /// Get the list of template parameters
432 TemplateParameterList *getTemplateParameters() const {
433 const auto *const CTDI =
434 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
435 return CTDI ? CTDI->getTemplateParameters()
436 : TemplateParams.get<TemplateParameterList *>();
437 }
438
439 /// Get the constraint-expression from the associated requires-clause (if any)
440 const Expr *getRequiresClause() const {
441 const TemplateParameterList *const TP = getTemplateParameters();
442 return TP ? TP->getRequiresClause() : nullptr;
443 }
444
445 Expr *getAssociatedConstraints() const {
446 const TemplateDecl *const C = cast<TemplateDecl>(getCanonicalDecl());
447 const auto *const CTDI =
448 C->TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
449 return CTDI ? CTDI->getAssociatedConstraints() : nullptr;
450 }
451
452 /// Get the underlying, templated declaration.
453 NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
454
455 // Implement isa/cast/dyncast/etc.
456 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
457
458 static bool classofKind(Kind K) {
459 return K >= firstTemplate && K <= lastTemplate;
460 }
461
462 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
463 return SourceRange(getTemplateParameters()->getTemplateLoc(),
464 TemplatedDecl->getSourceRange().getEnd());
465 }
466
467protected:
468 NamedDecl *TemplatedDecl;
469 /// \brief The template parameter list and optional requires-clause
470 /// associated with this declaration; alternatively, a
471 /// \c ConstrainedTemplateDeclInfo if the associated constraints of the
472 /// template are being tracked by this particular declaration.
473 llvm::PointerUnion<TemplateParameterList *,
474 ConstrainedTemplateDeclInfo *>
475 TemplateParams;
476
477 void setTemplateParameters(TemplateParameterList *TParams) {
478 if (auto *const CTDI =
479 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>()) {
480 CTDI->setTemplateParameters(TParams);
481 } else {
482 TemplateParams = TParams;
483 }
484 }
485
486 void setAssociatedConstraints(Expr *AC) {
487 assert(isCanonicalDecl() &&(static_cast <bool> (isCanonicalDecl() && "Attaching associated constraints to non-canonical Decl"
) ? void (0) : __assert_fail ("isCanonicalDecl() && \"Attaching associated constraints to non-canonical Decl\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 488, __extension__ __PRETTY_FUNCTION__))
488 "Attaching associated constraints to non-canonical Decl")(static_cast <bool> (isCanonicalDecl() && "Attaching associated constraints to non-canonical Decl"
) ? void (0) : __assert_fail ("isCanonicalDecl() && \"Attaching associated constraints to non-canonical Decl\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 488, __extension__ __PRETTY_FUNCTION__))
;
489 TemplateParams.get<ConstrainedTemplateDeclInfo *>()
490 ->setAssociatedConstraints(AC);
491 }
492
493public:
494 /// \brief Initialize the underlying templated declaration and
495 /// template parameters.
496 void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
497 assert(!TemplatedDecl && "TemplatedDecl already set!")(static_cast <bool> (!TemplatedDecl && "TemplatedDecl already set!"
) ? void (0) : __assert_fail ("!TemplatedDecl && \"TemplatedDecl already set!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 497, __extension__ __PRETTY_FUNCTION__))
;
498 assert(!TemplateParams && "TemplateParams already set!")(static_cast <bool> (!TemplateParams && "TemplateParams already set!"
) ? void (0) : __assert_fail ("!TemplateParams && \"TemplateParams already set!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 498, __extension__ __PRETTY_FUNCTION__))
;
499 TemplatedDecl = templatedDecl;
500 TemplateParams = templateParams;
501 }
502};
503
504/// \brief Provides information about a function template specialization,
505/// which is a FunctionDecl that has been explicitly specialization or
506/// instantiated from a function template.
507class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
508 FunctionTemplateSpecializationInfo(FunctionDecl *FD,
509 FunctionTemplateDecl *Template,
510 TemplateSpecializationKind TSK,
511 const TemplateArgumentList *TemplateArgs,
512 const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
513 SourceLocation POI)
514 : Function(FD), Template(Template, TSK - 1),
515 TemplateArguments(TemplateArgs),
516 TemplateArgumentsAsWritten(TemplateArgsAsWritten),
517 PointOfInstantiation(POI) {}
518
519public:
520 static FunctionTemplateSpecializationInfo *
521 Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
522 TemplateSpecializationKind TSK,
523 const TemplateArgumentList *TemplateArgs,
524 const TemplateArgumentListInfo *TemplateArgsAsWritten,
525 SourceLocation POI);
526
527 /// \brief The function template specialization that this structure
528 /// describes.
529 FunctionDecl *Function;
530
531 /// \brief The function template from which this function template
532 /// specialization was generated.
533 ///
534 /// The two bits contain the top 4 values of TemplateSpecializationKind.
535 llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
536
537 /// \brief The template arguments used to produce the function template
538 /// specialization from the function template.
539 const TemplateArgumentList *TemplateArguments;
540
541 /// \brief The template arguments as written in the sources, if provided.
542 const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
543
544 /// \brief The point at which this function template specialization was
545 /// first instantiated.
546 SourceLocation PointOfInstantiation;
547
548 /// \brief Retrieve the template from which this function was specialized.
549 FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
550
551 /// \brief Determine what kind of template specialization this is.
552 TemplateSpecializationKind getTemplateSpecializationKind() const {
553 return (TemplateSpecializationKind)(Template.getInt() + 1);
554 }
555
556 bool isExplicitSpecialization() const {
557 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
558 }
559
560 /// \brief True if this declaration is an explicit specialization,
561 /// explicit instantiation declaration, or explicit instantiation
562 /// definition.
563 bool isExplicitInstantiationOrSpecialization() const {
564 return isTemplateExplicitInstantiationOrSpecialization(
565 getTemplateSpecializationKind());
566 }
567
568 /// \brief Set the template specialization kind.
569 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
570 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode TSK_Undeclared for a function template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 571, __extension__ __PRETTY_FUNCTION__))
571 "Cannot encode TSK_Undeclared for a function template specialization")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode TSK_Undeclared for a function template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 571, __extension__ __PRETTY_FUNCTION__))
;
572 Template.setInt(TSK - 1);
573 }
574
575 /// \brief Retrieve the first point of instantiation of this function
576 /// template specialization.
577 ///
578 /// The point of instantiation may be an invalid source location if this
579 /// function has yet to be instantiated.
580 SourceLocation getPointOfInstantiation() const {
581 return PointOfInstantiation;
582 }
583
584 /// \brief Set the (first) point of instantiation of this function template
585 /// specialization.
586 void setPointOfInstantiation(SourceLocation POI) {
587 PointOfInstantiation = POI;
588 }
589
590 void Profile(llvm::FoldingSetNodeID &ID) {
591 Profile(ID, TemplateArguments->asArray(),
592 Function->getASTContext());
593 }
594
595 static void
596 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
597 ASTContext &Context) {
598 ID.AddInteger(TemplateArgs.size());
599 for (const TemplateArgument &TemplateArg : TemplateArgs)
600 TemplateArg.Profile(ID, Context);
601 }
602};
603
604/// \brief Provides information a specialization of a member of a class
605/// template, which may be a member function, static data member,
606/// member class or member enumeration.
607class MemberSpecializationInfo {
608 // The member declaration from which this member was instantiated, and the
609 // manner in which the instantiation occurred (in the lower two bits).
610 llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
611
612 // The point at which this member was first instantiated.
613 SourceLocation PointOfInstantiation;
614
615public:
616 explicit
617 MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
618 SourceLocation POI = SourceLocation())
619 : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
620 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 621, __extension__ __PRETTY_FUNCTION__))
621 "Cannot encode undeclared template specializations for members")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 621, __extension__ __PRETTY_FUNCTION__))
;
622 }
623
624 /// \brief Retrieve the member declaration from which this member was
625 /// instantiated.
626 NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
627
628 /// \brief Determine what kind of template specialization this is.
629 TemplateSpecializationKind getTemplateSpecializationKind() const {
630 return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
631 }
632
633 bool isExplicitSpecialization() const {
634 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
635 }
636
637 /// \brief Set the template specialization kind.
638 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
639 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 640, __extension__ __PRETTY_FUNCTION__))
640 "Cannot encode undeclared template specializations for members")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 640, __extension__ __PRETTY_FUNCTION__))
;
641 MemberAndTSK.setInt(TSK - 1);
642 }
643
644 /// \brief Retrieve the first point of instantiation of this member.
645 /// If the point of instantiation is an invalid location, then this member
646 /// has not yet been instantiated.
647 SourceLocation getPointOfInstantiation() const {
648 return PointOfInstantiation;
649 }
650
651 /// \brief Set the first point of instantiation.
652 void setPointOfInstantiation(SourceLocation POI) {
653 PointOfInstantiation = POI;
654 }
655};
656
657/// \brief Provides information about a dependent function-template
658/// specialization declaration.
659///
660/// Since explicit function template specialization and instantiation
661/// declarations can only appear in namespace scope, and you can only
662/// specialize a member of a fully-specialized class, the only way to
663/// get one of these is in a friend declaration like the following:
664///
665/// \code
666/// template \<class T> void foo(T);
667/// template \<class T> class A {
668/// friend void foo<>(T);
669/// };
670/// \endcode
671class DependentFunctionTemplateSpecializationInfo final
672 : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
673 TemplateArgumentLoc,
674 FunctionTemplateDecl *> {
675 /// The number of potential template candidates.
676 unsigned NumTemplates;
677
678 /// The number of template arguments.
679 unsigned NumArgs;
680
681 /// The locations of the left and right angle brackets.
682 SourceRange AngleLocs;
683
684 size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
685 return NumArgs;
686 }
687 size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
688 return NumTemplates;
689 }
690
691 DependentFunctionTemplateSpecializationInfo(
692 const UnresolvedSetImpl &Templates,
693 const TemplateArgumentListInfo &TemplateArgs);
694
695public:
696 friend TrailingObjects;
697
698 static DependentFunctionTemplateSpecializationInfo *
699 Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
700 const TemplateArgumentListInfo &TemplateArgs);
701
702 /// \brief Returns the number of function templates that this might
703 /// be a specialization of.
704 unsigned getNumTemplates() const { return NumTemplates; }
705
706 /// \brief Returns the i'th template candidate.
707 FunctionTemplateDecl *getTemplate(unsigned I) const {
708 assert(I < getNumTemplates() && "template index out of range")(static_cast <bool> (I < getNumTemplates() &&
"template index out of range") ? void (0) : __assert_fail ("I < getNumTemplates() && \"template index out of range\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 708, __extension__ __PRETTY_FUNCTION__))
;
709 return getTrailingObjects<FunctionTemplateDecl *>()[I];
710 }
711
712 /// \brief Returns the explicit template arguments that were given.
713 const TemplateArgumentLoc *getTemplateArgs() const {
714 return getTrailingObjects<TemplateArgumentLoc>();
715 }
716
717 /// \brief Returns the number of explicit template arguments that were given.
718 unsigned getNumTemplateArgs() const { return NumArgs; }
719
720 /// \brief Returns the nth template argument.
721 const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
722 assert(I < getNumTemplateArgs() && "template arg index out of range")(static_cast <bool> (I < getNumTemplateArgs() &&
"template arg index out of range") ? void (0) : __assert_fail
("I < getNumTemplateArgs() && \"template arg index out of range\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 722, __extension__ __PRETTY_FUNCTION__))
;
723 return getTemplateArgs()[I];
724 }
725
726 SourceLocation getLAngleLoc() const {
727 return AngleLocs.getBegin();
728 }
729
730 SourceLocation getRAngleLoc() const {
731 return AngleLocs.getEnd();
732 }
733};
734
735/// Declaration of a redeclarable template.
736class RedeclarableTemplateDecl : public TemplateDecl,
737 public Redeclarable<RedeclarableTemplateDecl>
738{
739 using redeclarable_base = Redeclarable<RedeclarableTemplateDecl>;
740
741 RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
742 return getNextRedeclaration();
743 }
744
745 RedeclarableTemplateDecl *getPreviousDeclImpl() override {
746 return getPreviousDecl();
747 }
748
749 RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
750 return getMostRecentDecl();
751 }
752
753protected:
754 template <typename EntryType> struct SpecEntryTraits {
755 using DeclType = EntryType;
756
757 static DeclType *getDecl(EntryType *D) {
758 return D;
759 }
760
761 static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
762 return D->getTemplateArgs().asArray();
763 }
764 };
765
766 template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
767 typename DeclType = typename SETraits::DeclType>
768 struct SpecIterator
769 : llvm::iterator_adaptor_base<
770 SpecIterator<EntryType, SETraits, DeclType>,
771 typename llvm::FoldingSetVector<EntryType>::iterator,
772 typename std::iterator_traits<typename llvm::FoldingSetVector<
773 EntryType>::iterator>::iterator_category,
774 DeclType *, ptrdiff_t, DeclType *, DeclType *> {
775 SpecIterator() = default;
776 explicit SpecIterator(
777 typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
778 : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
779
780 DeclType *operator*() const {
781 return SETraits::getDecl(&*this->I)->getMostRecentDecl();
782 }
783
784 DeclType *operator->() const { return **this; }
785 };
786
787 template <typename EntryType>
788 static SpecIterator<EntryType>
789 makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
790 return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
791 }
792
793 void loadLazySpecializationsImpl() const;
794
795 template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
796 findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
797 ArrayRef<TemplateArgument> Args, void *&InsertPos);
798
799 template <class Derived, class EntryType>
800 void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
801 EntryType *Entry, void *InsertPos);
802
803 struct CommonBase {
804 CommonBase() : InstantiatedFromMember(nullptr, false) {}
805
806 /// \brief The template from which this was most
807 /// directly instantiated (or null).
808 ///
809 /// The boolean value indicates whether this template
810 /// was explicitly specialized.
811 llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
812 InstantiatedFromMember;
813
814 /// \brief If non-null, points to an array of specializations (including
815 /// partial specializations) known only by their external declaration IDs.
816 ///
817 /// The first value in the array is the number of specializations/partial
818 /// specializations that follow.
819 uint32_t *LazySpecializations = nullptr;
820 };
821
822 /// \brief Pointer to the common data shared by all declarations of this
823 /// template.
824 mutable CommonBase *Common = nullptr;
825
826 /// \brief Retrieves the "common" pointer shared by all (re-)declarations of
827 /// the same template. Calling this routine may implicitly allocate memory
828 /// for the common pointer.
829 CommonBase *getCommonPtr() const;
830
831 virtual CommonBase *newCommon(ASTContext &C) const = 0;
832
833 // Construct a template decl with name, parameters, and templated element.
834 RedeclarableTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK,
835 ASTContext &C, DeclContext *DC, SourceLocation L,
836 DeclarationName Name, TemplateParameterList *Params,
837 NamedDecl *Decl)
838 : TemplateDecl(CTDI, DK, DC, L, Name, Params, Decl), redeclarable_base(C)
839 {}
840
841 RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
842 SourceLocation L, DeclarationName Name,
843 TemplateParameterList *Params, NamedDecl *Decl)
844 : RedeclarableTemplateDecl(nullptr, DK, C, DC, L, Name, Params, Decl) {}
845
846public:
847 friend class ASTDeclReader;
848 friend class ASTDeclWriter;
849 friend class ASTReader;
850 template <class decl_type> friend class RedeclarableTemplate;
851
852 /// \brief Retrieves the canonical declaration of this template.
853 RedeclarableTemplateDecl *getCanonicalDecl() override {
854 return getFirstDecl();
855 }
856 const RedeclarableTemplateDecl *getCanonicalDecl() const {
857 return getFirstDecl();
858 }
859
860 /// \brief Determines whether this template was a specialization of a
861 /// member template.
862 ///
863 /// In the following example, the function template \c X<int>::f and the
864 /// member template \c X<int>::Inner are member specializations.
865 ///
866 /// \code
867 /// template<typename T>
868 /// struct X {
869 /// template<typename U> void f(T, U);
870 /// template<typename U> struct Inner;
871 /// };
872 ///
873 /// template<> template<typename T>
874 /// void X<int>::f(int, T);
875 /// template<> template<typename T>
876 /// struct X<int>::Inner { /* ... */ };
877 /// \endcode
878 bool isMemberSpecialization() const {
879 return getCommonPtr()->InstantiatedFromMember.getInt();
880 }
881
882 /// \brief Note that this member template is a specialization.
883 void setMemberSpecialization() {
884 assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&(static_cast <bool> (getCommonPtr()->InstantiatedFromMember
.getPointer() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("getCommonPtr()->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 885, __extension__ __PRETTY_FUNCTION__))
885 "Only member templates can be member template specializations")(static_cast <bool> (getCommonPtr()->InstantiatedFromMember
.getPointer() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("getCommonPtr()->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 885, __extension__ __PRETTY_FUNCTION__))
;
886 getCommonPtr()->InstantiatedFromMember.setInt(true);
887 }
888
889 /// \brief Retrieve the member template from which this template was
890 /// instantiated, or nullptr if this template was not instantiated from a
891 /// member template.
892 ///
893 /// A template is instantiated from a member template when the member
894 /// template itself is part of a class template (or member thereof). For
895 /// example, given
896 ///
897 /// \code
898 /// template<typename T>
899 /// struct X {
900 /// template<typename U> void f(T, U);
901 /// };
902 ///
903 /// void test(X<int> x) {
904 /// x.f(1, 'a');
905 /// };
906 /// \endcode
907 ///
908 /// \c X<int>::f is a FunctionTemplateDecl that describes the function
909 /// template
910 ///
911 /// \code
912 /// template<typename U> void X<int>::f(int, U);
913 /// \endcode
914 ///
915 /// which was itself created during the instantiation of \c X<int>. Calling
916 /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
917 /// retrieve the FunctionTemplateDecl for the original template \c f within
918 /// the class template \c X<T>, i.e.,
919 ///
920 /// \code
921 /// template<typename T>
922 /// template<typename U>
923 /// void X<T>::f(T, U);
924 /// \endcode
925 RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
926 return getCommonPtr()->InstantiatedFromMember.getPointer();
927 }
928
929 void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
930 assert(!getCommonPtr()->InstantiatedFromMember.getPointer())(static_cast <bool> (!getCommonPtr()->InstantiatedFromMember
.getPointer()) ? void (0) : __assert_fail ("!getCommonPtr()->InstantiatedFromMember.getPointer()"
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 930, __extension__ __PRETTY_FUNCTION__))
;
931 getCommonPtr()->InstantiatedFromMember.setPointer(TD);
932 }
933
934 using redecl_range = redeclarable_base::redecl_range;
935 using redecl_iterator = redeclarable_base::redecl_iterator;
936
937 using redeclarable_base::redecls_begin;
938 using redeclarable_base::redecls_end;
939 using redeclarable_base::redecls;
940 using redeclarable_base::getPreviousDecl;
941 using redeclarable_base::getMostRecentDecl;
942 using redeclarable_base::isFirstDecl;
943
944 // Implement isa/cast/dyncast/etc.
945 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
946
947 static bool classofKind(Kind K) {
948 return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
949 }
950};
951
952template <> struct RedeclarableTemplateDecl::
953SpecEntryTraits<FunctionTemplateSpecializationInfo> {
954 using DeclType = FunctionDecl;
955
956 static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
957 return I->Function;
958 }
959
960 static ArrayRef<TemplateArgument>
961 getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
962 return I->TemplateArguments->asArray();
963 }
964};
965
966/// Declaration of a template function.
967class FunctionTemplateDecl : public RedeclarableTemplateDecl {
968protected:
969 friend class FunctionDecl;
970
971 /// \brief Data that is common to all of the declarations of a given
972 /// function template.
973 struct Common : CommonBase {
974 /// \brief The function template specializations for this function
975 /// template, including explicit specializations and instantiations.
976 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
977
978 /// \brief The set of "injected" template arguments used within this
979 /// function template.
980 ///
981 /// This pointer refers to the template arguments (there are as
982 /// many template arguments as template parameaters) for the function
983 /// template, and is allocated lazily, since most function templates do not
984 /// require the use of this information.
985 TemplateArgument *InjectedArgs = nullptr;
986
987 Common() = default;
988 };
989
990 FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
991 DeclarationName Name, TemplateParameterList *Params,
992 NamedDecl *Decl)
993 : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
994 Decl) {}
995
996 CommonBase *newCommon(ASTContext &C) const override;
997
998 Common *getCommonPtr() const {
999 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1000 }
1001
1002 /// \brief Retrieve the set of function template specializations of this
1003 /// function template.
1004 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
1005 getSpecializations() const;
1006
1007 /// \brief Add a specialization of this function template.
1008 ///
1009 /// \param InsertPos Insert position in the FoldingSetVector, must have been
1010 /// retrieved by an earlier call to findSpecialization().
1011 void addSpecialization(FunctionTemplateSpecializationInfo* Info,
1012 void *InsertPos);
1013
1014public:
1015 friend class ASTDeclReader;
1016 friend class ASTDeclWriter;
1017
1018 /// \brief Load any lazily-loaded specializations from the external source.
1019 void LoadLazySpecializations() const;
1020
1021 /// Get the underlying function declaration of the template.
1022 FunctionDecl *getTemplatedDecl() const {
1023 return static_cast<FunctionDecl *>(TemplatedDecl);
1024 }
1025
1026 /// Returns whether this template declaration defines the primary
1027 /// pattern.
1028 bool isThisDeclarationADefinition() const {
1029 return getTemplatedDecl()->isThisDeclarationADefinition();
1030 }
1031
1032 /// \brief Return the specialization with the provided arguments if it exists,
1033 /// otherwise return the insertion point.
1034 FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
1035 void *&InsertPos);
1036
1037 FunctionTemplateDecl *getCanonicalDecl() override {
1038 return cast<FunctionTemplateDecl>(
1039 RedeclarableTemplateDecl::getCanonicalDecl());
1040 }
1041 const FunctionTemplateDecl *getCanonicalDecl() const {
1042 return cast<FunctionTemplateDecl>(
1043 RedeclarableTemplateDecl::getCanonicalDecl());
1044 }
1045
1046 /// \brief Retrieve the previous declaration of this function template, or
1047 /// nullptr if no such declaration exists.
1048 FunctionTemplateDecl *getPreviousDecl() {
1049 return cast_or_null<FunctionTemplateDecl>(
1050 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1051 }
1052 const FunctionTemplateDecl *getPreviousDecl() const {
1053 return cast_or_null<FunctionTemplateDecl>(
1054 static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1055 }
1056
1057 FunctionTemplateDecl *getMostRecentDecl() {
1058 return cast<FunctionTemplateDecl>(
1059 static_cast<RedeclarableTemplateDecl *>(this)
1060 ->getMostRecentDecl());
1061 }
1062 const FunctionTemplateDecl *getMostRecentDecl() const {
1063 return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
1064 }
1065
1066 FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
1067 return cast_or_null<FunctionTemplateDecl>(
1068 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1069 }
1070
1071 using spec_iterator = SpecIterator<FunctionTemplateSpecializationInfo>;
1072 using spec_range = llvm::iterator_range<spec_iterator>;
1073
1074 spec_range specializations() const {
1075 return spec_range(spec_begin(), spec_end());
1076 }
1077
1078 spec_iterator spec_begin() const {
1079 return makeSpecIterator(getSpecializations(), false);
1080 }
1081
1082 spec_iterator spec_end() const {
1083 return makeSpecIterator(getSpecializations(), true);
1084 }
1085
1086 /// \brief Retrieve the "injected" template arguments that correspond to the
1087 /// template parameters of this function template.
1088 ///
1089 /// Although the C++ standard has no notion of the "injected" template
1090 /// arguments for a function template, the notion is convenient when
1091 /// we need to perform substitutions inside the definition of a function
1092 /// template.
1093 ArrayRef<TemplateArgument> getInjectedTemplateArgs();
1094
1095 /// \brief Create a function template node.
1096 static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1097 SourceLocation L,
1098 DeclarationName Name,
1099 TemplateParameterList *Params,
1100 NamedDecl *Decl);
1101
1102 /// \brief Create an empty function template node.
1103 static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1104
1105 // Implement isa/cast/dyncast support
1106 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1107 static bool classofKind(Kind K) { return K == FunctionTemplate; }
1108};
1109
1110//===----------------------------------------------------------------------===//
1111// Kinds of Template Parameters
1112//===----------------------------------------------------------------------===//
1113
1114/// \brief Defines the position of a template parameter within a template
1115/// parameter list.
1116///
1117/// Because template parameter can be listed
1118/// sequentially for out-of-line template members, each template parameter is
1119/// given a Depth - the nesting of template parameter scopes - and a Position -
1120/// the occurrence within the parameter list.
1121/// This class is inheritedly privately by different kinds of template
1122/// parameters and is not part of the Decl hierarchy. Just a facility.
1123class TemplateParmPosition {
1124protected:
1125 // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
1126 // position? Maybe?
1127 unsigned Depth;
1128 unsigned Position;
1129
1130 TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {}
1131
1132public:
1133 TemplateParmPosition() = delete;
1134
1135 /// Get the nesting depth of the template parameter.
1136 unsigned getDepth() const { return Depth; }
1137 void setDepth(unsigned D) { Depth = D; }
1138
1139 /// Get the position of the template parameter within its parameter list.
1140 unsigned getPosition() const { return Position; }
1141 void setPosition(unsigned P) { Position = P; }
1142
1143 /// Get the index of the template parameter within its parameter list.
1144 unsigned getIndex() const { return Position; }
1145};
1146
1147/// \brief Declaration of a template type parameter.
1148///
1149/// For example, "T" in
1150/// \code
1151/// template<typename T> class vector;
1152/// \endcode
1153class TemplateTypeParmDecl : public TypeDecl {
1154 /// Sema creates these on the stack during auto type deduction.
1155 friend class Sema;
1156
1157 /// \brief Whether this template type parameter was declaration with
1158 /// the 'typename' keyword.
1159 ///
1160 /// If false, it was declared with the 'class' keyword.
1161 bool Typename : 1;
1162
1163 /// \brief The default template argument, if any.
1164 using DefArgStorage =
1165 DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>;
1166 DefArgStorage DefaultArgument;
1167
1168 TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
1169 SourceLocation IdLoc, IdentifierInfo *Id,
1170 bool Typename)
1171 : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename) {}
1172
1173public:
1174 static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
1175 SourceLocation KeyLoc,
1176 SourceLocation NameLoc,
1177 unsigned D, unsigned P,
1178 IdentifierInfo *Id, bool Typename,
1179 bool ParameterPack);
1180 static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
1181 unsigned ID);
1182
1183 /// \brief Whether this template type parameter was declared with
1184 /// the 'typename' keyword.
1185 ///
1186 /// If not, it was declared with the 'class' keyword.
1187 bool wasDeclaredWithTypename() const { return Typename; }
1188
1189 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1190
1191 /// \brief Determine whether this template parameter has a default
1192 /// argument.
1193 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1194
1195 /// \brief Retrieve the default argument, if any.
1196 QualType getDefaultArgument() const {
1197 return DefaultArgument.get()->getType();
1198 }
1199
1200 /// \brief Retrieves the default argument's source information, if any.
1201 TypeSourceInfo *getDefaultArgumentInfo() const {
1202 return DefaultArgument.get();
1203 }
1204
1205 /// \brief Retrieves the location of the default argument declaration.
1206 SourceLocation getDefaultArgumentLoc() const;
1207
1208 /// \brief Determines whether the default argument was inherited
1209 /// from a previous declaration of this template.
1210 bool defaultArgumentWasInherited() const {
1211 return DefaultArgument.isInherited();
1212 }
1213
1214 /// \brief Set the default argument for this template parameter.
1215 void setDefaultArgument(TypeSourceInfo *DefArg) {
1216 DefaultArgument.set(DefArg);
1217 }
1218
1219 /// \brief Set that this default argument was inherited from another
1220 /// parameter.
1221 void setInheritedDefaultArgument(const ASTContext &C,
1222 TemplateTypeParmDecl *Prev) {
1223 DefaultArgument.setInherited(C, Prev);
1224 }
1225
1226 /// \brief Removes the default argument of this template parameter.
1227 void removeDefaultArgument() {
1228 DefaultArgument.clear();
1229 }
1230
1231 /// \brief Set whether this template type parameter was declared with
1232 /// the 'typename' or 'class' keyword.
1233 void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
1234
1235 /// \brief Retrieve the depth of the template parameter.
1236 unsigned getDepth() const;
1237
1238 /// \brief Retrieve the index of the template parameter.
1239 unsigned getIndex() const;
1240
1241 /// \brief Returns whether this is a parameter pack.
1242 bool isParameterPack() const;
1243
1244 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1245
1246 // Implement isa/cast/dyncast/etc.
1247 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1248 static bool classofKind(Kind K) { return K == TemplateTypeParm; }
1249};
1250
1251/// NonTypeTemplateParmDecl - Declares a non-type template parameter,
1252/// e.g., "Size" in
1253/// @code
1254/// template<int Size> class array { };
1255/// @endcode
1256class NonTypeTemplateParmDecl final
1257 : public DeclaratorDecl,
1258 protected TemplateParmPosition,
1259 private llvm::TrailingObjects<NonTypeTemplateParmDecl,
1260 std::pair<QualType, TypeSourceInfo *>> {
1261 friend class ASTDeclReader;
1262 friend TrailingObjects;
1263
1264 /// \brief The default template argument, if any, and whether or not
1265 /// it was inherited.
1266 using DefArgStorage = DefaultArgStorage<NonTypeTemplateParmDecl, Expr *>;
1267 DefArgStorage DefaultArgument;
1268
1269 // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
1270 // down here to save memory.
1271
1272 /// \brief Whether this non-type template parameter is a parameter pack.
1273 bool ParameterPack;
1274
1275 /// \brief Whether this non-type template parameter is an "expanded"
1276 /// parameter pack, meaning that its type is a pack expansion and we
1277 /// already know the set of types that expansion expands to.
1278 bool ExpandedParameterPack = false;
1279
1280 /// \brief The number of types in an expanded parameter pack.
1281 unsigned NumExpandedTypes = 0;
1282
1283 size_t numTrailingObjects(
1284 OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
1285 return NumExpandedTypes;
1286 }
1287
1288 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1289 SourceLocation IdLoc, unsigned D, unsigned P,
1290 IdentifierInfo *Id, QualType T,
1291 bool ParameterPack, TypeSourceInfo *TInfo)
1292 : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
1293 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1294
1295 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1296 SourceLocation IdLoc, unsigned D, unsigned P,
1297 IdentifierInfo *Id, QualType T,
1298 TypeSourceInfo *TInfo,
1299 ArrayRef<QualType> ExpandedTypes,
1300 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1301
1302public:
1303 static NonTypeTemplateParmDecl *
1304 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1305 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1306 QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
1307
1308 static NonTypeTemplateParmDecl *
1309 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1310 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1311 QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes,
1312 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1313
1314 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1315 unsigned ID);
1316 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1317 unsigned ID,
1318 unsigned NumExpandedTypes);
1319
1320 using TemplateParmPosition::getDepth;
1321 using TemplateParmPosition::setDepth;
1322 using TemplateParmPosition::getPosition;
1323 using TemplateParmPosition::setPosition;
1324 using TemplateParmPosition::getIndex;
1325
1326 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1327
1328 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1329
1330 /// \brief Determine whether this template parameter has a default
1331 /// argument.
1332 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1333
1334 /// \brief Retrieve the default argument, if any.
1335 Expr *getDefaultArgument() const { return DefaultArgument.get(); }
1336
1337 /// \brief Retrieve the location of the default argument, if any.
1338 SourceLocation getDefaultArgumentLoc() const;
1339
1340 /// \brief Determines whether the default argument was inherited
1341 /// from a previous declaration of this template.
1342 bool defaultArgumentWasInherited() const {
1343 return DefaultArgument.isInherited();
1344 }
1345
1346 /// \brief Set the default argument for this template parameter, and
1347 /// whether that default argument was inherited from another
1348 /// declaration.
1349 void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
1350 void setInheritedDefaultArgument(const ASTContext &C,
1351 NonTypeTemplateParmDecl *Parm) {
1352 DefaultArgument.setInherited(C, Parm);
1353 }
1354
1355 /// \brief Removes the default argument of this template parameter.
1356 void removeDefaultArgument() { DefaultArgument.clear(); }
1357
1358 /// \brief Whether this parameter is a non-type template parameter pack.
1359 ///
1360 /// If the parameter is a parameter pack, the type may be a
1361 /// \c PackExpansionType. In the following example, the \c Dims parameter
1362 /// is a parameter pack (whose type is 'unsigned').
1363 ///
1364 /// \code
1365 /// template<typename T, unsigned ...Dims> struct multi_array;
1366 /// \endcode
1367 bool isParameterPack() const { return ParameterPack; }
1368
1369 /// \brief Whether this parameter pack is a pack expansion.
1370 ///
1371 /// A non-type template parameter pack is a pack expansion if its type
1372 /// contains an unexpanded parameter pack. In this case, we will have
1373 /// built a PackExpansionType wrapping the type.
1374 bool isPackExpansion() const {
1375 return ParameterPack && getType()->getAs<PackExpansionType>();
1376 }
1377
1378 /// \brief Whether this parameter is a non-type template parameter pack
1379 /// that has a known list of different types at different positions.
1380 ///
1381 /// A parameter pack is an expanded parameter pack when the original
1382 /// parameter pack's type was itself a pack expansion, and that expansion
1383 /// has already been expanded. For example, given:
1384 ///
1385 /// \code
1386 /// template<typename ...Types>
1387 /// struct X {
1388 /// template<Types ...Values>
1389 /// struct Y { /* ... */ };
1390 /// };
1391 /// \endcode
1392 ///
1393 /// The parameter pack \c Values has a \c PackExpansionType as its type,
1394 /// which expands \c Types. When \c Types is supplied with template arguments
1395 /// by instantiating \c X, the instantiation of \c Values becomes an
1396 /// expanded parameter pack. For example, instantiating
1397 /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1398 /// pack with expansion types \c int and \c unsigned int.
1399 ///
1400 /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1401 /// return the expansion types.
1402 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1403
1404 /// \brief Retrieves the number of expansion types in an expanded parameter
1405 /// pack.
1406 unsigned getNumExpansionTypes() const {
1407 assert(ExpandedParameterPack && "Not an expansion parameter pack")(static_cast <bool> (ExpandedParameterPack && "Not an expansion parameter pack"
) ? void (0) : __assert_fail ("ExpandedParameterPack && \"Not an expansion parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1407, __extension__ __PRETTY_FUNCTION__))
;
1408 return NumExpandedTypes;
1409 }
1410
1411 /// \brief Retrieve a particular expansion type within an expanded parameter
1412 /// pack.
1413 QualType getExpansionType(unsigned I) const {
1414 assert(I < NumExpandedTypes && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedTypes &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedTypes && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1414, __extension__ __PRETTY_FUNCTION__))
;
1415 auto TypesAndInfos =
1416 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1417 return TypesAndInfos[I].first;
1418 }
1419
1420 /// \brief Retrieve a particular expansion type source info within an
1421 /// expanded parameter pack.
1422 TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1423 assert(I < NumExpandedTypes && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedTypes &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedTypes && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1423, __extension__ __PRETTY_FUNCTION__))
;
1424 auto TypesAndInfos =
1425 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1426 return TypesAndInfos[I].second;
1427 }
1428
1429 // Implement isa/cast/dyncast/etc.
1430 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1431 static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1432};
1433
1434/// TemplateTemplateParmDecl - Declares a template template parameter,
1435/// e.g., "T" in
1436/// @code
1437/// template <template <typename> class T> class container { };
1438/// @endcode
1439/// A template template parameter is a TemplateDecl because it defines the
1440/// name of a template and the template parameters allowable for substitution.
1441class TemplateTemplateParmDecl final
1442 : public TemplateDecl,
1443 protected TemplateParmPosition,
1444 private llvm::TrailingObjects<TemplateTemplateParmDecl,
1445 TemplateParameterList *> {
1446 /// \brief The default template argument, if any.
1447 using DefArgStorage =
1448 DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>;
1449 DefArgStorage DefaultArgument;
1450
1451 /// \brief Whether this parameter is a parameter pack.
1452 bool ParameterPack;
1453
1454 /// \brief Whether this template template parameter is an "expanded"
1455 /// parameter pack, meaning that it is a pack expansion and we
1456 /// already know the set of template parameters that expansion expands to.
1457 bool ExpandedParameterPack = false;
1458
1459 /// \brief The number of parameters in an expanded parameter pack.
1460 unsigned NumExpandedParams = 0;
1461
1462 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1463 unsigned D, unsigned P, bool ParameterPack,
1464 IdentifierInfo *Id, TemplateParameterList *Params)
1465 : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1466 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1467
1468 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1469 unsigned D, unsigned P,
1470 IdentifierInfo *Id, TemplateParameterList *Params,
1471 ArrayRef<TemplateParameterList *> Expansions);
1472
1473 void anchor() override;
1474
1475public:
1476 friend class ASTDeclReader;
1477 friend class ASTDeclWriter;
1478 friend TrailingObjects;
1479
1480 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1481 SourceLocation L, unsigned D,
1482 unsigned P, bool ParameterPack,
1483 IdentifierInfo *Id,
1484 TemplateParameterList *Params);
1485 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1486 SourceLocation L, unsigned D,
1487 unsigned P,
1488 IdentifierInfo *Id,
1489 TemplateParameterList *Params,
1490 ArrayRef<TemplateParameterList *> Expansions);
1491
1492 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1493 unsigned ID);
1494 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1495 unsigned ID,
1496 unsigned NumExpansions);
1497
1498 using TemplateParmPosition::getDepth;
1499 using TemplateParmPosition::setDepth;
1500 using TemplateParmPosition::getPosition;
1501 using TemplateParmPosition::setPosition;
1502 using TemplateParmPosition::getIndex;
1503
1504 /// \brief Whether this template template parameter is a template
1505 /// parameter pack.
1506 ///
1507 /// \code
1508 /// template<template <class T> ...MetaFunctions> struct Apply;
1509 /// \endcode
1510 bool isParameterPack() const { return ParameterPack; }
1511
1512 /// \brief Whether this parameter pack is a pack expansion.
1513 ///
1514 /// A template template parameter pack is a pack expansion if its template
1515 /// parameter list contains an unexpanded parameter pack.
1516 bool isPackExpansion() const {
1517 return ParameterPack &&
1518 getTemplateParameters()->containsUnexpandedParameterPack();
1519 }
1520
1521 /// \brief Whether this parameter is a template template parameter pack that
1522 /// has a known list of different template parameter lists at different
1523 /// positions.
1524 ///
1525 /// A parameter pack is an expanded parameter pack when the original parameter
1526 /// pack's template parameter list was itself a pack expansion, and that
1527 /// expansion has already been expanded. For exampe, given:
1528 ///
1529 /// \code
1530 /// template<typename...Types> struct Outer {
1531 /// template<template<Types> class...Templates> struct Inner;
1532 /// };
1533 /// \endcode
1534 ///
1535 /// The parameter pack \c Templates is a pack expansion, which expands the
1536 /// pack \c Types. When \c Types is supplied with template arguments by
1537 /// instantiating \c Outer, the instantiation of \c Templates is an expanded
1538 /// parameter pack.
1539 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1540
1541 /// \brief Retrieves the number of expansion template parameters in
1542 /// an expanded parameter pack.
1543 unsigned getNumExpansionTemplateParameters() const {
1544 assert(ExpandedParameterPack && "Not an expansion parameter pack")(static_cast <bool> (ExpandedParameterPack && "Not an expansion parameter pack"
) ? void (0) : __assert_fail ("ExpandedParameterPack && \"Not an expansion parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1544, __extension__ __PRETTY_FUNCTION__))
;
1545 return NumExpandedParams;
1546 }
1547
1548 /// \brief Retrieve a particular expansion type within an expanded parameter
1549 /// pack.
1550 TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
1551 assert(I < NumExpandedParams && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedParams &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedParams && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1551, __extension__ __PRETTY_FUNCTION__))
;
1552 return getTrailingObjects<TemplateParameterList *>()[I];
1553 }
1554
1555 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1556
1557 /// \brief Determine whether this template parameter has a default
1558 /// argument.
1559 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1560
1561 /// \brief Retrieve the default argument, if any.
1562 const TemplateArgumentLoc &getDefaultArgument() const {
1563 static const TemplateArgumentLoc None;
1564 return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
1565 }
1566
1567 /// \brief Retrieve the location of the default argument, if any.
1568 SourceLocation getDefaultArgumentLoc() const;
1569
1570 /// \brief Determines whether the default argument was inherited
1571 /// from a previous declaration of this template.
1572 bool defaultArgumentWasInherited() const {
1573 return DefaultArgument.isInherited();
1574 }
1575
1576 /// \brief Set the default argument for this template parameter, and
1577 /// whether that default argument was inherited from another
1578 /// declaration.
1579 void setDefaultArgument(const ASTContext &C,
1580 const TemplateArgumentLoc &DefArg);
1581 void setInheritedDefaultArgument(const ASTContext &C,
1582 TemplateTemplateParmDecl *Prev) {
1583 DefaultArgument.setInherited(C, Prev);
1584 }
1585
1586 /// \brief Removes the default argument of this template parameter.
1587 void removeDefaultArgument() { DefaultArgument.clear(); }
1588
1589 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1590 SourceLocation End = getLocation();
1591 if (hasDefaultArgument() && !defaultArgumentWasInherited())
1592 End = getDefaultArgument().getSourceRange().getEnd();
1593 return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1594 }
1595
1596 // Implement isa/cast/dyncast/etc.
1597 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1598 static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1599};
1600
1601/// \brief Represents the builtin template declaration which is used to
1602/// implement __make_integer_seq and other builtin templates. It serves
1603/// no real purpose beyond existing as a place to hold template parameters.
1604class BuiltinTemplateDecl : public TemplateDecl {
1605 BuiltinTemplateKind BTK;
1606
1607 BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
1608 DeclarationName Name, BuiltinTemplateKind BTK);
1609
1610 void anchor() override;
1611
1612public:
1613 // Implement isa/cast/dyncast support
1614 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1615 static bool classofKind(Kind K) { return K == BuiltinTemplate; }
1616
1617 static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
1618 DeclarationName Name,
1619 BuiltinTemplateKind BTK) {
1620 return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
1621 }
1622
1623 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1624 return SourceRange();
1625 }
1626
1627 BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
1628};
1629
1630/// \brief Represents a class template specialization, which refers to
1631/// a class template with a given set of template arguments.
1632///
1633/// Class template specializations represent both explicit
1634/// specialization of class templates, as in the example below, and
1635/// implicit instantiations of class templates.
1636///
1637/// \code
1638/// template<typename T> class array;
1639///
1640/// template<>
1641/// class array<bool> { }; // class template specialization array<bool>
1642/// \endcode
1643class ClassTemplateSpecializationDecl
1644 : public CXXRecordDecl, public llvm::FoldingSetNode {
1645 /// \brief Structure that stores information about a class template
1646 /// specialization that was instantiated from a class template partial
1647 /// specialization.
1648 struct SpecializedPartialSpecialization {
1649 /// \brief The class template partial specialization from which this
1650 /// class template specialization was instantiated.
1651 ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1652
1653 /// \brief The template argument list deduced for the class template
1654 /// partial specialization itself.
1655 const TemplateArgumentList *TemplateArgs;
1656 };
1657
1658 /// \brief The template that this specialization specializes
1659 llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1660 SpecializedTemplate;
1661
1662 /// \brief Further info for explicit template specialization/instantiation.
1663 struct ExplicitSpecializationInfo {
1664 /// \brief The type-as-written.
1665 TypeSourceInfo *TypeAsWritten = nullptr;
1666
1667 /// \brief The location of the extern keyword.
1668 SourceLocation ExternLoc;
1669
1670 /// \brief The location of the template keyword.
1671 SourceLocation TemplateKeywordLoc;
1672
1673 ExplicitSpecializationInfo() = default;
1674 };
1675
1676 /// \brief Further info for explicit template specialization/instantiation.
1677 /// Does not apply to implicit specializations.
1678 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
1679
1680 /// \brief The template arguments used to describe this specialization.
1681 const TemplateArgumentList *TemplateArgs;
1682
1683 /// \brief The point where this template was instantiated (if any)
1684 SourceLocation PointOfInstantiation;
1685
1686 /// \brief The kind of specialization this declaration refers to.
1687 /// Really a value of type TemplateSpecializationKind.
1688 unsigned SpecializationKind : 3;
1689
1690protected:
1691 ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1692 DeclContext *DC, SourceLocation StartLoc,
1693 SourceLocation IdLoc,
1694 ClassTemplateDecl *SpecializedTemplate,
1695 ArrayRef<TemplateArgument> Args,
1696 ClassTemplateSpecializationDecl *PrevDecl);
1697
1698 explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
1699
1700public:
1701 friend class ASTDeclReader;
1702 friend class ASTDeclWriter;
1703
1704 static ClassTemplateSpecializationDecl *
1705 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1706 SourceLocation StartLoc, SourceLocation IdLoc,
1707 ClassTemplateDecl *SpecializedTemplate,
1708 ArrayRef<TemplateArgument> Args,
1709 ClassTemplateSpecializationDecl *PrevDecl);
1710 static ClassTemplateSpecializationDecl *
1711 CreateDeserialized(ASTContext &C, unsigned ID);
1712
1713 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1714 bool Qualified) const override;
1715
1716 // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
1717 // different "most recent" declaration from this function for the same
1718 // declaration, because we don't override getMostRecentDeclImpl(). But
1719 // it's not clear that we should override that, because the most recent
1720 // declaration as a CXXRecordDecl sometimes is the injected-class-name.
1721 ClassTemplateSpecializationDecl *getMostRecentDecl() {
1722 CXXRecordDecl *Recent = static_cast<CXXRecordDecl *>(
1723 this)->getMostRecentDecl();
1724 while (!isa<ClassTemplateSpecializationDecl>(Recent)) {
1725 // FIXME: Does injected class name need to be in the redeclarations chain?
1726 assert(Recent->isInjectedClassName() && Recent->getPreviousDecl())(static_cast <bool> (Recent->isInjectedClassName() &&
Recent->getPreviousDecl()) ? void (0) : __assert_fail ("Recent->isInjectedClassName() && Recent->getPreviousDecl()"
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1726, __extension__ __PRETTY_FUNCTION__))
;
1727 Recent = Recent->getPreviousDecl();
1728 }
1729 return cast<ClassTemplateSpecializationDecl>(Recent);
1730 }
1731
1732 /// \brief Retrieve the template that this specialization specializes.
1733 ClassTemplateDecl *getSpecializedTemplate() const;
1734
1735 /// \brief Retrieve the template arguments of the class template
1736 /// specialization.
1737 const TemplateArgumentList &getTemplateArgs() const {
1738 return *TemplateArgs;
1739 }
1740
1741 /// \brief Determine the kind of specialization that this
1742 /// declaration represents.
1743 TemplateSpecializationKind getSpecializationKind() const {
1744 return static_cast<TemplateSpecializationKind>(SpecializationKind);
1745 }
1746
1747 bool isExplicitSpecialization() const {
1748 return getSpecializationKind() == TSK_ExplicitSpecialization;
1749 }
1750
1751 /// \brief True if this declaration is an explicit specialization,
1752 /// explicit instantiation declaration, or explicit instantiation
1753 /// definition.
1754 bool isExplicitInstantiationOrSpecialization() const {
1755 return isTemplateExplicitInstantiationOrSpecialization(
1756 getTemplateSpecializationKind());
1757 }
1758
1759 void setSpecializationKind(TemplateSpecializationKind TSK) {
1760 SpecializationKind = TSK;
1761 }
1762
1763 /// \brief Get the point of instantiation (if any), or null if none.
1764 SourceLocation getPointOfInstantiation() const {
1765 return PointOfInstantiation;
1766 }
1767
1768 void setPointOfInstantiation(SourceLocation Loc) {
1769 assert(Loc.isValid() && "point of instantiation must be valid!")(static_cast <bool> (Loc.isValid() && "point of instantiation must be valid!"
) ? void (0) : __assert_fail ("Loc.isValid() && \"point of instantiation must be valid!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1769, __extension__ __PRETTY_FUNCTION__))
;
1770 PointOfInstantiation = Loc;
1771 }
1772
1773 /// \brief If this class template specialization is an instantiation of
1774 /// a template (rather than an explicit specialization), return the
1775 /// class template or class template partial specialization from which it
1776 /// was instantiated.
1777 llvm::PointerUnion<ClassTemplateDecl *,
1778 ClassTemplatePartialSpecializationDecl *>
1779 getInstantiatedFrom() const {
1780 if (!isTemplateInstantiation(getSpecializationKind()))
1781 return llvm::PointerUnion<ClassTemplateDecl *,
1782 ClassTemplatePartialSpecializationDecl *>();
1783
1784 return getSpecializedTemplateOrPartial();
1785 }
1786
1787 /// \brief Retrieve the class template or class template partial
1788 /// specialization which was specialized by this.
1789 llvm::PointerUnion<ClassTemplateDecl *,
1790 ClassTemplatePartialSpecializationDecl *>
1791 getSpecializedTemplateOrPartial() const {
1792 if (SpecializedPartialSpecialization *PartialSpec
1793 = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1794 return PartialSpec->PartialSpecialization;
1795
1796 return SpecializedTemplate.get<ClassTemplateDecl*>();
1797 }
1798
1799 /// \brief Retrieve the set of template arguments that should be used
1800 /// to instantiate members of the class template or class template partial
1801 /// specialization from which this class template specialization was
1802 /// instantiated.
1803 ///
1804 /// \returns For a class template specialization instantiated from the primary
1805 /// template, this function will return the same template arguments as
1806 /// getTemplateArgs(). For a class template specialization instantiated from
1807 /// a class template partial specialization, this function will return the
1808 /// deduced template arguments for the class template partial specialization
1809 /// itself.
1810 const TemplateArgumentList &getTemplateInstantiationArgs() const {
1811 if (SpecializedPartialSpecialization *PartialSpec
1812 = SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization*>())
1813 return *PartialSpec->TemplateArgs;
1814
1815 return getTemplateArgs();
1816 }
1817
1818 /// \brief Note that this class template specialization is actually an
1819 /// instantiation of the given class template partial specialization whose
1820 /// template arguments have been deduced.
1821 void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
1822 const TemplateArgumentList *TemplateArgs) {
1823 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Already set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1824, __extension__ __PRETTY_FUNCTION__))
1824 "Already set to a class template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Already set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1824, __extension__ __PRETTY_FUNCTION__))
;
1825 SpecializedPartialSpecialization *PS
1826 = new (getASTContext()) SpecializedPartialSpecialization();
1827 PS->PartialSpecialization = PartialSpec;
1828 PS->TemplateArgs = TemplateArgs;
1829 SpecializedTemplate = PS;
1830 }
1831
1832 /// \brief Note that this class template specialization is an instantiation
1833 /// of the given class template.
1834 void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
1835 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Previously set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1836, __extension__ __PRETTY_FUNCTION__))
1836 "Previously set to a class template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Previously set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 1836, __extension__ __PRETTY_FUNCTION__))
;
1837 SpecializedTemplate = TemplDecl;
1838 }
1839
1840 /// \brief Sets the type of this specialization as it was written by
1841 /// the user. This will be a class template specialization type.
1842 void setTypeAsWritten(TypeSourceInfo *T) {
1843 if (!ExplicitInfo)
20
Assuming the condition is true
21
Taking true branch
1844 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
22
Null pointer value stored to field 'ExplicitInfo'
1845 ExplicitInfo->TypeAsWritten = T;
23
Access to field 'TypeAsWritten' results in a dereference of a null pointer (loaded from field 'ExplicitInfo')
1846 }
1847
1848 /// \brief Gets the type of this specialization as it was written by
1849 /// the user, if it was so written.
1850 TypeSourceInfo *getTypeAsWritten() const {
1851 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
1852 }
1853
1854 /// \brief Gets the location of the extern keyword, if present.
1855 SourceLocation getExternLoc() const {
1856 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
1857 }
1858
1859 /// \brief Sets the location of the extern keyword.
1860 void setExternLoc(SourceLocation Loc) {
1861 if (!ExplicitInfo)
1862 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1863 ExplicitInfo->ExternLoc = Loc;
1864 }
1865
1866 /// \brief Sets the location of the template keyword.
1867 void setTemplateKeywordLoc(SourceLocation Loc) {
1868 if (!ExplicitInfo)
1869 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1870 ExplicitInfo->TemplateKeywordLoc = Loc;
1871 }
1872
1873 /// \brief Gets the location of the template keyword, if present.
1874 SourceLocation getTemplateKeywordLoc() const {
1875 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
1876 }
1877
1878 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1879
1880 void Profile(llvm::FoldingSetNodeID &ID) const {
1881 Profile(ID, TemplateArgs->asArray(), getASTContext());
1882 }
1883
1884 static void
1885 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
1886 ASTContext &Context) {
1887 ID.AddInteger(TemplateArgs.size());
1888 for (const TemplateArgument &TemplateArg : TemplateArgs)
1889 TemplateArg.Profile(ID, Context);
1890 }
1891
1892 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1893
1894 static bool classofKind(Kind K) {
1895 return K >= firstClassTemplateSpecialization &&
1896 K <= lastClassTemplateSpecialization;
1897 }
1898};
1899
1900class ClassTemplatePartialSpecializationDecl
1901 : public ClassTemplateSpecializationDecl {
1902 /// \brief The list of template parameters
1903 TemplateParameterList* TemplateParams = nullptr;
1904
1905 /// \brief The source info for the template arguments as written.
1906 /// FIXME: redundant with TypeAsWritten?
1907 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
1908
1909 /// \brief The class template partial specialization from which this
1910 /// class template partial specialization was instantiated.
1911 ///
1912 /// The boolean value will be true to indicate that this class template
1913 /// partial specialization was specialized at this level.
1914 llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
1915 InstantiatedFromMember;
1916
1917 ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
1918 DeclContext *DC,
1919 SourceLocation StartLoc,
1920 SourceLocation IdLoc,
1921 TemplateParameterList *Params,
1922 ClassTemplateDecl *SpecializedTemplate,
1923 ArrayRef<TemplateArgument> Args,
1924 const ASTTemplateArgumentListInfo *ArgsAsWritten,
1925 ClassTemplatePartialSpecializationDecl *PrevDecl);
1926
1927 ClassTemplatePartialSpecializationDecl(ASTContext &C)
1928 : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
1929 InstantiatedFromMember(nullptr, false) {}
1930
1931 void anchor() override;
1932
1933public:
1934 friend class ASTDeclReader;
1935 friend class ASTDeclWriter;
1936
1937 static ClassTemplatePartialSpecializationDecl *
1938 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1939 SourceLocation StartLoc, SourceLocation IdLoc,
1940 TemplateParameterList *Params,
1941 ClassTemplateDecl *SpecializedTemplate,
1942 ArrayRef<TemplateArgument> Args,
1943 const TemplateArgumentListInfo &ArgInfos,
1944 QualType CanonInjectedType,
1945 ClassTemplatePartialSpecializationDecl *PrevDecl);
1946
1947 static ClassTemplatePartialSpecializationDecl *
1948 CreateDeserialized(ASTContext &C, unsigned ID);
1949
1950 ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
1951 return cast<ClassTemplatePartialSpecializationDecl>(
1952 static_cast<ClassTemplateSpecializationDecl *>(
1953 this)->getMostRecentDecl());
1954 }
1955
1956 /// Get the list of template parameters
1957 TemplateParameterList *getTemplateParameters() const {
1958 return TemplateParams;
1959 }
1960
1961 /// Get the template arguments as written.
1962 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
1963 return ArgsAsWritten;
1964 }
1965
1966 /// \brief Retrieve the member class template partial specialization from
1967 /// which this particular class template partial specialization was
1968 /// instantiated.
1969 ///
1970 /// \code
1971 /// template<typename T>
1972 /// struct Outer {
1973 /// template<typename U> struct Inner;
1974 /// template<typename U> struct Inner<U*> { }; // #1
1975 /// };
1976 ///
1977 /// Outer<float>::Inner<int*> ii;
1978 /// \endcode
1979 ///
1980 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
1981 /// end up instantiating the partial specialization
1982 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
1983 /// template partial specialization \c Outer<T>::Inner<U*>. Given
1984 /// \c Outer<float>::Inner<U*>, this function would return
1985 /// \c Outer<T>::Inner<U*>.
1986 ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
1987 const ClassTemplatePartialSpecializationDecl *First =
1988 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
1989 return First->InstantiatedFromMember.getPointer();
1990 }
1991 ClassTemplatePartialSpecializationDecl *
1992 getInstantiatedFromMemberTemplate() const {
1993 return getInstantiatedFromMember();
1994 }
1995
1996 void setInstantiatedFromMember(
1997 ClassTemplatePartialSpecializationDecl *PartialSpec) {
1998 ClassTemplatePartialSpecializationDecl *First =
1999 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2000 First->InstantiatedFromMember.setPointer(PartialSpec);
2001 }
2002
2003 /// \brief Determines whether this class template partial specialization
2004 /// template was a specialization of a member partial specialization.
2005 ///
2006 /// In the following example, the member template partial specialization
2007 /// \c X<int>::Inner<T*> is a member specialization.
2008 ///
2009 /// \code
2010 /// template<typename T>
2011 /// struct X {
2012 /// template<typename U> struct Inner;
2013 /// template<typename U> struct Inner<U*>;
2014 /// };
2015 ///
2016 /// template<> template<typename T>
2017 /// struct X<int>::Inner<T*> { /* ... */ };
2018 /// \endcode
2019 bool isMemberSpecialization() {
2020 ClassTemplatePartialSpecializationDecl *First =
2021 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2022 return First->InstantiatedFromMember.getInt();
2023 }
2024
2025 /// \brief Note that this member template is a specialization.
2026 void setMemberSpecialization() {
2027 ClassTemplatePartialSpecializationDecl *First =
2028 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2029 assert(First->InstantiatedFromMember.getPointer() &&(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2030, __extension__ __PRETTY_FUNCTION__))
2030 "Only member templates can be member template specializations")(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2030, __extension__ __PRETTY_FUNCTION__))
;
2031 return First->InstantiatedFromMember.setInt(true);
2032 }
2033
2034 /// Retrieves the injected specialization type for this partial
2035 /// specialization. This is not the same as the type-decl-type for
2036 /// this partial specialization, which is an InjectedClassNameType.
2037 QualType getInjectedSpecializationType() const {
2038 assert(getTypeForDecl() && "partial specialization has no type set!")(static_cast <bool> (getTypeForDecl() && "partial specialization has no type set!"
) ? void (0) : __assert_fail ("getTypeForDecl() && \"partial specialization has no type set!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2038, __extension__ __PRETTY_FUNCTION__))
;
2039 return cast<InjectedClassNameType>(getTypeForDecl())
2040 ->getInjectedSpecializationType();
2041 }
2042
2043 // FIXME: Add Profile support!
2044
2045 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2046
2047 static bool classofKind(Kind K) {
2048 return K == ClassTemplatePartialSpecialization;
2049 }
2050};
2051
2052/// Declaration of a class template.
2053class ClassTemplateDecl : public RedeclarableTemplateDecl {
2054protected:
2055 /// \brief Data that is common to all of the declarations of a given
2056 /// class template.
2057 struct Common : CommonBase {
2058 /// \brief The class template specializations for this class
2059 /// template, including explicit specializations and instantiations.
2060 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
2061
2062 /// \brief The class template partial specializations for this class
2063 /// template.
2064 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
2065 PartialSpecializations;
2066
2067 /// \brief The injected-class-name type for this class template.
2068 QualType InjectedClassNameType;
2069
2070 Common() = default;
2071 };
2072
2073 /// \brief Retrieve the set of specializations of this class template.
2074 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
2075 getSpecializations() const;
2076
2077 /// \brief Retrieve the set of partial specializations of this class
2078 /// template.
2079 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
2080 getPartialSpecializations();
2081
2082 ClassTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, ASTContext &C,
2083 DeclContext *DC, SourceLocation L, DeclarationName Name,
2084 TemplateParameterList *Params, NamedDecl *Decl)
2085 : RedeclarableTemplateDecl(CTDI, ClassTemplate, C, DC, L, Name, Params,
2086 Decl) {}
2087
2088 ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2089 DeclarationName Name, TemplateParameterList *Params,
2090 NamedDecl *Decl)
2091 : ClassTemplateDecl(nullptr, C, DC, L, Name, Params, Decl) {}
2092
2093 CommonBase *newCommon(ASTContext &C) const override;
2094
2095 Common *getCommonPtr() const {
2096 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2097 }
2098
2099public:
2100 friend class ASTDeclReader;
2101 friend class ASTDeclWriter;
2102
2103 /// \brief Load any lazily-loaded specializations from the external source.
2104 void LoadLazySpecializations() const;
2105
2106 /// \brief Get the underlying class declarations of the template.
2107 CXXRecordDecl *getTemplatedDecl() const {
2108 return static_cast<CXXRecordDecl *>(TemplatedDecl);
2109 }
2110
2111 /// \brief Returns whether this template declaration defines the primary
2112 /// class pattern.
2113 bool isThisDeclarationADefinition() const {
2114 return getTemplatedDecl()->isThisDeclarationADefinition();
2115 }
2116
2117 // FIXME: remove default argument for AssociatedConstraints
2118 /// \brief Create a class template node.
2119 static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2120 SourceLocation L,
2121 DeclarationName Name,
2122 TemplateParameterList *Params,
2123 NamedDecl *Decl,
2124 Expr *AssociatedConstraints = nullptr);
2125
2126 /// \brief Create an empty class template node.
2127 static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2128
2129 /// \brief Return the specialization with the provided arguments if it exists,
2130 /// otherwise return the insertion point.
2131 ClassTemplateSpecializationDecl *
2132 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2133
2134 /// \brief Insert the specified specialization knowing that it is not already
2135 /// in. InsertPos must be obtained from findSpecialization.
2136 void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
2137
2138 ClassTemplateDecl *getCanonicalDecl() override {
2139 return cast<ClassTemplateDecl>(
2140 RedeclarableTemplateDecl::getCanonicalDecl());
2141 }
2142 const ClassTemplateDecl *getCanonicalDecl() const {
2143 return cast<ClassTemplateDecl>(
2144 RedeclarableTemplateDecl::getCanonicalDecl());
2145 }
2146
2147 /// \brief Retrieve the previous declaration of this class template, or
2148 /// nullptr if no such declaration exists.
2149 ClassTemplateDecl *getPreviousDecl() {
2150 return cast_or_null<ClassTemplateDecl>(
2151 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2152 }
2153 const ClassTemplateDecl *getPreviousDecl() const {
2154 return cast_or_null<ClassTemplateDecl>(
2155 static_cast<const RedeclarableTemplateDecl *>(
2156 this)->getPreviousDecl());
2157 }
2158
2159 ClassTemplateDecl *getMostRecentDecl() {
2160 return cast<ClassTemplateDecl>(
2161 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2162 }
2163 const ClassTemplateDecl *getMostRecentDecl() const {
2164 return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
2165 }
2166
2167 ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
2168 return cast_or_null<ClassTemplateDecl>(
2169 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2170 }
2171
2172 /// \brief Return the partial specialization with the provided arguments if it
2173 /// exists, otherwise return the insertion point.
2174 ClassTemplatePartialSpecializationDecl *
2175 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2176
2177 /// \brief Insert the specified partial specialization knowing that it is not
2178 /// already in. InsertPos must be obtained from findPartialSpecialization.
2179 void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
2180 void *InsertPos);
2181
2182 /// \brief Retrieve the partial specializations as an ordered list.
2183 void getPartialSpecializations(
2184 SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
2185
2186 /// \brief Find a class template partial specialization with the given
2187 /// type T.
2188 ///
2189 /// \param T a dependent type that names a specialization of this class
2190 /// template.
2191 ///
2192 /// \returns the class template partial specialization that exactly matches
2193 /// the type \p T, or nullptr if no such partial specialization exists.
2194 ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
2195
2196 /// \brief Find a class template partial specialization which was instantiated
2197 /// from the given member partial specialization.
2198 ///
2199 /// \param D a member class template partial specialization.
2200 ///
2201 /// \returns the class template partial specialization which was instantiated
2202 /// from the given member partial specialization, or nullptr if no such
2203 /// partial specialization exists.
2204 ClassTemplatePartialSpecializationDecl *
2205 findPartialSpecInstantiatedFromMember(
2206 ClassTemplatePartialSpecializationDecl *D);
2207
2208 /// \brief Retrieve the template specialization type of the
2209 /// injected-class-name for this class template.
2210 ///
2211 /// The injected-class-name for a class template \c X is \c
2212 /// X<template-args>, where \c template-args is formed from the
2213 /// template arguments that correspond to the template parameters of
2214 /// \c X. For example:
2215 ///
2216 /// \code
2217 /// template<typename T, int N>
2218 /// struct array {
2219 /// typedef array this_type; // "array" is equivalent to "array<T, N>"
2220 /// };
2221 /// \endcode
2222 QualType getInjectedClassNameSpecialization();
2223
2224 using spec_iterator = SpecIterator<ClassTemplateSpecializationDecl>;
2225 using spec_range = llvm::iterator_range<spec_iterator>;
2226
2227 spec_range specializations() const {
2228 return spec_range(spec_begin(), spec_end());
2229 }
2230
2231 spec_iterator spec_begin() const {
2232 return makeSpecIterator(getSpecializations(), false);
2233 }
2234
2235 spec_iterator spec_end() const {
2236 return makeSpecIterator(getSpecializations(), true);
2237 }
2238
2239 // Implement isa/cast/dyncast support
2240 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2241 static bool classofKind(Kind K) { return K == ClassTemplate; }
2242};
2243
2244/// \brief Declaration of a friend template.
2245///
2246/// For example:
2247/// \code
2248/// template \<typename T> class A {
2249/// friend class MyVector<T>; // not a friend template
2250/// template \<typename U> friend class B; // not a friend template
2251/// template \<typename U> friend class Foo<T>::Nested; // friend template
2252/// };
2253/// \endcode
2254///
2255/// \note This class is not currently in use. All of the above
2256/// will yield a FriendDecl, not a FriendTemplateDecl.
2257class FriendTemplateDecl : public Decl {
2258 virtual void anchor();
2259
2260public:
2261 using FriendUnion = llvm::PointerUnion<NamedDecl *,TypeSourceInfo *>;
2262
2263private:
2264 // The number of template parameters; always non-zero.
2265 unsigned NumParams = 0;
2266
2267 // The parameter list.
2268 TemplateParameterList **Params = nullptr;
2269
2270 // The declaration that's a friend of this class.
2271 FriendUnion Friend;
2272
2273 // Location of the 'friend' specifier.
2274 SourceLocation FriendLoc;
2275
2276 FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
2277 MutableArrayRef<TemplateParameterList *> Params,
2278 FriendUnion Friend, SourceLocation FriendLoc)
2279 : Decl(Decl::FriendTemplate, DC, Loc), NumParams(Params.size()),
2280 Params(Params.data()), Friend(Friend), FriendLoc(FriendLoc) {}
2281
2282 FriendTemplateDecl(EmptyShell Empty) : Decl(Decl::FriendTemplate, Empty) {}
2283
2284public:
2285 friend class ASTDeclReader;
2286
2287 static FriendTemplateDecl *
2288 Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc,
2289 MutableArrayRef<TemplateParameterList *> Params, FriendUnion Friend,
2290 SourceLocation FriendLoc);
2291
2292 static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2293
2294 /// If this friend declaration names a templated type (or
2295 /// a dependent member type of a templated type), return that
2296 /// type; otherwise return null.
2297 TypeSourceInfo *getFriendType() const {
2298 return Friend.dyn_cast<TypeSourceInfo*>();
2299 }
2300
2301 /// If this friend declaration names a templated function (or
2302 /// a member function of a templated type), return that type;
2303 /// otherwise return null.
2304 NamedDecl *getFriendDecl() const {
2305 return Friend.dyn_cast<NamedDecl*>();
2306 }
2307
2308 /// \brief Retrieves the location of the 'friend' keyword.
2309 SourceLocation getFriendLoc() const {
2310 return FriendLoc;
2311 }
2312
2313 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2314 assert(i <= NumParams)(static_cast <bool> (i <= NumParams) ? void (0) : __assert_fail
("i <= NumParams", "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2314, __extension__ __PRETTY_FUNCTION__))
;
2315 return Params[i];
2316 }
2317
2318 unsigned getNumTemplateParameters() const {
2319 return NumParams;
2320 }
2321
2322 // Implement isa/cast/dyncast/etc.
2323 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2324 static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
2325};
2326
2327/// \brief Declaration of an alias template.
2328///
2329/// For example:
2330/// \code
2331/// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
2332/// \endcode
2333class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
2334protected:
2335 using Common = CommonBase;
2336
2337 TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2338 DeclarationName Name, TemplateParameterList *Params,
2339 NamedDecl *Decl)
2340 : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
2341 Decl) {}
2342
2343 CommonBase *newCommon(ASTContext &C) const override;
2344
2345 Common *getCommonPtr() {
2346 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2347 }
2348
2349public:
2350 friend class ASTDeclReader;
2351 friend class ASTDeclWriter;
2352
2353 /// Get the underlying function declaration of the template.
2354 TypeAliasDecl *getTemplatedDecl() const {
2355 return static_cast<TypeAliasDecl *>(TemplatedDecl);
2356 }
2357
2358
2359 TypeAliasTemplateDecl *getCanonicalDecl() override {
2360 return cast<TypeAliasTemplateDecl>(
2361 RedeclarableTemplateDecl::getCanonicalDecl());
2362 }
2363 const TypeAliasTemplateDecl *getCanonicalDecl() const {
2364 return cast<TypeAliasTemplateDecl>(
2365 RedeclarableTemplateDecl::getCanonicalDecl());
2366 }
2367
2368 /// \brief Retrieve the previous declaration of this function template, or
2369 /// nullptr if no such declaration exists.
2370 TypeAliasTemplateDecl *getPreviousDecl() {
2371 return cast_or_null<TypeAliasTemplateDecl>(
2372 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2373 }
2374 const TypeAliasTemplateDecl *getPreviousDecl() const {
2375 return cast_or_null<TypeAliasTemplateDecl>(
2376 static_cast<const RedeclarableTemplateDecl *>(
2377 this)->getPreviousDecl());
2378 }
2379
2380 TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
2381 return cast_or_null<TypeAliasTemplateDecl>(
2382 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2383 }
2384
2385 /// \brief Create a function template node.
2386 static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2387 SourceLocation L,
2388 DeclarationName Name,
2389 TemplateParameterList *Params,
2390 NamedDecl *Decl);
2391
2392 /// \brief Create an empty alias template node.
2393 static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2394
2395 // Implement isa/cast/dyncast support
2396 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2397 static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2398};
2399
2400/// \brief Declaration of a function specialization at template class scope.
2401///
2402/// This is a non-standard extension needed to support MSVC.
2403///
2404/// For example:
2405/// \code
2406/// template <class T>
2407/// class A {
2408/// template <class U> void foo(U a) { }
2409/// template<> void foo(int a) { }
2410/// }
2411/// \endcode
2412///
2413/// "template<> foo(int a)" will be saved in Specialization as a normal
2414/// CXXMethodDecl. Then during an instantiation of class A, it will be
2415/// transformed into an actual function specialization.
2416class ClassScopeFunctionSpecializationDecl : public Decl {
2417 CXXMethodDecl *Specialization;
2418 bool HasExplicitTemplateArgs;
2419 TemplateArgumentListInfo TemplateArgs;
2420
2421 ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
2422 CXXMethodDecl *FD, bool Args,
2423 TemplateArgumentListInfo TemplArgs)
2424 : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
2425 Specialization(FD), HasExplicitTemplateArgs(Args),
2426 TemplateArgs(std::move(TemplArgs)) {}
2427
2428 ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
2429 : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
2430
2431 virtual void anchor();
2432
2433public:
2434 friend class ASTDeclReader;
2435 friend class ASTDeclWriter;
2436
2437 CXXMethodDecl *getSpecialization() const { return Specialization; }
2438 bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
2439 const TemplateArgumentListInfo& templateArgs() const { return TemplateArgs; }
2440
2441 static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
2442 DeclContext *DC,
2443 SourceLocation Loc,
2444 CXXMethodDecl *FD,
2445 bool HasExplicitTemplateArgs,
2446 TemplateArgumentListInfo TemplateArgs) {
2447 return new (C, DC) ClassScopeFunctionSpecializationDecl(
2448 DC, Loc, FD, HasExplicitTemplateArgs, std::move(TemplateArgs));
2449 }
2450
2451 static ClassScopeFunctionSpecializationDecl *
2452 CreateDeserialized(ASTContext &Context, unsigned ID);
2453
2454 // Implement isa/cast/dyncast/etc.
2455 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2456
2457 static bool classofKind(Kind K) {
2458 return K == Decl::ClassScopeFunctionSpecialization;
2459 }
2460};
2461
2462/// Implementation of inline functions that require the template declarations
2463inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
2464 : Function(FTD) {}
2465
2466/// \brief Represents a variable template specialization, which refers to
2467/// a variable template with a given set of template arguments.
2468///
2469/// Variable template specializations represent both explicit
2470/// specializations of variable templates, as in the example below, and
2471/// implicit instantiations of variable templates.
2472///
2473/// \code
2474/// template<typename T> constexpr T pi = T(3.1415926535897932385);
2475///
2476/// template<>
2477/// constexpr float pi<float>; // variable template specialization pi<float>
2478/// \endcode
2479class VarTemplateSpecializationDecl : public VarDecl,
2480 public llvm::FoldingSetNode {
2481
2482 /// \brief Structure that stores information about a variable template
2483 /// specialization that was instantiated from a variable template partial
2484 /// specialization.
2485 struct SpecializedPartialSpecialization {
2486 /// \brief The variable template partial specialization from which this
2487 /// variable template specialization was instantiated.
2488 VarTemplatePartialSpecializationDecl *PartialSpecialization;
2489
2490 /// \brief The template argument list deduced for the variable template
2491 /// partial specialization itself.
2492 const TemplateArgumentList *TemplateArgs;
2493 };
2494
2495 /// \brief The template that this specialization specializes.
2496 llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
2497 SpecializedTemplate;
2498
2499 /// \brief Further info for explicit template specialization/instantiation.
2500 struct ExplicitSpecializationInfo {
2501 /// \brief The type-as-written.
2502 TypeSourceInfo *TypeAsWritten = nullptr;
2503
2504 /// \brief The location of the extern keyword.
2505 SourceLocation ExternLoc;
2506
2507 /// \brief The location of the template keyword.
2508 SourceLocation TemplateKeywordLoc;
2509
2510 ExplicitSpecializationInfo() = default;
2511 };
2512
2513 /// \brief Further info for explicit template specialization/instantiation.
2514 /// Does not apply to implicit specializations.
2515 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
2516
2517 /// \brief The template arguments used to describe this specialization.
2518 const TemplateArgumentList *TemplateArgs;
2519 TemplateArgumentListInfo TemplateArgsInfo;
2520
2521 /// \brief The point where this template was instantiated (if any).
2522 SourceLocation PointOfInstantiation;
2523
2524 /// \brief The kind of specialization this declaration refers to.
2525 /// Really a value of type TemplateSpecializationKind.
2526 unsigned SpecializationKind : 3;
2527
2528 /// \brief Whether this declaration is a complete definition of the
2529 /// variable template specialization. We can't otherwise tell apart
2530 /// an instantiated declaration from an instantiated definition with
2531 /// no initializer.
2532 unsigned IsCompleteDefinition : 1;
2533
2534protected:
2535 VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
2536 SourceLocation StartLoc, SourceLocation IdLoc,
2537 VarTemplateDecl *SpecializedTemplate,
2538 QualType T, TypeSourceInfo *TInfo,
2539 StorageClass S,
2540 ArrayRef<TemplateArgument> Args);
2541
2542 explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
2543
2544public:
2545 friend class ASTDeclReader;
2546 friend class ASTDeclWriter;
2547 friend class VarDecl;
2548
2549 static VarTemplateSpecializationDecl *
2550 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2551 SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
2552 TypeSourceInfo *TInfo, StorageClass S,
2553 ArrayRef<TemplateArgument> Args);
2554 static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
2555 unsigned ID);
2556
2557 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2558 bool Qualified) const override;
2559
2560 VarTemplateSpecializationDecl *getMostRecentDecl() {
2561 VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
2562 return cast<VarTemplateSpecializationDecl>(Recent);
2563 }
2564
2565 /// \brief Retrieve the template that this specialization specializes.
2566 VarTemplateDecl *getSpecializedTemplate() const;
2567
2568 /// \brief Retrieve the template arguments of the variable template
2569 /// specialization.
2570 const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
2571
2572 // TODO: Always set this when creating the new specialization?
2573 void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
2574
2575 const TemplateArgumentListInfo &getTemplateArgsInfo() const {
2576 return TemplateArgsInfo;
2577 }
2578
2579 /// \brief Determine the kind of specialization that this
2580 /// declaration represents.
2581 TemplateSpecializationKind getSpecializationKind() const {
2582 return static_cast<TemplateSpecializationKind>(SpecializationKind);
2583 }
2584
2585 bool isExplicitSpecialization() const {
2586 return getSpecializationKind() == TSK_ExplicitSpecialization;
2587 }
2588
2589 /// \brief True if this declaration is an explicit specialization,
2590 /// explicit instantiation declaration, or explicit instantiation
2591 /// definition.
2592 bool isExplicitInstantiationOrSpecialization() const {
2593 return isTemplateExplicitInstantiationOrSpecialization(
2594 getTemplateSpecializationKind());
2595 }
2596
2597 void setSpecializationKind(TemplateSpecializationKind TSK) {
2598 SpecializationKind = TSK;
2599 }
2600
2601 /// \brief Get the point of instantiation (if any), or null if none.
2602 SourceLocation getPointOfInstantiation() const {
2603 return PointOfInstantiation;
2604 }
2605
2606 void setPointOfInstantiation(SourceLocation Loc) {
2607 assert(Loc.isValid() && "point of instantiation must be valid!")(static_cast <bool> (Loc.isValid() && "point of instantiation must be valid!"
) ? void (0) : __assert_fail ("Loc.isValid() && \"point of instantiation must be valid!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2607, __extension__ __PRETTY_FUNCTION__))
;
2608 PointOfInstantiation = Loc;
2609 }
2610
2611 void setCompleteDefinition() { IsCompleteDefinition = true; }
2612
2613 /// \brief If this variable template specialization is an instantiation of
2614 /// a template (rather than an explicit specialization), return the
2615 /// variable template or variable template partial specialization from which
2616 /// it was instantiated.
2617 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2618 getInstantiatedFrom() const {
2619 if (!isTemplateInstantiation(getSpecializationKind()))
2620 return llvm::PointerUnion<VarTemplateDecl *,
2621 VarTemplatePartialSpecializationDecl *>();
2622
2623 return getSpecializedTemplateOrPartial();
2624 }
2625
2626 /// \brief Retrieve the variable template or variable template partial
2627 /// specialization which was specialized by this.
2628 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2629 getSpecializedTemplateOrPartial() const {
2630 if (SpecializedPartialSpecialization *PartialSpec =
2631 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2632 return PartialSpec->PartialSpecialization;
2633
2634 return SpecializedTemplate.get<VarTemplateDecl *>();
2635 }
2636
2637 /// \brief Retrieve the set of template arguments that should be used
2638 /// to instantiate the initializer of the variable template or variable
2639 /// template partial specialization from which this variable template
2640 /// specialization was instantiated.
2641 ///
2642 /// \returns For a variable template specialization instantiated from the
2643 /// primary template, this function will return the same template arguments
2644 /// as getTemplateArgs(). For a variable template specialization instantiated
2645 /// from a variable template partial specialization, this function will the
2646 /// return deduced template arguments for the variable template partial
2647 /// specialization itself.
2648 const TemplateArgumentList &getTemplateInstantiationArgs() const {
2649 if (SpecializedPartialSpecialization *PartialSpec =
2650 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2651 return *PartialSpec->TemplateArgs;
2652
2653 return getTemplateArgs();
2654 }
2655
2656 /// \brief Note that this variable template specialization is actually an
2657 /// instantiation of the given variable template partial specialization whose
2658 /// template arguments have been deduced.
2659 void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
2660 const TemplateArgumentList *TemplateArgs) {
2661 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Already set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2662, __extension__ __PRETTY_FUNCTION__))
2662 "Already set to a variable template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Already set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2662, __extension__ __PRETTY_FUNCTION__))
;
2663 SpecializedPartialSpecialization *PS =
2664 new (getASTContext()) SpecializedPartialSpecialization();
2665 PS->PartialSpecialization = PartialSpec;
2666 PS->TemplateArgs = TemplateArgs;
2667 SpecializedTemplate = PS;
2668 }
2669
2670 /// \brief Note that this variable template specialization is an instantiation
2671 /// of the given variable template.
2672 void setInstantiationOf(VarTemplateDecl *TemplDecl) {
2673 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Previously set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2674, __extension__ __PRETTY_FUNCTION__))
2674 "Previously set to a variable template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Previously set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2674, __extension__ __PRETTY_FUNCTION__))
;
2675 SpecializedTemplate = TemplDecl;
2676 }
2677
2678 /// \brief Sets the type of this specialization as it was written by
2679 /// the user.
2680 void setTypeAsWritten(TypeSourceInfo *T) {
2681 if (!ExplicitInfo)
2682 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2683 ExplicitInfo->TypeAsWritten = T;
2684 }
2685
2686 /// \brief Gets the type of this specialization as it was written by
2687 /// the user, if it was so written.
2688 TypeSourceInfo *getTypeAsWritten() const {
2689 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
2690 }
2691
2692 /// \brief Gets the location of the extern keyword, if present.
2693 SourceLocation getExternLoc() const {
2694 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
2695 }
2696
2697 /// \brief Sets the location of the extern keyword.
2698 void setExternLoc(SourceLocation Loc) {
2699 if (!ExplicitInfo)
2700 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2701 ExplicitInfo->ExternLoc = Loc;
2702 }
2703
2704 /// \brief Sets the location of the template keyword.
2705 void setTemplateKeywordLoc(SourceLocation Loc) {
2706 if (!ExplicitInfo)
2707 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2708 ExplicitInfo->TemplateKeywordLoc = Loc;
2709 }
2710
2711 /// \brief Gets the location of the template keyword, if present.
2712 SourceLocation getTemplateKeywordLoc() const {
2713 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
2714 }
2715
2716 void Profile(llvm::FoldingSetNodeID &ID) const {
2717 Profile(ID, TemplateArgs->asArray(), getASTContext());
2718 }
2719
2720 static void Profile(llvm::FoldingSetNodeID &ID,
2721 ArrayRef<TemplateArgument> TemplateArgs,
2722 ASTContext &Context) {
2723 ID.AddInteger(TemplateArgs.size());
2724 for (const TemplateArgument &TemplateArg : TemplateArgs)
2725 TemplateArg.Profile(ID, Context);
2726 }
2727
2728 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2729
2730 static bool classofKind(Kind K) {
2731 return K >= firstVarTemplateSpecialization &&
2732 K <= lastVarTemplateSpecialization;
2733 }
2734};
2735
2736class VarTemplatePartialSpecializationDecl
2737 : public VarTemplateSpecializationDecl {
2738 /// \brief The list of template parameters
2739 TemplateParameterList *TemplateParams = nullptr;
2740
2741 /// \brief The source info for the template arguments as written.
2742 /// FIXME: redundant with TypeAsWritten?
2743 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2744
2745 /// \brief The variable template partial specialization from which this
2746 /// variable template partial specialization was instantiated.
2747 ///
2748 /// The boolean value will be true to indicate that this variable template
2749 /// partial specialization was specialized at this level.
2750 llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
2751 InstantiatedFromMember;
2752
2753 VarTemplatePartialSpecializationDecl(
2754 ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2755 SourceLocation IdLoc, TemplateParameterList *Params,
2756 VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
2757 StorageClass S, ArrayRef<TemplateArgument> Args,
2758 const ASTTemplateArgumentListInfo *ArgInfos);
2759
2760 VarTemplatePartialSpecializationDecl(ASTContext &Context)
2761 : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization,
2762 Context),
2763 InstantiatedFromMember(nullptr, false) {}
2764
2765 void anchor() override;
2766
2767public:
2768 friend class ASTDeclReader;
2769 friend class ASTDeclWriter;
2770
2771 static VarTemplatePartialSpecializationDecl *
2772 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2773 SourceLocation IdLoc, TemplateParameterList *Params,
2774 VarTemplateDecl *SpecializedTemplate, QualType T,
2775 TypeSourceInfo *TInfo, StorageClass S, ArrayRef<TemplateArgument> Args,
2776 const TemplateArgumentListInfo &ArgInfos);
2777
2778 static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
2779 unsigned ID);
2780
2781 VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
2782 return cast<VarTemplatePartialSpecializationDecl>(
2783 static_cast<VarTemplateSpecializationDecl *>(
2784 this)->getMostRecentDecl());
2785 }
2786
2787 /// Get the list of template parameters
2788 TemplateParameterList *getTemplateParameters() const {
2789 return TemplateParams;
2790 }
2791
2792 /// Get the template arguments as written.
2793 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2794 return ArgsAsWritten;
2795 }
2796
2797 /// \brief Retrieve the member variable template partial specialization from
2798 /// which this particular variable template partial specialization was
2799 /// instantiated.
2800 ///
2801 /// \code
2802 /// template<typename T>
2803 /// struct Outer {
2804 /// template<typename U> U Inner;
2805 /// template<typename U> U* Inner<U*> = (U*)(0); // #1
2806 /// };
2807 ///
2808 /// template int* Outer<float>::Inner<int*>;
2809 /// \endcode
2810 ///
2811 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
2812 /// end up instantiating the partial specialization
2813 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
2814 /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
2815 /// \c Outer<float>::Inner<U*>, this function would return
2816 /// \c Outer<T>::Inner<U*>.
2817 VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
2818 const VarTemplatePartialSpecializationDecl *First =
2819 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2820 return First->InstantiatedFromMember.getPointer();
2821 }
2822
2823 void
2824 setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
2825 VarTemplatePartialSpecializationDecl *First =
2826 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2827 First->InstantiatedFromMember.setPointer(PartialSpec);
2828 }
2829
2830 /// \brief Determines whether this variable template partial specialization
2831 /// was a specialization of a member partial specialization.
2832 ///
2833 /// In the following example, the member template partial specialization
2834 /// \c X<int>::Inner<T*> is a member specialization.
2835 ///
2836 /// \code
2837 /// template<typename T>
2838 /// struct X {
2839 /// template<typename U> U Inner;
2840 /// template<typename U> U* Inner<U*> = (U*)(0);
2841 /// };
2842 ///
2843 /// template<> template<typename T>
2844 /// U* X<int>::Inner<T*> = (T*)(0) + 1;
2845 /// \endcode
2846 bool isMemberSpecialization() {
2847 VarTemplatePartialSpecializationDecl *First =
2848 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2849 return First->InstantiatedFromMember.getInt();
2850 }
2851
2852 /// \brief Note that this member template is a specialization.
2853 void setMemberSpecialization() {
2854 VarTemplatePartialSpecializationDecl *First =
2855 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2856 assert(First->InstantiatedFromMember.getPointer() &&(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2857, __extension__ __PRETTY_FUNCTION__))
2857 "Only member templates can be member template specializations")(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn326061/tools/clang/include/clang/AST/DeclTemplate.h"
, 2857, __extension__ __PRETTY_FUNCTION__))
;
2858 return First->InstantiatedFromMember.setInt(true);
2859 }
2860
2861 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2862
2863 static bool classofKind(Kind K) {
2864 return K == VarTemplatePartialSpecialization;
2865 }
2866};
2867
2868/// Declaration of a variable template.
2869class VarTemplateDecl : public RedeclarableTemplateDecl {
2870protected:
2871 /// \brief Data that is common to all of the declarations of a given
2872 /// variable template.
2873 struct Common : CommonBase {
2874 /// \brief The variable template specializations for this variable
2875 /// template, including explicit specializations and instantiations.
2876 llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
2877
2878 /// \brief The variable template partial specializations for this variable
2879 /// template.
2880 llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
2881 PartialSpecializations;
2882
2883 Common() = default;
2884 };
2885
2886 /// \brief Retrieve the set of specializations of this variable template.
2887 llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
2888 getSpecializations() const;
2889
2890 /// \brief Retrieve the set of partial specializations of this class
2891 /// template.
2892 llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
2893 getPartialSpecializations();
2894
2895 VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2896 DeclarationName Name, TemplateParameterList *Params,
2897 NamedDecl *Decl)
2898 : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
2899
2900 CommonBase *newCommon(ASTContext &C) const override;
2901
2902 Common *getCommonPtr() const {
2903 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2904 }
2905
2906public:
2907 friend class ASTDeclReader;
2908 friend class ASTDeclWriter;
2909
2910 /// \brief Load any lazily-loaded specializations from the external source.
2911 void LoadLazySpecializations() const;
2912
2913 /// \brief Get the underlying variable declarations of the template.
2914 VarDecl *getTemplatedDecl() const {
2915 return static_cast<VarDecl *>(TemplatedDecl);
2916 }
2917
2918 /// \brief Returns whether this template declaration defines the primary
2919 /// variable pattern.
2920 bool isThisDeclarationADefinition() const {
2921 return getTemplatedDecl()->isThisDeclarationADefinition();
2922 }
2923
2924 VarTemplateDecl *getDefinition();
2925
2926 /// \brief Create a variable template node.
2927 static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2928 SourceLocation L, DeclarationName Name,
2929 TemplateParameterList *Params,
2930 VarDecl *Decl);
2931
2932 /// \brief Create an empty variable template node.
2933 static VarTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2934
2935 /// \brief Return the specialization with the provided arguments if it exists,
2936 /// otherwise return the insertion point.
2937 VarTemplateSpecializationDecl *
2938 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2939
2940 /// \brief Insert the specified specialization knowing that it is not already
2941 /// in. InsertPos must be obtained from findSpecialization.
2942 void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
2943
2944 VarTemplateDecl *getCanonicalDecl() override {
2945 return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2946 }
2947 const VarTemplateDecl *getCanonicalDecl() const {
2948 return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2949 }
2950
2951 /// \brief Retrieve the previous declaration of this variable template, or
2952 /// nullptr if no such declaration exists.
2953 VarTemplateDecl *getPreviousDecl() {
2954 return cast_or_null<VarTemplateDecl>(
2955 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2956 }
2957 const VarTemplateDecl *getPreviousDecl() const {
2958 return cast_or_null<VarTemplateDecl>(
2959 static_cast<const RedeclarableTemplateDecl *>(
2960 this)->getPreviousDecl());
2961 }
2962
2963 VarTemplateDecl *getMostRecentDecl() {
2964 return cast<VarTemplateDecl>(
2965 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2966 }
2967 const VarTemplateDecl *getMostRecentDecl() const {
2968 return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
2969 }
2970
2971 VarTemplateDecl *getInstantiatedFromMemberTemplate() const {
2972 return cast_or_null<VarTemplateDecl>(
2973 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2974 }
2975
2976 /// \brief Return the partial specialization with the provided arguments if it
2977 /// exists, otherwise return the insertion point.
2978 VarTemplatePartialSpecializationDecl *
2979 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2980
2981 /// \brief Insert the specified partial specialization knowing that it is not
2982 /// already in. InsertPos must be obtained from findPartialSpecialization.
2983 void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
2984 void *InsertPos);
2985
2986 /// \brief Retrieve the partial specializations as an ordered list.
2987 void getPartialSpecializations(
2988 SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS);
2989
2990 /// \brief Find a variable template partial specialization which was
2991 /// instantiated
2992 /// from the given member partial specialization.
2993 ///
2994 /// \param D a member variable template partial specialization.
2995 ///
2996 /// \returns the variable template partial specialization which was
2997 /// instantiated
2998 /// from the given member partial specialization, or nullptr if no such
2999 /// partial specialization exists.
3000 VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
3001 VarTemplatePartialSpecializationDecl *D);
3002
3003 using spec_iterator = SpecIterator<VarTemplateSpecializationDecl>;
3004 using spec_range = llvm::iterator_range<spec_iterator>;
3005
3006 spec_range specializations() const {
3007 return spec_range(spec_begin(), spec_end());
3008 }
3009
3010 spec_iterator spec_begin() const {
3011 return makeSpecIterator(getSpecializations(), false);
3012 }
3013
3014 spec_iterator spec_end() const {
3015 return makeSpecIterator(getSpecializations(), true);
3016 }
3017
3018 // Implement isa/cast/dyncast support
3019 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3020 static bool classofKind(Kind K) { return K == VarTemplate; }
3021};
3022
3023inline NamedDecl *getAsNamedDecl(TemplateParameter P) {
3024 if (auto *PD = P.dyn_cast<TemplateTypeParmDecl*>())
3025 return PD;
3026 if (auto *PD = P.dyn_cast<NonTypeTemplateParmDecl*>())
3027 return PD;
3028 return P.get<TemplateTemplateParmDecl*>();
3029}
3030
3031inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
3032 auto *TD = dyn_cast<TemplateDecl>(D);
3033 return TD && (isa<ClassTemplateDecl>(TD) ||
3034 isa<ClassTemplatePartialSpecializationDecl>(TD) ||
3035 isa<TypeAliasTemplateDecl>(TD) ||
3036 isa<TemplateTemplateParmDecl>(TD))
3037 ? TD
3038 : nullptr;
3039}
3040
3041} // namespace clang
3042
3043#endif // LLVM_CLANG_AST_DECLTEMPLATE_H