Bug Summary

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

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~svn326551/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/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~svn326551/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-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

/build/llvm-toolchain-snapshot-7~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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())
1328 return nullptr;
1329
1330 ClassTemplateDecl *InstClassTemplate
1331 = dyn_cast<ClassTemplateDecl>(Found.front());
1332 if (!InstClassTemplate)
1333 return nullptr;
1334
1335 if (ClassTemplatePartialSpecializationDecl *Result
1336 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1337 return Result;
1338
1339 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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~svn326551/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 SemaRef.CheckForFunctionRedefinition(Function);
1810 if (!Function->isInvalidDecl()) {
1811 for (auto R : Function->redecls()) {
1812 if (R == Function)
1813 continue;
1814
1815 // If some prior declaration of this function has been used, we need
1816 // to instantiate its definition.
1817 if (!QueuedInstantiation && R->isUsed(false)) {
1818 if (MemberSpecializationInfo *MSInfo =
1819 Function->getMemberSpecializationInfo()) {
1820 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1821 SourceLocation Loc = R->getLocation(); // FIXME
1822 MSInfo->setPointOfInstantiation(Loc);
1823 SemaRef.PendingLocalImplicitInstantiations.push_back(
1824 std::make_pair(Function, Loc));
1825 QueuedInstantiation = true;
1826 }
1827 }
1828 }
1829 }
1830 }
1831 }
1832
1833 // Check the template parameter list against the previous declaration. The
1834 // goal here is to pick up default arguments added since the friend was
1835 // declared; we know the template parameter lists match, since otherwise
1836 // we would not have picked this template as the previous declaration.
1837 if (TemplateParams && FunctionTemplate->getPreviousDecl()) {
1838 SemaRef.CheckTemplateParameterList(
1839 TemplateParams,
1840 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
1841 Function->isThisDeclarationADefinition()
1842 ? Sema::TPC_FriendFunctionTemplateDefinition
1843 : Sema::TPC_FriendFunctionTemplate);
1844 }
1845 }
1846
1847 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1848 DC->makeDeclVisibleInContext(PrincipalDecl);
1849
1850 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1851 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1852 PrincipalDecl->setNonMemberOperator();
1853
1854 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1854, __extension__ __PRETTY_FUNCTION__))
;
1855 return Function;
1856}
1857
1858Decl *
1859TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1860 TemplateParameterList *TemplateParams,
1861 bool IsClassScopeSpecialization) {
1862 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1863 if (FunctionTemplate && !TemplateParams) {
1864 // We are creating a function template specialization from a function
1865 // template. Check whether there is already a function template
1866 // specialization for this particular set of template arguments.
1867 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
1868
1869 void *InsertPos = nullptr;
1870 FunctionDecl *SpecFunc
1871 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
1872
1873 // If we already have a function template specialization, return it.
1874 if (SpecFunc)
1875 return SpecFunc;
1876 }
1877
1878 bool isFriend;
1879 if (FunctionTemplate)
1880 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1881 else
1882 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1883
1884 bool MergeWithParentScope = (TemplateParams != nullptr) ||
1885 !(isa<Decl>(Owner) &&
1886 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1887 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
1888
1889 // Instantiate enclosing template arguments for friends.
1890 SmallVector<TemplateParameterList *, 4> TempParamLists;
1891 unsigned NumTempParamLists = 0;
1892 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1893 TempParamLists.resize(NumTempParamLists);
1894 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1895 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1896 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1897 if (!InstParams)
1898 return nullptr;
1899 TempParamLists[I] = InstParams;
1900 }
1901 }
1902
1903 SmallVector<ParmVarDecl *, 4> Params;
1904 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
1905 if (!TInfo)
1906 return nullptr;
1907 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
1908
1909 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1910 if (QualifierLoc) {
1911 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1912 TemplateArgs);
1913 if (!QualifierLoc)
1914 return nullptr;
1915 }
1916
1917 DeclContext *DC = Owner;
1918 if (isFriend) {
1919 if (QualifierLoc) {
1920 CXXScopeSpec SS;
1921 SS.Adopt(QualifierLoc);
1922 DC = SemaRef.computeDeclContext(SS);
1923
1924 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1925 return nullptr;
1926 } else {
1927 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1928 D->getDeclContext(),
1929 TemplateArgs);
1930 }
1931 if (!DC) return nullptr;
1932 }
1933
1934 // Build the instantiated method declaration.
1935 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1936 CXXMethodDecl *Method = nullptr;
1937
1938 SourceLocation StartLoc = D->getInnerLocStart();
1939 DeclarationNameInfo NameInfo
1940 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1941 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
1942 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1943 StartLoc, NameInfo, T, TInfo,
1944 Constructor->isExplicit(),
1945 Constructor->isInlineSpecified(),
1946 false, Constructor->isConstexpr());
1947 Method->setRangeEnd(Constructor->getLocEnd());
1948 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1949 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1950 StartLoc, NameInfo, T, TInfo,
1951 Destructor->isInlineSpecified(),
1952 false);
1953 Method->setRangeEnd(Destructor->getLocEnd());
1954 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
1955 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1956 StartLoc, NameInfo, T, TInfo,
1957 Conversion->isInlineSpecified(),
1958 Conversion->isExplicit(),
1959 Conversion->isConstexpr(),
1960 Conversion->getLocEnd());
1961 } else {
1962 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
1963 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
1964 StartLoc, NameInfo, T, TInfo,
1965 SC, D->isInlineSpecified(),
1966 D->isConstexpr(), D->getLocEnd());
1967 }
1968
1969 if (D->isInlined())
1970 Method->setImplicitlyInline();
1971
1972 if (QualifierLoc)
1973 Method->setQualifierInfo(QualifierLoc);
1974
1975 if (TemplateParams) {
1976 // Our resulting instantiation is actually a function template, since we
1977 // are substituting only the outer template parameters. For example, given
1978 //
1979 // template<typename T>
1980 // struct X {
1981 // template<typename U> void f(T, U);
1982 // };
1983 //
1984 // X<int> x;
1985 //
1986 // We are instantiating the member template "f" within X<int>, which means
1987 // substituting int for T, but leaving "f" as a member function template.
1988 // Build the function template itself.
1989 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1990 Method->getLocation(),
1991 Method->getDeclName(),
1992 TemplateParams, Method);
1993 if (isFriend) {
1994 FunctionTemplate->setLexicalDeclContext(Owner);
1995 FunctionTemplate->setObjectOfFriendDecl();
1996 } else if (D->isOutOfLine())
1997 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
1998 Method->setDescribedFunctionTemplate(FunctionTemplate);
1999 } else if (FunctionTemplate) {
2000 // Record this function template specialization.
2001 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2002 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2003 TemplateArgumentList::CreateCopy(SemaRef.Context,
2004 Innermost),
2005 /*InsertPos=*/nullptr);
2006 } else if (!isFriend) {
2007 // Record that this is an instantiation of a member function.
2008 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2009 }
2010
2011 // If we are instantiating a member function defined
2012 // out-of-line, the instantiation will have the same lexical
2013 // context (which will be a namespace scope) as the template.
2014 if (isFriend) {
2015 if (NumTempParamLists)
2016 Method->setTemplateParameterListsInfo(
2017 SemaRef.Context,
2018 llvm::makeArrayRef(TempParamLists.data(), NumTempParamLists));
2019
2020 Method->setLexicalDeclContext(Owner);
2021 Method->setObjectOfFriendDecl();
2022 } else if (D->isOutOfLine())
2023 Method->setLexicalDeclContext(D->getLexicalDeclContext());
2024
2025 // Attach the parameters
2026 for (unsigned P = 0; P < Params.size(); ++P)
2027 Params[P]->setOwningFunction(Method);
2028 Method->setParams(Params);
2029
2030 if (InitMethodInstantiation(Method, D))
2031 Method->setInvalidDecl();
2032
2033 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2034 Sema::ForExternalRedeclaration);
2035
2036 if (!FunctionTemplate || TemplateParams || isFriend) {
2037 SemaRef.LookupQualifiedName(Previous, Record);
2038
2039 // In C++, the previous declaration we find might be a tag type
2040 // (class or enum). In this case, the new declaration will hide the
2041 // tag type. Note that this does does not apply if we're declaring a
2042 // typedef (C++ [dcl.typedef]p4).
2043 if (Previous.isSingleTagDecl())
2044 Previous.clear();
2045 }
2046
2047 if (!IsClassScopeSpecialization)
2048 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
2049
2050 if (D->isPure())
2051 SemaRef.CheckPureMethod(Method, SourceRange());
2052
2053 // Propagate access. For a non-friend declaration, the access is
2054 // whatever we're propagating from. For a friend, it should be the
2055 // previous declaration we just found.
2056 if (isFriend && Method->getPreviousDecl())
2057 Method->setAccess(Method->getPreviousDecl()->getAccess());
2058 else
2059 Method->setAccess(D->getAccess());
2060 if (FunctionTemplate)
2061 FunctionTemplate->setAccess(Method->getAccess());
2062
2063 SemaRef.CheckOverrideControl(Method);
2064
2065 // If a function is defined as defaulted or deleted, mark it as such now.
2066 if (D->isExplicitlyDefaulted())
2067 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
2068 if (D->isDeletedAsWritten())
2069 SemaRef.SetDeclDeleted(Method, Method->getLocation());
2070
2071 // If there's a function template, let our caller handle it.
2072 if (FunctionTemplate) {
2073 // do nothing
2074
2075 // Don't hide a (potentially) valid declaration with an invalid one.
2076 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2077 // do nothing
2078
2079 // Otherwise, check access to friends and make them visible.
2080 } else if (isFriend) {
2081 // We only need to re-check access for methods which we didn't
2082 // manage to match during parsing.
2083 if (!D->getPreviousDecl())
2084 SemaRef.CheckFriendAccess(Method);
2085
2086 Record->makeDeclVisibleInContext(Method);
2087
2088 // Otherwise, add the declaration. We don't need to do this for
2089 // class-scope specializations because we'll have matched them with
2090 // the appropriate template.
2091 } else if (!IsClassScopeSpecialization) {
2092 Owner->addDecl(Method);
2093 }
2094
2095 return Method;
2096}
2097
2098Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2099 return VisitCXXMethodDecl(D);
2100}
2101
2102Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2103 return VisitCXXMethodDecl(D);
2104}
2105
2106Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2107 return VisitCXXMethodDecl(D);
2108}
2109
2110Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2111 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
2112 /*ExpectParameterPack=*/ false);
2113}
2114
2115Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2116 TemplateTypeParmDecl *D) {
2117 // TODO: don't always clone when decls are refcounted.
2118 assert(D->getTypeForDecl()->isTemplateTypeParmType())(static_cast <bool> (D->getTypeForDecl()->isTemplateTypeParmType
()) ? void (0) : __assert_fail ("D->getTypeForDecl()->isTemplateTypeParmType()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2118, __extension__ __PRETTY_FUNCTION__))
;
2119
2120 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2121 SemaRef.Context, Owner, D->getLocStart(), D->getLocation(),
2122 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2123 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack());
2124 Inst->setAccess(AS_public);
2125
2126 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2127 TypeSourceInfo *InstantiatedDefaultArg =
2128 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2129 D->getDefaultArgumentLoc(), D->getDeclName());
2130 if (InstantiatedDefaultArg)
2131 Inst->setDefaultArgument(InstantiatedDefaultArg);
2132 }
2133
2134 // Introduce this template parameter's instantiation into the instantiation
2135 // scope.
2136 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2137
2138 return Inst;
2139}
2140
2141Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2142 NonTypeTemplateParmDecl *D) {
2143 // Substitute into the type of the non-type template parameter.
2144 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2145 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2146 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2147 bool IsExpandedParameterPack = false;
2148 TypeSourceInfo *DI;
2149 QualType T;
2150 bool Invalid = false;
2151
2152 if (D->isExpandedParameterPack()) {
2153 // The non-type template parameter pack is an already-expanded pack
2154 // expansion of types. Substitute into each of the expanded types.
2155 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2156 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2157 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2158 TypeSourceInfo *NewDI =
2159 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2160 D->getLocation(), D->getDeclName());
2161 if (!NewDI)
2162 return nullptr;
2163
2164 QualType NewT =
2165 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2166 if (NewT.isNull())
2167 return nullptr;
2168
2169 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2170 ExpandedParameterPackTypes.push_back(NewT);
2171 }
2172
2173 IsExpandedParameterPack = true;
2174 DI = D->getTypeSourceInfo();
2175 T = DI->getType();
2176 } else if (D->isPackExpansion()) {
2177 // The non-type template parameter pack's type is a pack expansion of types.
2178 // Determine whether we need to expand this parameter pack into separate
2179 // types.
2180 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2181 TypeLoc Pattern = Expansion.getPatternLoc();
2182 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2183 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2184
2185 // Determine whether the set of unexpanded parameter packs can and should
2186 // be expanded.
2187 bool Expand = true;
2188 bool RetainExpansion = false;
2189 Optional<unsigned> OrigNumExpansions
2190 = Expansion.getTypePtr()->getNumExpansions();
2191 Optional<unsigned> NumExpansions = OrigNumExpansions;
2192 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2193 Pattern.getSourceRange(),
2194 Unexpanded,
2195 TemplateArgs,
2196 Expand, RetainExpansion,
2197 NumExpansions))
2198 return nullptr;
2199
2200 if (Expand) {
2201 for (unsigned I = 0; I != *NumExpansions; ++I) {
2202 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2203 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2204 D->getLocation(),
2205 D->getDeclName());
2206 if (!NewDI)
2207 return nullptr;
2208
2209 QualType NewT =
2210 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2211 if (NewT.isNull())
2212 return nullptr;
2213
2214 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2215 ExpandedParameterPackTypes.push_back(NewT);
2216 }
2217
2218 // Note that we have an expanded parameter pack. The "type" of this
2219 // expanded parameter pack is the original expansion type, but callers
2220 // will end up using the expanded parameter pack types for type-checking.
2221 IsExpandedParameterPack = true;
2222 DI = D->getTypeSourceInfo();
2223 T = DI->getType();
2224 } else {
2225 // We cannot fully expand the pack expansion now, so substitute into the
2226 // pattern and create a new pack expansion type.
2227 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2228 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2229 D->getLocation(),
2230 D->getDeclName());
2231 if (!NewPattern)
2232 return nullptr;
2233
2234 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2235 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2236 NumExpansions);
2237 if (!DI)
2238 return nullptr;
2239
2240 T = DI->getType();
2241 }
2242 } else {
2243 // Simple case: substitution into a parameter that is not a parameter pack.
2244 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2245 D->getLocation(), D->getDeclName());
2246 if (!DI)
2247 return nullptr;
2248
2249 // Check that this type is acceptable for a non-type template parameter.
2250 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2251 if (T.isNull()) {
2252 T = SemaRef.Context.IntTy;
2253 Invalid = true;
2254 }
2255 }
2256
2257 NonTypeTemplateParmDecl *Param;
2258 if (IsExpandedParameterPack)
2259 Param = NonTypeTemplateParmDecl::Create(
2260 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2261 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2262 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
2263 ExpandedParameterPackTypesAsWritten);
2264 else
2265 Param = NonTypeTemplateParmDecl::Create(
2266 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2267 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2268 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
2269
2270 Param->setAccess(AS_public);
2271 if (Invalid)
2272 Param->setInvalidDecl();
2273
2274 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2275 EnterExpressionEvaluationContext ConstantEvaluated(
2276 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2277 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
2278 if (!Value.isInvalid())
2279 Param->setDefaultArgument(Value.get());
2280 }
2281
2282 // Introduce this template parameter's instantiation into the instantiation
2283 // scope.
2284 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2285 return Param;
2286}
2287
2288static void collectUnexpandedParameterPacks(
2289 Sema &S,
2290 TemplateParameterList *Params,
2291 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
2292 for (const auto &P : *Params) {
2293 if (P->isTemplateParameterPack())
2294 continue;
2295 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
2296 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
2297 Unexpanded);
2298 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
2299 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
2300 Unexpanded);
2301 }
2302}
2303
2304Decl *
2305TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
2306 TemplateTemplateParmDecl *D) {
2307 // Instantiate the template parameter list of the template template parameter.
2308 TemplateParameterList *TempParams = D->getTemplateParameters();
2309 TemplateParameterList *InstParams;
2310 SmallVector<TemplateParameterList*, 8> ExpandedParams;
2311
2312 bool IsExpandedParameterPack = false;
2313
2314 if (D->isExpandedParameterPack()) {
2315 // The template template parameter pack is an already-expanded pack
2316 // expansion of template parameters. Substitute into each of the expanded
2317 // parameters.
2318 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2319 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2320 I != N; ++I) {
2321 LocalInstantiationScope Scope(SemaRef);
2322 TemplateParameterList *Expansion =
2323 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2324 if (!Expansion)
2325 return nullptr;
2326 ExpandedParams.push_back(Expansion);
2327 }
2328
2329 IsExpandedParameterPack = true;
2330 InstParams = TempParams;
2331 } else if (D->isPackExpansion()) {
2332 // The template template parameter pack expands to a pack of template
2333 // template parameters. Determine whether we need to expand this parameter
2334 // pack into separate parameters.
2335 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2336 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2337 Unexpanded);
2338
2339 // Determine whether the set of unexpanded parameter packs can and should
2340 // be expanded.
2341 bool Expand = true;
2342 bool RetainExpansion = false;
2343 Optional<unsigned> NumExpansions;
2344 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2345 TempParams->getSourceRange(),
2346 Unexpanded,
2347 TemplateArgs,
2348 Expand, RetainExpansion,
2349 NumExpansions))
2350 return nullptr;
2351
2352 if (Expand) {
2353 for (unsigned I = 0; I != *NumExpansions; ++I) {
2354 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2355 LocalInstantiationScope Scope(SemaRef);
2356 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2357 if (!Expansion)
2358 return nullptr;
2359 ExpandedParams.push_back(Expansion);
2360 }
2361
2362 // Note that we have an expanded parameter pack. The "type" of this
2363 // expanded parameter pack is the original expansion type, but callers
2364 // will end up using the expanded parameter pack types for type-checking.
2365 IsExpandedParameterPack = true;
2366 InstParams = TempParams;
2367 } else {
2368 // We cannot fully expand the pack expansion now, so just substitute
2369 // into the pattern.
2370 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2371
2372 LocalInstantiationScope Scope(SemaRef);
2373 InstParams = SubstTemplateParams(TempParams);
2374 if (!InstParams)
2375 return nullptr;
2376 }
2377 } else {
2378 // Perform the actual substitution of template parameters within a new,
2379 // local instantiation scope.
2380 LocalInstantiationScope Scope(SemaRef);
2381 InstParams = SubstTemplateParams(TempParams);
2382 if (!InstParams)
2383 return nullptr;
2384 }
2385
2386 // Build the template template parameter.
2387 TemplateTemplateParmDecl *Param;
2388 if (IsExpandedParameterPack)
2389 Param = TemplateTemplateParmDecl::Create(
2390 SemaRef.Context, Owner, D->getLocation(),
2391 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2392 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
2393 else
2394 Param = TemplateTemplateParmDecl::Create(
2395 SemaRef.Context, Owner, D->getLocation(),
2396 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
2397 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
2398 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2399 NestedNameSpecifierLoc QualifierLoc =
2400 D->getDefaultArgument().getTemplateQualifierLoc();
2401 QualifierLoc =
2402 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2403 TemplateName TName = SemaRef.SubstTemplateName(
2404 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2405 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2406 if (!TName.isNull())
2407 Param->setDefaultArgument(
2408 SemaRef.Context,
2409 TemplateArgumentLoc(TemplateArgument(TName),
2410 D->getDefaultArgument().getTemplateQualifierLoc(),
2411 D->getDefaultArgument().getTemplateNameLoc()));
2412 }
2413 Param->setAccess(AS_public);
2414
2415 // Introduce this template parameter's instantiation into the instantiation
2416 // scope.
2417 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
2418
2419 return Param;
2420}
2421
2422Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
2423 // Using directives are never dependent (and never contain any types or
2424 // expressions), so they require no explicit instantiation work.
2425
2426 UsingDirectiveDecl *Inst
2427 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
2428 D->getNamespaceKeyLocation(),
2429 D->getQualifierLoc(),
2430 D->getIdentLocation(),
2431 D->getNominatedNamespace(),
2432 D->getCommonAncestor());
2433
2434 // Add the using directive to its declaration context
2435 // only if this is not a function or method.
2436 if (!Owner->isFunctionOrMethod())
2437 Owner->addDecl(Inst);
2438
2439 return Inst;
2440}
2441
2442Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
2443
2444 // The nested name specifier may be dependent, for example
2445 // template <typename T> struct t {
2446 // struct s1 { T f1(); };
2447 // struct s2 : s1 { using s1::f1; };
2448 // };
2449 // template struct t<int>;
2450 // Here, in using s1::f1, s1 refers to t<T>::s1;
2451 // we need to substitute for t<int>::s1.
2452 NestedNameSpecifierLoc QualifierLoc
2453 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2454 TemplateArgs);
2455 if (!QualifierLoc)
2456 return nullptr;
2457
2458 // For an inheriting constructor declaration, the name of the using
2459 // declaration is the name of a constructor in this class, not in the
2460 // base class.
2461 DeclarationNameInfo NameInfo = D->getNameInfo();
2462 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2463 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
2464 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
2465 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
2466
2467 // We only need to do redeclaration lookups if we're in a class
2468 // scope (in fact, it's not really even possible in non-class
2469 // scopes).
2470 bool CheckRedeclaration = Owner->isRecord();
2471
2472 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2473 Sema::ForVisibleRedeclaration);
2474
2475 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
2476 D->getUsingLoc(),
2477 QualifierLoc,
2478 NameInfo,
2479 D->hasTypename());
2480
2481 CXXScopeSpec SS;
2482 SS.Adopt(QualifierLoc);
2483 if (CheckRedeclaration) {
2484 Prev.setHideTags(false);
2485 SemaRef.LookupQualifiedName(Prev, Owner);
2486
2487 // Check for invalid redeclarations.
2488 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2489 D->hasTypename(), SS,
2490 D->getLocation(), Prev))
2491 NewUD->setInvalidDecl();
2492
2493 }
2494
2495 if (!NewUD->isInvalidDecl() &&
2496 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(),
2497 SS, NameInfo, D->getLocation()))
2498 NewUD->setInvalidDecl();
2499
2500 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2501 NewUD->setAccess(D->getAccess());
2502 Owner->addDecl(NewUD);
2503
2504 // Don't process the shadow decls for an invalid decl.
2505 if (NewUD->isInvalidDecl())
2506 return NewUD;
2507
2508 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
2509 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
2510
2511 bool isFunctionScope = Owner->isFunctionOrMethod();
2512
2513 // Process the shadow decls.
2514 for (auto *Shadow : D->shadows()) {
2515 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
2516 // reconstruct it in the case where it matters.
2517 NamedDecl *OldTarget = Shadow->getTargetDecl();
2518 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
2519 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
2520 OldTarget = BaseShadow;
2521
2522 NamedDecl *InstTarget =
2523 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2524 Shadow->getLocation(), OldTarget, TemplateArgs));
2525 if (!InstTarget)
2526 return nullptr;
2527
2528 UsingShadowDecl *PrevDecl = nullptr;
2529 if (CheckRedeclaration) {
2530 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2531 continue;
2532 } else if (UsingShadowDecl *OldPrev =
2533 getPreviousDeclForInstantiation(Shadow)) {
2534 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2535 Shadow->getLocation(), OldPrev, TemplateArgs));
2536 }
2537
2538 UsingShadowDecl *InstShadow =
2539 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2540 PrevDecl);
2541 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
2542
2543 if (isFunctionScope)
2544 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
2545 }
2546
2547 return NewUD;
2548}
2549
2550Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
2551 // Ignore these; we handle them in bulk when processing the UsingDecl.
2552 return nullptr;
2553}
2554
2555Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
2556 ConstructorUsingShadowDecl *D) {
2557 // Ignore these; we handle them in bulk when processing the UsingDecl.
2558 return nullptr;
2559}
2560
2561template <typename T>
2562Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
2563 T *D, bool InstantiatingPackElement) {
2564 // If this is a pack expansion, expand it now.
2565 if (D->isPackExpansion() && !InstantiatingPackElement) {
2566 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2567 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
2568 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
2569
2570 // Determine whether the set of unexpanded parameter packs can and should
2571 // be expanded.
2572 bool Expand = true;
2573 bool RetainExpansion = false;
2574 Optional<unsigned> NumExpansions;
2575 if (SemaRef.CheckParameterPacksForExpansion(
2576 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
2577 Expand, RetainExpansion, NumExpansions))
2578 return nullptr;
2579
2580 // This declaration cannot appear within a function template signature,
2581 // so we can't have a partial argument list for a parameter pack.
2582 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2583, __extension__ __PRETTY_FUNCTION__))
2583 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2583, __extension__ __PRETTY_FUNCTION__))
;
2584
2585 if (!Expand) {
2586 // We cannot fully expand the pack expansion now, so substitute into the
2587 // pattern and create a new pack expansion.
2588 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2589 return instantiateUnresolvedUsingDecl(D, true);
2590 }
2591
2592 // Within a function, we don't have any normal way to check for conflicts
2593 // between shadow declarations from different using declarations in the
2594 // same pack expansion, but this is always ill-formed because all expansions
2595 // must produce (conflicting) enumerators.
2596 //
2597 // Sadly we can't just reject this in the template definition because it
2598 // could be valid if the pack is empty or has exactly one expansion.
2599 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
2600 SemaRef.Diag(D->getEllipsisLoc(),
2601 diag::err_using_decl_redeclaration_expansion);
2602 return nullptr;
2603 }
2604
2605 // Instantiate the slices of this pack and build a UsingPackDecl.
2606 SmallVector<NamedDecl*, 8> Expansions;
2607 for (unsigned I = 0; I != *NumExpansions; ++I) {
2608 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2609 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
2610 if (!Slice)
2611 return nullptr;
2612 // Note that we can still get unresolved using declarations here, if we
2613 // had arguments for all packs but the pattern also contained other
2614 // template arguments (this only happens during partial substitution, eg
2615 // into the body of a generic lambda in a function template).
2616 Expansions.push_back(cast<NamedDecl>(Slice));
2617 }
2618
2619 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2620 if (isDeclWithinFunction(D))
2621 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2622 return NewD;
2623 }
2624
2625 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
2626 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
2627
2628 NestedNameSpecifierLoc QualifierLoc
2629 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2630 TemplateArgs);
2631 if (!QualifierLoc)
2632 return nullptr;
2633
2634 CXXScopeSpec SS;
2635 SS.Adopt(QualifierLoc);
2636
2637 DeclarationNameInfo NameInfo
2638 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2639
2640 // Produce a pack expansion only if we're not instantiating a particular
2641 // slice of a pack expansion.
2642 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
2643 SemaRef.ArgumentPackSubstitutionIndex != -1;
2644 SourceLocation EllipsisLoc =
2645 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
2646
2647 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
2648 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
2649 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc, nullptr,
2650 /*IsInstantiation*/ true);
2651 if (UD)
2652 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
2653
2654 return UD;
2655}
2656
2657Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
2658 UnresolvedUsingTypenameDecl *D) {
2659 return instantiateUnresolvedUsingDecl(D);
2660}
2661
2662Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
2663 UnresolvedUsingValueDecl *D) {
2664 return instantiateUnresolvedUsingDecl(D);
2665}
2666
2667Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
2668 SmallVector<NamedDecl*, 8> Expansions;
2669 for (auto *UD : D->expansions()) {
2670 if (NamedDecl *NewUD =
2671 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
2672 Expansions.push_back(NewUD);
2673 else
2674 return nullptr;
2675 }
2676
2677 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
2678 if (isDeclWithinFunction(D))
2679 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
2680 return NewD;
2681}
2682
2683Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2684 ClassScopeFunctionSpecializationDecl *Decl) {
2685 CXXMethodDecl *OldFD = Decl->getSpecialization();
2686 CXXMethodDecl *NewFD =
2687 cast_or_null<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, nullptr, true));
2688 if (!NewFD)
2689 return nullptr;
2690
2691 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2692 Sema::ForExternalRedeclaration);
2693
2694 TemplateArgumentListInfo TemplateArgs;
2695 TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
2696 if (Decl->hasExplicitTemplateArgs()) {
2697 TemplateArgs = Decl->templateArgs();
2698 TemplateArgsPtr = &TemplateArgs;
2699 }
2700
2701 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
2702 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2703 Previous)) {
2704 NewFD->setInvalidDecl();
2705 return NewFD;
2706 }
2707
2708 // Associate the specialization with the pattern.
2709 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2710 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2710, __extension__ __PRETTY_FUNCTION__))
;
2711 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2712
2713 return NewFD;
2714}
2715
2716Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2717 OMPThreadPrivateDecl *D) {
2718 SmallVector<Expr *, 5> Vars;
2719 for (auto *I : D->varlists()) {
2720 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
2721 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2721, __extension__ __PRETTY_FUNCTION__))
;
2722 Vars.push_back(Var);
2723 }
2724
2725 OMPThreadPrivateDecl *TD =
2726 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2727
2728 TD->setAccess(AS_public);
2729 Owner->addDecl(TD);
2730
2731 return TD;
2732}
2733
2734Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
2735 OMPDeclareReductionDecl *D) {
2736 // Instantiate type and check if it is allowed.
2737 QualType SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
2738 D->getLocation(),
2739 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
2740 D->getLocation(), DeclarationName())));
2741 if (SubstReductionType.isNull())
2742 return nullptr;
2743 bool IsCorrect = !SubstReductionType.isNull();
2744 // Create instantiated copy.
2745 std::pair<QualType, SourceLocation> ReductionTypes[] = {
2746 std::make_pair(SubstReductionType, D->getLocation())};
2747 auto *PrevDeclInScope = D->getPrevDeclInScope();
2748 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
2749 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
2750 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
2751 ->get<Decl *>());
2752 }
2753 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
2754 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
2755 PrevDeclInScope);
2756 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
2757 if (isDeclWithinFunction(NewDRD))
2758 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
2759 Expr *SubstCombiner = nullptr;
2760 Expr *SubstInitializer = nullptr;
2761 // Combiners instantiation sequence.
2762 if (D->getCombiner()) {
2763 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
2764 /*S=*/nullptr, NewDRD);
2765 const char *Names[] = {"omp_in", "omp_out"};
2766 for (auto &Name : Names) {
2767 DeclarationName DN(&SemaRef.Context.Idents.get(Name));
2768 auto OldLookup = D->lookup(DN);
2769 auto Lookup = NewDRD->lookup(DN);
2770 if (!OldLookup.empty() && !Lookup.empty()) {
2771 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2771, __extension__ __PRETTY_FUNCTION__))
;
2772 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldLookup.front(),
2773 Lookup.front());
2774 }
2775 }
2776 SubstCombiner = SemaRef.SubstExpr(D->getCombiner(), TemplateArgs).get();
2777 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
2778 // Initializers instantiation sequence.
2779 if (D->getInitializer()) {
2780 VarDecl *OmpPrivParm =
2781 SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
2782 /*S=*/nullptr, NewDRD);
2783 const char *Names[] = {"omp_orig", "omp_priv"};
2784 for (auto &Name : Names) {
2785 DeclarationName DN(&SemaRef.Context.Idents.get(Name));
2786 auto OldLookup = D->lookup(DN);
2787 auto Lookup = NewDRD->lookup(DN);
2788 if (!OldLookup.empty() && !Lookup.empty()) {
2789 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2789, __extension__ __PRETTY_FUNCTION__))
;
2790 auto *OldVD = cast<VarDecl>(OldLookup.front());
2791 auto *NewVD = cast<VarDecl>(Lookup.front());
2792 SemaRef.InstantiateVariableInitializer(NewVD, OldVD, TemplateArgs);
2793 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldVD, NewVD);
2794 }
2795 }
2796 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
2797 SubstInitializer =
2798 SemaRef.SubstExpr(D->getInitializer(), TemplateArgs).get();
2799 } else {
2800 IsCorrect = IsCorrect && OmpPrivParm->hasInit();
2801 }
2802 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(
2803 NewDRD, SubstInitializer, OmpPrivParm);
2804 }
2805 IsCorrect =
2806 IsCorrect && SubstCombiner &&
2807 (!D->getInitializer() ||
2808 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
2809 SubstInitializer) ||
2810 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
2811 !SubstInitializer && !SubstInitializer));
2812 } else
2813 IsCorrect = false;
2814
2815 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(/*S=*/nullptr, DRD,
2816 IsCorrect);
2817
2818 return NewDRD;
2819}
2820
2821Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
2822 OMPCapturedExprDecl * /*D*/) {
2823 llvm_unreachable("Should not be met in templates")::llvm::llvm_unreachable_internal("Should not be met in templates"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2823)
;
2824}
2825
2826Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2827 return VisitFunctionDecl(D, nullptr);
2828}
2829
2830Decl *
2831TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
2832 return VisitFunctionDecl(D, nullptr);
2833}
2834
2835Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2836 return VisitCXXMethodDecl(D, nullptr);
2837}
2838
2839Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2840 llvm_unreachable("There are only CXXRecordDecls in C++")::llvm::llvm_unreachable_internal("There are only CXXRecordDecls in C++"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2840)
;
2841}
2842
2843Decl *
2844TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2845 ClassTemplateSpecializationDecl *D) {
2846 // As a MS extension, we permit class-scope explicit specialization
2847 // of member class templates.
2848 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2849 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2852, __extension__ __PRETTY_FUNCTION__))
2850 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2852, __extension__ __PRETTY_FUNCTION__))
2851 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2852, __extension__ __PRETTY_FUNCTION__))
2852 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2852, __extension__ __PRETTY_FUNCTION__))
;
2853
2854 // Lookup the already-instantiated declaration in the instantiation
2855 // of the class template. FIXME: Diagnose or assert if this fails?
2856 DeclContext::lookup_result Found
2857 = Owner->lookup(ClassTemplate->getDeclName());
2858 if (Found.empty())
2859 return nullptr;
2860 ClassTemplateDecl *InstClassTemplate
2861 = dyn_cast<ClassTemplateDecl>(Found.front());
2862 if (!InstClassTemplate)
2863 return nullptr;
2864
2865 // Substitute into the template arguments of the class template explicit
2866 // specialization.
2867 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2868 castAs<TemplateSpecializationTypeLoc>();
2869 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2870 Loc.getRAngleLoc());
2871 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2872 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2873 ArgLocs.push_back(Loc.getArgLoc(I));
2874 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2875 InstTemplateArgs, TemplateArgs))
2876 return nullptr;
2877
2878 // Check that the template argument list is well-formed for this
2879 // class template.
2880 SmallVector<TemplateArgument, 4> Converted;
2881 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2882 D->getLocation(),
2883 InstTemplateArgs,
2884 false,
2885 Converted))
2886 return nullptr;
2887
2888 // Figure out where to insert this class template explicit specialization
2889 // in the member template's set of class template explicit specializations.
2890 void *InsertPos = nullptr;
2891 ClassTemplateSpecializationDecl *PrevDecl =
2892 InstClassTemplate->findSpecialization(Converted, InsertPos);
2893
2894 // Check whether we've already seen a conflicting instantiation of this
2895 // declaration (for instance, if there was a prior implicit instantiation).
2896 bool Ignored;
2897 if (PrevDecl &&
2898 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2899 D->getSpecializationKind(),
2900 PrevDecl,
2901 PrevDecl->getSpecializationKind(),
2902 PrevDecl->getPointOfInstantiation(),
2903 Ignored))
2904 return nullptr;
2905
2906 // If PrevDecl was a definition and D is also a definition, diagnose.
2907 // This happens in cases like:
2908 //
2909 // template<typename T, typename U>
2910 // struct Outer {
2911 // template<typename X> struct Inner;
2912 // template<> struct Inner<T> {};
2913 // template<> struct Inner<U> {};
2914 // };
2915 //
2916 // Outer<int, int> outer; // error: the explicit specializations of Inner
2917 // // have the same signature.
2918 if (PrevDecl && PrevDecl->getDefinition() &&
2919 D->isThisDeclarationADefinition()) {
2920 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2921 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2922 diag::note_previous_definition);
2923 return nullptr;
2924 }
2925
2926 // Create the class template partial specialization declaration.
2927 ClassTemplateSpecializationDecl *InstD
2928 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2929 D->getTagKind(),
2930 Owner,
2931 D->getLocStart(),
2932 D->getLocation(),
2933 InstClassTemplate,
2934 Converted,
2935 PrevDecl);
2936
2937 // Add this partial specialization to the set of class template partial
2938 // specializations.
2939 if (!PrevDecl)
2940 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2941
2942 // Substitute the nested name specifier, if any.
2943 if (SubstQualifier(D, InstD))
2944 return nullptr;
2945
2946 // Build the canonical type that describes the converted template
2947 // arguments of the class template explicit specialization.
2948 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2949 TemplateName(InstClassTemplate), Converted,
2950 SemaRef.Context.getRecordType(InstD));
2951
2952 // Build the fully-sugared type for this class template
2953 // specialization as the user wrote in the specialization
2954 // itself. This means that we'll pretty-print the type retrieved
2955 // from the specialization's declaration the way that the user
2956 // actually wrote the specialization, rather than formatting the
2957 // name based on the "canonical" representation used to store the
2958 // template arguments in the specialization.
2959 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2960 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2961 CanonType);
2962
2963 InstD->setAccess(D->getAccess());
2964 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2965 InstD->setSpecializationKind(D->getSpecializationKind());
2966 InstD->setTypeAsWritten(WrittenTy);
2967 InstD->setExternLoc(D->getExternLoc());
2968 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2969
2970 Owner->addDecl(InstD);
2971
2972 // Instantiate the members of the class-scope explicit specialization eagerly.
2973 // We don't have support for lazy instantiation of an explicit specialization
2974 // yet, and MSVC eagerly instantiates in this case.
2975 if (D->isThisDeclarationADefinition() &&
2976 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2977 TSK_ImplicitInstantiation,
2978 /*Complain=*/true))
2979 return nullptr;
2980
2981 return InstD;
2982}
2983
2984Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2985 VarTemplateSpecializationDecl *D) {
2986
2987 TemplateArgumentListInfo VarTemplateArgsInfo;
2988 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2989 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2990, __extension__ __PRETTY_FUNCTION__))
2990 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 2990, __extension__ __PRETTY_FUNCTION__))
;
2991
2992 // Substitute the current template arguments.
2993 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2994 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2995 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2996
2997 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2998 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2999 return nullptr;
3000
3001 // Check that the template argument list is well-formed for this template.
3002 SmallVector<TemplateArgument, 4> Converted;
3003 if (SemaRef.CheckTemplateArgumentList(
3004 VarTemplate, VarTemplate->getLocStart(),
3005 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
3006 Converted))
3007 return nullptr;
3008
3009 // Find the variable template specialization declaration that
3010 // corresponds to these arguments.
3011 void *InsertPos = nullptr;
3012 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
3013 Converted, InsertPos))
3014 // If we already have a variable template specialization, return it.
3015 return VarSpec;
3016
3017 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
3018 VarTemplateArgsInfo, Converted);
3019}
3020
3021Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3022 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
3023 const TemplateArgumentListInfo &TemplateArgsInfo,
3024 ArrayRef<TemplateArgument> Converted) {
3025
3026 // Do substitution on the type of the declaration
3027 TypeSourceInfo *DI =
3028 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3029 D->getTypeSpecStartLoc(), D->getDeclName());
3030 if (!DI)
3031 return nullptr;
3032
3033 if (DI->getType()->isFunctionType()) {
3034 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3035 << D->isStaticDataMember() << DI->getType();
3036 return nullptr;
3037 }
3038
3039 // Build the instantiated declaration
3040 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3041 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3042 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3043 Var->setTemplateArgsInfo(TemplateArgsInfo);
3044 if (InsertPos)
3045 VarTemplate->AddSpecialization(Var, InsertPos);
3046
3047 // Substitute the nested name specifier, if any.
3048 if (SubstQualifier(D, Var))
3049 return nullptr;
3050
3051 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
3052 Owner, StartingScope);
3053
3054 return Var;
3055}
3056
3057Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3058 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3058)
;
3059}
3060
3061Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3062 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3063 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3064 DiagnosticsEngine::Error,
3065 "cannot instantiate %0 yet");
3066 SemaRef.Diag(D->getLocation(), DiagID)
3067 << D->getDeclKindName();
3068
3069 return nullptr;
3070}
3071
3072Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
3073 llvm_unreachable("Unexpected decl")::llvm::llvm_unreachable_internal("Unexpected decl", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3073)
;
3074}
3075
3076Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
3077 const MultiLevelTemplateArgumentList &TemplateArgs) {
3078 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
3079 if (D->isInvalidDecl())
3080 return nullptr;
3081
3082 return Instantiator.Visit(D);
3083}
3084
3085/// \brief Instantiates a nested template parameter list in the current
3086/// instantiation context.
3087///
3088/// \param L The parameter list to instantiate
3089///
3090/// \returns NULL if there was an error
3091TemplateParameterList *
3092TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
3093 // Get errors for all the parameters before bailing out.
3094 bool Invalid = false;
3095
3096 unsigned N = L->size();
3097 typedef SmallVector<NamedDecl *, 8> ParamVector;
3098 ParamVector Params;
3099 Params.reserve(N);
3100 for (auto &P : *L) {
3101 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
3102 Params.push_back(D);
3103 Invalid = Invalid || !D || D->isInvalidDecl();
3104 }
3105
3106 // Clean up if we had an error.
3107 if (Invalid)
3108 return nullptr;
3109
3110 // Note: we substitute into associated constraints later
3111 Expr *const UninstantiatedRequiresClause = L->getRequiresClause();
3112
3113 TemplateParameterList *InstL
3114 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
3115 L->getLAngleLoc(), Params,
3116 L->getRAngleLoc(),
3117 UninstantiatedRequiresClause);
3118 return InstL;
3119}
3120
3121/// \brief Instantiate the declaration of a class template partial
3122/// specialization.
3123///
3124/// \param ClassTemplate the (instantiated) class template that is partially
3125// specialized by the instantiation of \p PartialSpec.
3126///
3127/// \param PartialSpec the (uninstantiated) class template partial
3128/// specialization that we are instantiating.
3129///
3130/// \returns The instantiated partial specialization, if successful; otherwise,
3131/// NULL to indicate an error.
3132ClassTemplatePartialSpecializationDecl *
3133TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
3134 ClassTemplateDecl *ClassTemplate,
3135 ClassTemplatePartialSpecializationDecl *PartialSpec) {
3136 // Create a local instantiation scope for this class template partial
3137 // specialization, which will contain the instantiations of the template
3138 // parameters.
3139 LocalInstantiationScope Scope(SemaRef);
3140
3141 // Substitute into the template parameters of the class template partial
3142 // specialization.
3143 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3144 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3145 if (!InstParams)
3146 return nullptr;
3147
3148 // Substitute into the template arguments of the class template partial
3149 // specialization.
3150 const ASTTemplateArgumentListInfo *TemplArgInfo
3151 = PartialSpec->getTemplateArgsAsWritten();
3152 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3153 TemplArgInfo->RAngleLoc);
3154 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3155 TemplArgInfo->NumTemplateArgs,
3156 InstTemplateArgs, TemplateArgs))
3157 return nullptr;
3158
3159 // Check that the template argument list is well-formed for this
3160 // class template.
3161 SmallVector<TemplateArgument, 4> Converted;
3162 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
3163 PartialSpec->getLocation(),
3164 InstTemplateArgs,
3165 false,
3166 Converted))
3167 return nullptr;
3168
3169 // Check these arguments are valid for a template partial specialization.
3170 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3171 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
3172 Converted))
3173 return nullptr;
3174
3175 // Figure out where to insert this class template partial specialization
3176 // in the member template's set of class template partial specializations.
3177 void *InsertPos = nullptr;
3178 ClassTemplateSpecializationDecl *PrevDecl
3179 = ClassTemplate->findPartialSpecialization(Converted, InsertPos);
3180
3181 // Build the canonical type that describes the converted template
3182 // arguments of the class template partial specialization.
3183 QualType CanonType
3184 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
3185 Converted);
3186
3187 // Build the fully-sugared type for this class template
3188 // specialization as the user wrote in the specialization
3189 // itself. This means that we'll pretty-print the type retrieved
3190 // from the specialization's declaration the way that the user
3191 // actually wrote the specialization, rather than formatting the
3192 // name based on the "canonical" representation used to store the
3193 // template arguments in the specialization.
3194 TypeSourceInfo *WrittenTy
3195 = SemaRef.Context.getTemplateSpecializationTypeInfo(
3196 TemplateName(ClassTemplate),
3197 PartialSpec->getLocation(),
3198 InstTemplateArgs,
3199 CanonType);
3200
3201 if (PrevDecl) {
3202 // We've already seen a partial specialization with the same template
3203 // parameters and template arguments. This can happen, for example, when
3204 // substituting the outer template arguments ends up causing two
3205 // class template partial specializations of a member class template
3206 // to have identical forms, e.g.,
3207 //
3208 // template<typename T, typename U>
3209 // struct Outer {
3210 // template<typename X, typename Y> struct Inner;
3211 // template<typename Y> struct Inner<T, Y>;
3212 // template<typename Y> struct Inner<U, Y>;
3213 // };
3214 //
3215 // Outer<int, int> outer; // error: the partial specializations of Inner
3216 // // have the same signature.
3217 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
3218 << WrittenTy->getType();
3219 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
3220 << SemaRef.Context.getTypeDeclType(PrevDecl);
3221 return nullptr;
3222 }
3223
3224
3225 // Create the class template partial specialization declaration.
3226 ClassTemplatePartialSpecializationDecl *InstPartialSpec
3227 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
3228 PartialSpec->getTagKind(),
3229 Owner,
3230 PartialSpec->getLocStart(),
3231 PartialSpec->getLocation(),
3232 InstParams,
3233 ClassTemplate,
3234 Converted,
3235 InstTemplateArgs,
3236 CanonType,
3237 nullptr);
3238 // Substitute the nested name specifier, if any.
3239 if (SubstQualifier(PartialSpec, InstPartialSpec))
3240 return nullptr;
3241
3242 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3243 InstPartialSpec->setTypeAsWritten(WrittenTy);
3244
3245 // Check the completed partial specialization.
3246 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3247
3248 // Add this partial specialization to the set of class template partial
3249 // specializations.
3250 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
3251 /*InsertPos=*/nullptr);
3252 return InstPartialSpec;
3253}
3254
3255/// \brief Instantiate the declaration of a variable template partial
3256/// specialization.
3257///
3258/// \param VarTemplate the (instantiated) variable template that is partially
3259/// specialized by the instantiation of \p PartialSpec.
3260///
3261/// \param PartialSpec the (uninstantiated) variable template partial
3262/// specialization that we are instantiating.
3263///
3264/// \returns The instantiated partial specialization, if successful; otherwise,
3265/// NULL to indicate an error.
3266VarTemplatePartialSpecializationDecl *
3267TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
3268 VarTemplateDecl *VarTemplate,
3269 VarTemplatePartialSpecializationDecl *PartialSpec) {
3270 // Create a local instantiation scope for this variable template partial
3271 // specialization, which will contain the instantiations of the template
3272 // parameters.
3273 LocalInstantiationScope Scope(SemaRef);
3274
3275 // Substitute into the template parameters of the variable template partial
3276 // specialization.
3277 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
3278 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
3279 if (!InstParams)
3280 return nullptr;
3281
3282 // Substitute into the template arguments of the variable template partial
3283 // specialization.
3284 const ASTTemplateArgumentListInfo *TemplArgInfo
3285 = PartialSpec->getTemplateArgsAsWritten();
3286 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
3287 TemplArgInfo->RAngleLoc);
3288 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
3289 TemplArgInfo->NumTemplateArgs,
3290 InstTemplateArgs, TemplateArgs))
3291 return nullptr;
3292
3293 // Check that the template argument list is well-formed for this
3294 // class template.
3295 SmallVector<TemplateArgument, 4> Converted;
3296 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
3297 InstTemplateArgs, false, Converted))
3298 return nullptr;
3299
3300 // Check these arguments are valid for a template partial specialization.
3301 if (SemaRef.CheckTemplatePartialSpecializationArgs(
3302 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
3303 Converted))
3304 return nullptr;
3305
3306 // Figure out where to insert this variable template partial specialization
3307 // in the member template's set of variable template partial specializations.
3308 void *InsertPos = nullptr;
3309 VarTemplateSpecializationDecl *PrevDecl =
3310 VarTemplate->findPartialSpecialization(Converted, InsertPos);
3311
3312 // Build the canonical type that describes the converted template
3313 // arguments of the variable template partial specialization.
3314 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3315 TemplateName(VarTemplate), Converted);
3316
3317 // Build the fully-sugared type for this variable template
3318 // specialization as the user wrote in the specialization
3319 // itself. This means that we'll pretty-print the type retrieved
3320 // from the specialization's declaration the way that the user
3321 // actually wrote the specialization, rather than formatting the
3322 // name based on the "canonical" representation used to store the
3323 // template arguments in the specialization.
3324 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3325 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
3326 CanonType);
3327
3328 if (PrevDecl) {
3329 // We've already seen a partial specialization with the same template
3330 // parameters and template arguments. This can happen, for example, when
3331 // substituting the outer template arguments ends up causing two
3332 // variable template partial specializations of a member variable template
3333 // to have identical forms, e.g.,
3334 //
3335 // template<typename T, typename U>
3336 // struct Outer {
3337 // template<typename X, typename Y> pair<X,Y> p;
3338 // template<typename Y> pair<T, Y> p;
3339 // template<typename Y> pair<U, Y> p;
3340 // };
3341 //
3342 // Outer<int, int> outer; // error: the partial specializations of Inner
3343 // // have the same signature.
3344 SemaRef.Diag(PartialSpec->getLocation(),
3345 diag::err_var_partial_spec_redeclared)
3346 << WrittenTy->getType();
3347 SemaRef.Diag(PrevDecl->getLocation(),
3348 diag::note_var_prev_partial_spec_here);
3349 return nullptr;
3350 }
3351
3352 // Do substitution on the type of the declaration
3353 TypeSourceInfo *DI = SemaRef.SubstType(
3354 PartialSpec->getTypeSourceInfo(), TemplateArgs,
3355 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
3356 if (!DI)
3357 return nullptr;
3358
3359 if (DI->getType()->isFunctionType()) {
3360 SemaRef.Diag(PartialSpec->getLocation(),
3361 diag::err_variable_instantiates_to_function)
3362 << PartialSpec->isStaticDataMember() << DI->getType();
3363 return nullptr;
3364 }
3365
3366 // Create the variable template partial specialization declaration.
3367 VarTemplatePartialSpecializationDecl *InstPartialSpec =
3368 VarTemplatePartialSpecializationDecl::Create(
3369 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
3370 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
3371 DI, PartialSpec->getStorageClass(), Converted, InstTemplateArgs);
3372
3373 // Substitute the nested name specifier, if any.
3374 if (SubstQualifier(PartialSpec, InstPartialSpec))
3375 return nullptr;
3376
3377 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
3378 InstPartialSpec->setTypeAsWritten(WrittenTy);
3379
3380 // Check the completed partial specialization.
3381 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
3382
3383 // Add this partial specialization to the set of variable template partial
3384 // specializations. The instantiation of the initializer is not necessary.
3385 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
3386
3387 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
3388 LateAttrs, Owner, StartingScope);
3389
3390 return InstPartialSpec;
3391}
3392
3393TypeSourceInfo*
3394TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
3395 SmallVectorImpl<ParmVarDecl *> &Params) {
3396 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
3397 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3397, __extension__ __PRETTY_FUNCTION__))
;
3398 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3398, __extension__ __PRETTY_FUNCTION__))
;
3399
3400 CXXRecordDecl *ThisContext = nullptr;
3401 unsigned ThisTypeQuals = 0;
3402 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3403 ThisContext = cast<CXXRecordDecl>(Owner);
3404 ThisTypeQuals = Method->getTypeQualifiers();
3405 }
3406
3407 TypeSourceInfo *NewTInfo
3408 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
3409 D->getTypeSpecStartLoc(),
3410 D->getDeclName(),
3411 ThisContext, ThisTypeQuals);
3412 if (!NewTInfo)
3413 return nullptr;
3414
3415 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
3416 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
3417 if (NewTInfo != OldTInfo) {
3418 // Get parameters from the new type info.
3419 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
3420 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
3421 unsigned NewIdx = 0;
3422 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
3423 OldIdx != NumOldParams; ++OldIdx) {
3424 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
3425 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
3426
3427 Optional<unsigned> NumArgumentsInExpansion;
3428 if (OldParam->isParameterPack())
3429 NumArgumentsInExpansion =
3430 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
3431 TemplateArgs);
3432 if (!NumArgumentsInExpansion) {
3433 // Simple case: normal parameter, or a parameter pack that's
3434 // instantiated to a (still-dependent) parameter pack.
3435 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3436 Params.push_back(NewParam);
3437 Scope->InstantiatedLocal(OldParam, NewParam);
3438 } else {
3439 // Parameter pack expansion: make the instantiation an argument pack.
3440 Scope->MakeInstantiatedLocalArgPack(OldParam);
3441 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
3442 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
3443 Params.push_back(NewParam);
3444 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
3445 }
3446 }
3447 }
3448 } else {
3449 // The function type itself was not dependent and therefore no
3450 // substitution occurred. However, we still need to instantiate
3451 // the function parameters themselves.
3452 const FunctionProtoType *OldProto =
3453 cast<FunctionProtoType>(OldProtoLoc.getType());
3454 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
3455 ++i) {
3456 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
3457 if (!OldParam) {
3458 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
3459 D, D->getLocation(), OldProto->getParamType(i)));
3460 continue;
3461 }
3462
3463 ParmVarDecl *Parm =
3464 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
3465 if (!Parm)
3466 return nullptr;
3467 Params.push_back(Parm);
3468 }
3469 }
3470 } else {
3471 // If the type of this function, after ignoring parentheses, is not
3472 // *directly* a function type, then we're instantiating a function that
3473 // was declared via a typedef or with attributes, e.g.,
3474 //
3475 // typedef int functype(int, int);
3476 // functype func;
3477 // int __cdecl meth(int, int);
3478 //
3479 // In this case, we'll just go instantiate the ParmVarDecls that we
3480 // synthesized in the method declaration.
3481 SmallVector<QualType, 4> ParamTypes;
3482 Sema::ExtParameterInfoBuilder ExtParamInfos;
3483 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
3484 TemplateArgs, ParamTypes, &Params,
3485 ExtParamInfos))
3486 return nullptr;
3487 }
3488
3489 return NewTInfo;
3490}
3491
3492/// Introduce the instantiated function parameters into the local
3493/// instantiation scope, and set the parameter names to those used
3494/// in the template.
3495static bool addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
3496 const FunctionDecl *PatternDecl,
3497 LocalInstantiationScope &Scope,
3498 const MultiLevelTemplateArgumentList &TemplateArgs) {
3499 unsigned FParamIdx = 0;
3500 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
3501 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
3502 if (!PatternParam->isParameterPack()) {
3503 // Simple case: not a parameter pack.
3504 assert(FParamIdx < Function->getNumParams())(static_cast <bool> (FParamIdx < Function->getNumParams
()) ? void (0) : __assert_fail ("FParamIdx < Function->getNumParams()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3504, __extension__ __PRETTY_FUNCTION__))
;
3505 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3506 FunctionParam->setDeclName(PatternParam->getDeclName());
3507 // If the parameter's type is not dependent, update it to match the type
3508 // in the pattern. They can differ in top-level cv-qualifiers, and we want
3509 // the pattern's type here. If the type is dependent, they can't differ,
3510 // per core issue 1668. Substitute into the type from the pattern, in case
3511 // it's instantiation-dependent.
3512 // FIXME: Updating the type to work around this is at best fragile.
3513 if (!PatternDecl->getType()->isDependentType()) {
3514 QualType T = S.SubstType(PatternParam->getType(), TemplateArgs,
3515 FunctionParam->getLocation(),
3516 FunctionParam->getDeclName());
3517 if (T.isNull())
3518 return true;
3519 FunctionParam->setType(T);
3520 }
3521
3522 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3523 ++FParamIdx;
3524 continue;
3525 }
3526
3527 // Expand the parameter pack.
3528 Scope.MakeInstantiatedLocalArgPack(PatternParam);
3529 Optional<unsigned> NumArgumentsInExpansion
3530 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
3531 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3532, __extension__ __PRETTY_FUNCTION__))
3532 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3532, __extension__ __PRETTY_FUNCTION__))
;
3533 QualType PatternType =
3534 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
3535 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
3536 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3537 FunctionParam->setDeclName(PatternParam->getDeclName());
3538 if (!PatternDecl->getType()->isDependentType()) {
3539 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, Arg);
3540 QualType T = S.SubstType(PatternType, TemplateArgs,
3541 FunctionParam->getLocation(),
3542 FunctionParam->getDeclName());
3543 if (T.isNull())
3544 return true;
3545 FunctionParam->setType(T);
3546 }
3547
3548 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3549 ++FParamIdx;
3550 }
3551 }
3552
3553 return false;
3554}
3555
3556void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3557 FunctionDecl *Decl) {
3558 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3559 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
3560 return;
3561
3562 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3563 InstantiatingTemplate::ExceptionSpecification());
3564 if (Inst.isInvalid()) {
3565 // We hit the instantiation depth limit. Clear the exception specification
3566 // so that our callers don't have to cope with EST_Uninstantiated.
3567 UpdateExceptionSpec(Decl, EST_None);
3568 return;
3569 }
3570 if (Inst.isAlreadyInstantiating()) {
3571 // This exception specification indirectly depends on itself. Reject.
3572 // FIXME: Corresponding rule in the standard?
3573 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
3574 UpdateExceptionSpec(Decl, EST_None);
3575 return;
3576 }
3577
3578 // Enter the scope of this instantiation. We don't use
3579 // PushDeclContext because we don't have a scope.
3580 Sema::ContextRAII savedContext(*this, Decl);
3581 LocalInstantiationScope Scope(*this);
3582
3583 MultiLevelTemplateArgumentList TemplateArgs =
3584 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
3585
3586 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3587 if (addInstantiatedParametersToScope(*this, Decl, Template, Scope,
3588 TemplateArgs)) {
3589 UpdateExceptionSpec(Decl, EST_None);
3590 return;
3591 }
3592
3593 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
3594 TemplateArgs);
3595}
3596
3597/// \brief Initializes the common fields of an instantiation function
3598/// declaration (New) from the corresponding fields of its template (Tmpl).
3599///
3600/// \returns true if there was an error
3601bool
3602TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
3603 FunctionDecl *Tmpl) {
3604 if (Tmpl->isDeleted())
3605 New->setDeletedAsWritten();
3606
3607 New->setImplicit(Tmpl->isImplicit());
3608
3609 // Forward the mangling number from the template to the instantiated decl.
3610 SemaRef.Context.setManglingNumber(New,
3611 SemaRef.Context.getManglingNumber(Tmpl));
3612
3613 // If we are performing substituting explicitly-specified template arguments
3614 // or deduced template arguments into a function template and we reach this
3615 // point, we are now past the point where SFINAE applies and have committed
3616 // to keeping the new function template specialization. We therefore
3617 // convert the active template instantiation for the function template
3618 // into a template instantiation for this specific function template
3619 // specialization, which is not a SFINAE context, so that we diagnose any
3620 // further errors in the declaration itself.
3621 typedef Sema::CodeSynthesisContext ActiveInstType;
3622 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
3623 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3624 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
3625 if (FunctionTemplateDecl *FunTmpl
3626 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
3627 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3628, __extension__ __PRETTY_FUNCTION__))
3628 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3628, __extension__ __PRETTY_FUNCTION__))
;
3629 (void) FunTmpl;
3630 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
3631 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
3632 ActiveInst.Entity = New;
3633 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
3634 }
3635 }
3636
3637 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3638 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3638, __extension__ __PRETTY_FUNCTION__))
;
3639
3640 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
3641 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3642
3643 // DR1330: In C++11, defer instantiation of a non-trivial
3644 // exception specification.
3645 // DR1484: Local classes and their members are instantiated along with the
3646 // containing function.
3647 if (SemaRef.getLangOpts().CPlusPlus11 &&
3648 EPI.ExceptionSpec.Type != EST_None &&
3649 EPI.ExceptionSpec.Type != EST_DynamicNone &&
3650 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
3651 !Tmpl->isLexicallyWithinFunctionOrMethod()) {
3652 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3653 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
3654 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
3655 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3656 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
3657 NewEST = EST_Unevaluated;
3658
3659 // Mark the function has having an uninstantiated exception specification.
3660 const FunctionProtoType *NewProto
3661 = New->getType()->getAs<FunctionProtoType>();
3662 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3662, __extension__ __PRETTY_FUNCTION__))
;
3663 EPI = NewProto->getExtProtoInfo();
3664 EPI.ExceptionSpec.Type = NewEST;
3665 EPI.ExceptionSpec.SourceDecl = New;
3666 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
3667 New->setType(SemaRef.Context.getFunctionType(
3668 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
3669 } else {
3670 Sema::ContextRAII SwitchContext(SemaRef, New);
3671 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
3672 }
3673 }
3674
3675 // Get the definition. Leaves the variable unchanged if undefined.
3676 const FunctionDecl *Definition = Tmpl;
3677 Tmpl->isDefined(Definition);
3678
3679 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3680 LateAttrs, StartingScope);
3681
3682 return false;
3683}
3684
3685/// \brief Initializes common fields of an instantiated method
3686/// declaration (New) from the corresponding fields of its template
3687/// (Tmpl).
3688///
3689/// \returns true if there was an error
3690bool
3691TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
3692 CXXMethodDecl *Tmpl) {
3693 if (InitFunctionInstantiation(New, Tmpl))
3694 return true;
3695
3696 New->setAccess(Tmpl->getAccess());
3697 if (Tmpl->isVirtualAsWritten())
3698 New->setVirtualAsWritten(true);
3699
3700 // FIXME: New needs a pointer to Tmpl
3701 return false;
3702}
3703
3704/// Instantiate (or find existing instantiation of) a function template with a
3705/// given set of template arguments.
3706///
3707/// Usually this should not be used, and template argument deduction should be
3708/// used in its place.
3709FunctionDecl *
3710Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
3711 const TemplateArgumentList *Args,
3712 SourceLocation Loc) {
3713 FunctionDecl *FD = FTD->getTemplatedDecl();
3714
3715 sema::TemplateDeductionInfo Info(Loc);
3716 InstantiatingTemplate Inst(
3717 *this, Loc, FTD, Args->asArray(),
3718 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
3719 if (Inst.isInvalid())
3720 return nullptr;
3721
3722 ContextRAII SavedContext(*this, FD);
3723 MultiLevelTemplateArgumentList MArgs(*Args);
3724
3725 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
3726}
3727
3728/// In the MS ABI, we need to instantiate default arguments of dllexported
3729/// default constructors along with the constructor definition. This allows IR
3730/// gen to emit a constructor closure which calls the default constructor with
3731/// its default arguments.
3732static void InstantiateDefaultCtorDefaultArgs(Sema &S,
3733 CXXConstructorDecl *Ctor) {
3734 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3735, __extension__ __PRETTY_FUNCTION__))
3735 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3735, __extension__ __PRETTY_FUNCTION__))
;
3736 unsigned NumParams = Ctor->getNumParams();
3737 if (NumParams == 0)
3738 return;
3739 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
3740 if (!Attr)
3741 return;
3742 for (unsigned I = 0; I != NumParams; ++I) {
3743 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
3744 Ctor->getParamDecl(I));
3745 S.DiscardCleanupsInEvaluationContext();
3746 }
3747}
3748
3749/// \brief Instantiate the definition of the given function from its
3750/// template.
3751///
3752/// \param PointOfInstantiation the point at which the instantiation was
3753/// required. Note that this is not precisely a "point of instantiation"
3754/// for the function, but it's close.
3755///
3756/// \param Function the already-instantiated declaration of a
3757/// function template specialization or member function of a class template
3758/// specialization.
3759///
3760/// \param Recursive if true, recursively instantiates any functions that
3761/// are required by this instantiation.
3762///
3763/// \param DefinitionRequired if true, then we are performing an explicit
3764/// instantiation where the body of the function is required. Complain if
3765/// there is no such body.
3766void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
3767 FunctionDecl *Function,
3768 bool Recursive,
3769 bool DefinitionRequired,
3770 bool AtEndOfTU) {
3771 if (Function->isInvalidDecl() || Function->isDefined() ||
29
Assuming the condition is false
30
Assuming the condition is false
31
Taking false branch
3772 isa<CXXDeductionGuideDecl>(Function))
3773 return;
3774
3775 // Never instantiate an explicit specialization except if it is a class scope
3776 // explicit specialization.
3777 TemplateSpecializationKind TSK = Function->getTemplateSpecializationKind();
3778 if (TSK == TSK_ExplicitSpecialization &&
32
Assuming 'TSK' is not equal to TSK_ExplicitSpecialization
3779 !Function->getClassScopeSpecializationPattern())
3780 return;
3781
3782 // Find the function body that we'll be substituting.
3783 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
3784 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3784, __extension__ __PRETTY_FUNCTION__))
;
3785
3786 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
3787 Stmt *Pattern = nullptr;
3788 if (PatternDef) {
33
Taking false branch
3789 Pattern = PatternDef->getBody(PatternDef);
3790 PatternDecl = PatternDef;
3791 if (PatternDef->willHaveBody())
3792 PatternDef = nullptr;
3793 }
3794
3795 // FIXME: We need to track the instantiation stack in order to know which
3796 // definitions should be visible within this instantiation.
3797 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
34
Assuming the condition is false
35
Taking false branch
3798 Function->getInstantiatedFromMemberFunction(),
3799 PatternDecl, PatternDef, TSK,
3800 /*Complain*/DefinitionRequired)) {
3801 if (DefinitionRequired)
3802 Function->setInvalidDecl();
3803 else if (TSK == TSK_ExplicitInstantiationDefinition) {
3804 // Try again at the end of the translation unit (at which point a
3805 // definition will be required).
3806 assert(!Recursive)(static_cast <bool> (!Recursive) ? void (0) : __assert_fail
("!Recursive", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3806, __extension__ __PRETTY_FUNCTION__))
;
3807 Function->setInstantiationIsPending(true);
3808 PendingInstantiations.push_back(
3809 std::make_pair(Function, PointOfInstantiation));
3810 } else if (TSK == TSK_ImplicitInstantiation) {
3811 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
3812 !getSourceManager().isInSystemHeader(PatternDecl->getLocStart())) {
3813 Diag(PointOfInstantiation, diag::warn_func_template_missing)
3814 << Function;
3815 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
3816 if (getLangOpts().CPlusPlus11)
3817 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
3818 << Function;
3819 }
3820 }
3821
3822 return;
3823 }
3824
3825 // Postpone late parsed template instantiations.
3826 if (PatternDecl->isLateTemplateParsed() &&
36
Assuming the condition is false
3827 !LateTemplateParser) {
3828 Function->setInstantiationIsPending(true);
3829 PendingInstantiations.push_back(
3830 std::make_pair(Function, PointOfInstantiation));
3831 return;
3832 }
3833
3834 // If we're performing recursive template instantiation, create our own
3835 // queue of pending implicit instantiations that we will instantiate later,
3836 // while we're still within our own instantiation context.
3837 // This has to happen before LateTemplateParser below is called, so that
3838 // it marks vtables used in late parsed templates as used.
3839 GlobalEagerInstantiationScope GlobalInstantiations(*this,
3840 /*Enabled=*/Recursive);
3841 LocalEagerInstantiationScope LocalInstantiations(*this);
3842
3843 // Call the LateTemplateParser callback if there is a need to late parse
3844 // a templated function definition.
3845 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
3846 LateTemplateParser) {
3847 // FIXME: Optimize to allow individual templates to be deserialized.
3848 if (PatternDecl->isFromASTFile())
3849 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3850
3851 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
3852 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3853, __extension__ __PRETTY_FUNCTION__))
3853 "missing LateParsedTemplate")(static_cast <bool> (LPTIter != LateParsedTemplateMap.end
() && "missing LateParsedTemplate") ? void (0) : __assert_fail
("LPTIter != LateParsedTemplateMap.end() && \"missing LateParsedTemplate\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3853, __extension__ __PRETTY_FUNCTION__))
;
3854 LateTemplateParser(OpaqueParser, *LPTIter->second);
3855 Pattern = PatternDecl->getBody(PatternDecl);
3856 }
3857
3858 // Note, we should never try to instantiate a deleted function template.
3859 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3861, __extension__ __PRETTY_FUNCTION__))
3860 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3861, __extension__ __PRETTY_FUNCTION__))
3861 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 3861, __extension__ __PRETTY_FUNCTION__))
;
3862
3863 // C++1y [temp.explicit]p10:
3864 // Except for inline functions, declarations with types deduced from their
3865 // initializer or return value, and class template specializations, other
3866 // explicit instantiation declarations have the effect of suppressing the
3867 // implicit instantiation of the entity to which they refer.
3868 if (TSK == TSK_ExplicitInstantiationDeclaration &&
37
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDeclaration
3869 !PatternDecl->isInlined() &&
3870 !PatternDecl->getReturnType()->getContainedAutoType())
3871 return;
3872
3873 if (PatternDecl->isInlined()) {
38
Assuming the condition is false
39
Taking false branch
3874 // Function, and all later redeclarations of it (from imported modules,
3875 // for instance), are now implicitly inline.
3876 for (auto *D = Function->getMostRecentDecl(); /**/;
3877 D = D->getPreviousDecl()) {
3878 D->setImplicitlyInline();
3879 if (D == Function)
3880 break;
3881 }
3882 }
3883
3884 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3885 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
40
Assuming the condition is false
41
Assuming the condition is false
42
Taking false branch
3886 return;
3887 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3888 "instantiating function definition");
3889
3890 // The instantiation is visible here, even if it was first declared in an
3891 // unimported module.
3892 Function->setVisibleDespiteOwningModule();
3893
3894 // Copy the inner loc start from the pattern.
3895 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3896
3897 EnterExpressionEvaluationContext EvalContext(
3898 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3899
3900 // Introduce a new scope where local variable instantiations will be
3901 // recorded, unless we're actually a member function within a local
3902 // class, in which case we need to merge our results with the parent
3903 // scope (of the enclosing function).
3904 bool MergeWithParentScope = false;
3905 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
43
Taking false branch
3906 MergeWithParentScope = Rec->isLocalClass();
3907
3908 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3909
3910 if (PatternDecl->isDefaulted())
44
Taking false branch
3911 SetDeclDefaulted(Function, PatternDecl->getLocation());
3912 else {
3913 MultiLevelTemplateArgumentList TemplateArgs =
3914 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
3915
3916 // Substitute into the qualifier; we can get a substitution failure here
3917 // through evil use of alias templates.
3918 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
3919 // of the) lexical context of the pattern?
3920 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
3921
3922 ActOnStartOfFunctionDef(nullptr, Function);
3923
3924 // Enter the scope of this instantiation. We don't use
3925 // PushDeclContext because we don't have a scope.
3926 Sema::ContextRAII savedContext(*this, Function);
3927
3928 if (addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
45
Assuming the condition is false
46
Taking false branch
3929 TemplateArgs))
3930 return;
3931
3932 if (PatternDecl->hasSkippedBody()) {
47
Taking true branch
3933 ActOnSkippedFunctionBody(Function);
3934 } else {
3935 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
3936 // If this is a constructor, instantiate the member initializers.
3937 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
3938 TemplateArgs);
3939
3940 // If this is an MS ABI dllexport default constructor, instantiate any
3941 // default arguments.
3942 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3943 Ctor->isDefaultConstructor()) {
3944 InstantiateDefaultCtorDefaultArgs(*this, Ctor);
3945 }
3946 }
3947
3948 // Instantiate the function body.
3949 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3950
3951 if (Body.isInvalid())
3952 Function->setInvalidDecl();
3953
3954 // FIXME: finishing the function body while in an expression evaluation
3955 // context seems wrong. Investigate more.
3956 ActOnFinishFunctionBody(Function, Body.get(),
3957 /*IsInstantiation=*/true);
3958 }
3959
3960 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3961
3962 if (auto *Listener = getASTMutationListener())
48
Assuming 'Listener' is null
49
Taking false branch
3963 Listener->FunctionDefinitionInstantiated(Function);
3964
3965 savedContext.pop();
3966 }
3967
3968 DeclGroupRef DG(Function);
3969 Consumer.HandleTopLevelDecl(DG);
3970
3971 // This class may have local implicit instantiations that need to be
3972 // instantiation within this scope.
3973 LocalInstantiations.perform();
50
Calling 'LocalEagerInstantiationScope::perform'
3974 Scope.Exit();
3975 GlobalInstantiations.perform();
3976}
3977
3978VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3979 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3980 const TemplateArgumentList &TemplateArgList,
3981 const TemplateArgumentListInfo &TemplateArgsInfo,
3982 SmallVectorImpl<TemplateArgument> &Converted,
3983 SourceLocation PointOfInstantiation, void *InsertPos,
3984 LateInstantiatedAttrVec *LateAttrs,
3985 LocalInstantiationScope *StartingScope) {
3986 if (FromVar->isInvalidDecl())
3987 return nullptr;
3988
3989 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3990 if (Inst.isInvalid())
3991 return nullptr;
3992
3993 MultiLevelTemplateArgumentList TemplateArgLists;
3994 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3995
3996 // Instantiate the first declaration of the variable template: for a partial
3997 // specialization of a static data member template, the first declaration may
3998 // or may not be the declaration in the class; if it's in the class, we want
3999 // to instantiate a member in the class (a declaration), and if it's outside,
4000 // we want to instantiate a definition.
4001 //
4002 // If we're instantiating an explicitly-specialized member template or member
4003 // partial specialization, don't do this. The member specialization completely
4004 // replaces the original declaration in this case.
4005 bool IsMemberSpec = false;
4006 if (VarTemplatePartialSpecializationDecl *PartialSpec =
4007 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
4008 IsMemberSpec = PartialSpec->isMemberSpecialization();
4009 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
4010 IsMemberSpec = FromTemplate->isMemberSpecialization();
4011 if (!IsMemberSpec)
4012 FromVar = FromVar->getFirstDecl();
4013
4014 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
4015 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
4016 MultiLevelList);
4017
4018 // TODO: Set LateAttrs and StartingScope ...
4019
4020 return cast_or_null<VarTemplateSpecializationDecl>(
4021 Instantiator.VisitVarTemplateSpecializationDecl(
4022 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
4023}
4024
4025/// \brief Instantiates a variable template specialization by completing it
4026/// with appropriate type information and initializer.
4027VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
4028 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
4029 const MultiLevelTemplateArgumentList &TemplateArgs) {
4030 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4031, __extension__ __PRETTY_FUNCTION__))
4031 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4031, __extension__ __PRETTY_FUNCTION__))
;
4032
4033 // Do substitution on the type of the declaration
4034 TypeSourceInfo *DI =
4035 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
4036 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
4037 if (!DI)
4038 return nullptr;
4039
4040 // Update the type of this variable template specialization.
4041 VarSpec->setType(DI->getType());
4042
4043 // Convert the declaration into a definition now.
4044 VarSpec->setCompleteDefinition();
4045
4046 // Instantiate the initializer.
4047 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
4048
4049 return VarSpec;
4050}
4051
4052/// BuildVariableInstantiation - Used after a new variable has been created.
4053/// Sets basic variable data and decides whether to postpone the
4054/// variable instantiation.
4055void Sema::BuildVariableInstantiation(
4056 VarDecl *NewVar, VarDecl *OldVar,
4057 const MultiLevelTemplateArgumentList &TemplateArgs,
4058 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
4059 LocalInstantiationScope *StartingScope,
4060 bool InstantiatingVarTemplate) {
4061
4062 // If we are instantiating a local extern declaration, the
4063 // instantiation belongs lexically to the containing function.
4064 // If we are instantiating a static data member defined
4065 // out-of-line, the instantiation will have the same lexical
4066 // context (which will be a namespace scope) as the template.
4067 if (OldVar->isLocalExternDecl()) {
4068 NewVar->setLocalExternDecl();
4069 NewVar->setLexicalDeclContext(Owner);
4070 } else if (OldVar->isOutOfLine())
4071 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
4072 NewVar->setTSCSpec(OldVar->getTSCSpec());
4073 NewVar->setInitStyle(OldVar->getInitStyle());
4074 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
4075 NewVar->setConstexpr(OldVar->isConstexpr());
4076 NewVar->setInitCapture(OldVar->isInitCapture());
4077 NewVar->setPreviousDeclInSameBlockScope(
4078 OldVar->isPreviousDeclInSameBlockScope());
4079 NewVar->setAccess(OldVar->getAccess());
4080
4081 if (!OldVar->isStaticDataMember()) {
4082 if (OldVar->isUsed(false))
4083 NewVar->setIsUsed();
4084 NewVar->setReferenced(OldVar->isReferenced());
4085 }
4086
4087 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
4088
4089 LookupResult Previous(
4090 *this, NewVar->getDeclName(), NewVar->getLocation(),
4091 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
4092 : Sema::LookupOrdinaryName,
4093 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
4094 : forRedeclarationInCurContext());
4095
4096 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
4097 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
4098 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
4099 // We have a previous declaration. Use that one, so we merge with the
4100 // right type.
4101 if (NamedDecl *NewPrev = FindInstantiatedDecl(
4102 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
4103 Previous.addDecl(NewPrev);
4104 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
4105 OldVar->hasLinkage())
4106 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
4107 CheckVariableDeclaration(NewVar, Previous);
4108
4109 if (!InstantiatingVarTemplate) {
4110 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
4111 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
4112 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
4113 }
4114
4115 if (!OldVar->isOutOfLine()) {
4116 if (NewVar->getDeclContext()->isFunctionOrMethod())
4117 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
4118 }
4119
4120 // Link instantiations of static data members back to the template from
4121 // which they were instantiated.
4122 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
4123 NewVar->setInstantiationOfStaticDataMember(OldVar,
4124 TSK_ImplicitInstantiation);
4125
4126 // Forward the mangling number from the template to the instantiated decl.
4127 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
4128 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
4129
4130 // Delay instantiation of the initializer for variable templates or inline
4131 // static data members until a definition of the variable is needed. We need
4132 // it right away if the type contains 'auto'.
4133 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
4134 !InstantiatingVarTemplate &&
4135 !(OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
4136 !NewVar->isThisDeclarationADefinition())) ||
4137 NewVar->getType()->isUndeducedType())
4138 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
4139
4140 // Diagnose unused local variables with dependent types, where the diagnostic
4141 // will have been deferred.
4142 if (!NewVar->isInvalidDecl() &&
4143 NewVar->getDeclContext()->isFunctionOrMethod() &&
4144 OldVar->getType()->isDependentType())
4145 DiagnoseUnusedDecl(NewVar);
4146}
4147
4148/// \brief Instantiate the initializer of a variable.
4149void Sema::InstantiateVariableInitializer(
4150 VarDecl *Var, VarDecl *OldVar,
4151 const MultiLevelTemplateArgumentList &TemplateArgs) {
4152 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4153 L->VariableDefinitionInstantiated(Var);
4154
4155 // We propagate the 'inline' flag with the initializer, because it
4156 // would otherwise imply that the variable is a definition for a
4157 // non-static data member.
4158 if (OldVar->isInlineSpecified())
4159 Var->setInlineSpecified();
4160 else if (OldVar->isInline())
4161 Var->setImplicitlyInline();
4162
4163 if (OldVar->getInit()) {
4164 EnterExpressionEvaluationContext Evaluated(
4165 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
4166
4167 // Instantiate the initializer.
4168 ExprResult Init;
4169
4170 {
4171 ContextRAII SwitchContext(*this, Var->getDeclContext());
4172 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
4173 OldVar->getInitStyle() == VarDecl::CallInit);
4174 }
4175
4176 if (!Init.isInvalid()) {
4177 Expr *InitExpr = Init.get();
4178
4179 if (Var->hasAttr<DLLImportAttr>() &&
4180 (!InitExpr ||
4181 !InitExpr->isConstantInitializer(getASTContext(), false))) {
4182 // Do not dynamically initialize dllimport variables.
4183 } else if (InitExpr) {
4184 bool DirectInit = OldVar->isDirectInit();
4185 AddInitializerToDecl(Var, InitExpr, DirectInit);
4186 } else
4187 ActOnUninitializedDecl(Var);
4188 } else {
4189 // FIXME: Not too happy about invalidating the declaration
4190 // because of a bogus initializer.
4191 Var->setInvalidDecl();
4192 }
4193 } else {
4194 if (Var->isStaticDataMember()) {
4195 if (!Var->isOutOfLine())
4196 return;
4197
4198 // If the declaration inside the class had an initializer, don't add
4199 // another one to the out-of-line definition.
4200 if (OldVar->getFirstDecl()->hasInit())
4201 return;
4202 }
4203
4204 // We'll add an initializer to a for-range declaration later.
4205 if (Var->isCXXForRangeDecl())
4206 return;
4207
4208 ActOnUninitializedDecl(Var);
4209 }
4210}
4211
4212/// \brief Instantiate the definition of the given variable from its
4213/// template.
4214///
4215/// \param PointOfInstantiation the point at which the instantiation was
4216/// required. Note that this is not precisely a "point of instantiation"
4217/// for the variable, but it's close.
4218///
4219/// \param Var the already-instantiated declaration of a templated variable.
4220///
4221/// \param Recursive if true, recursively instantiates any functions that
4222/// are required by this instantiation.
4223///
4224/// \param DefinitionRequired if true, then we are performing an explicit
4225/// instantiation where a definition of the variable is required. Complain
4226/// if there is no such definition.
4227void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
4228 VarDecl *Var, bool Recursive,
4229 bool DefinitionRequired, bool AtEndOfTU) {
4230 if (Var->isInvalidDecl())
1
Assuming the condition is false
2
Taking false branch
62
Assuming the condition is false
63
Taking false branch
4231 return;
4232
4233 VarTemplateSpecializationDecl *VarSpec =
4234 dyn_cast<VarTemplateSpecializationDecl>(Var);
4235 VarDecl *PatternDecl = nullptr, *Def = nullptr;
4236 MultiLevelTemplateArgumentList TemplateArgs =
4237 getTemplateInstantiationArgs(Var);
4238
4239 if (VarSpec) {
3
Assuming 'VarSpec' is non-null
4
Taking true branch
64
Assuming 'VarSpec' is non-null
65
Taking true branch
4240 // If this is a variable template specialization, make sure that it is
4241 // non-dependent, then find its instantiation pattern.
4242 bool InstantiationDependent = false;
4243 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4246, __extension__ __PRETTY_FUNCTION__))
4244 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4246, __extension__ __PRETTY_FUNCTION__))
4245 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4246, __extension__ __PRETTY_FUNCTION__))
4246 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4246, __extension__ __PRETTY_FUNCTION__))
;
4247 (void)InstantiationDependent;
4248
4249 // Find the variable initialization that we'll be substituting. If the
4250 // pattern was instantiated from a member template, look back further to
4251 // find the real pattern.
4252 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4253, __extension__ __PRETTY_FUNCTION__))
4253 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4253, __extension__ __PRETTY_FUNCTION__))
;
4254 llvm::PointerUnion<VarTemplateDecl *,
4255 VarTemplatePartialSpecializationDecl *> PatternPtr =
4256 VarSpec->getSpecializedTemplateOrPartial();
4257 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
5
Taking true branch
66
Taking false branch
4258 VarTemplatePartialSpecializationDecl *Tmpl =
4259 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
4260 while (VarTemplatePartialSpecializationDecl *From =
6
Loop condition is false. Execution continues on line 4267
4261 Tmpl->getInstantiatedFromMember()) {
4262 if (Tmpl->isMemberSpecialization())
4263 break;
4264
4265 Tmpl = From;
4266 }
4267 PatternDecl = Tmpl;
4268 } else {
4269 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
4270 while (VarTemplateDecl *From =
67
Loop condition is false. Execution continues on line 4277
4271 Tmpl->getInstantiatedFromMemberTemplate()) {
4272 if (Tmpl->isMemberSpecialization())
4273 break;
4274
4275 Tmpl = From;
4276 }
4277 PatternDecl = Tmpl->getTemplatedDecl();
4278 }
4279
4280 // If this is a static data member template, there might be an
4281 // uninstantiated initializer on the declaration. If so, instantiate
4282 // it now.
4283 //
4284 // FIXME: This largely duplicates what we would do below. The difference
4285 // is that along this path we may instantiate an initializer from an
4286 // in-class declaration of the template and instantiate the definition
4287 // from a separate out-of-class definition.
4288 if (PatternDecl->isStaticDataMember() &&
68
Assuming the condition is false
4289 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
4290 !Var->hasInit()) {
4291 // FIXME: Factor out the duplicated instantiation context setup/tear down
4292 // code here.
4293 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4294 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4295 return;
4296 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4297 "instantiating variable initializer");
4298
4299 // The instantiation is visible here, even if it was first declared in an
4300 // unimported module.
4301 Var->setVisibleDespiteOwningModule();
4302
4303 // If we're performing recursive template instantiation, create our own
4304 // queue of pending implicit instantiations that we will instantiate
4305 // later, while we're still within our own instantiation context.
4306 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4307 /*Enabled=*/Recursive);
4308 LocalInstantiationScope Local(*this);
4309 LocalEagerInstantiationScope LocalInstantiations(*this);
4310
4311 // Enter the scope of this instantiation. We don't use
4312 // PushDeclContext because we don't have a scope.
4313 ContextRAII PreviousContext(*this, Var->getDeclContext());
4314 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
4315 PreviousContext.pop();
4316
4317 // This variable may have local implicit instantiations that need to be
4318 // instantiated within this scope.
4319 LocalInstantiations.perform();
4320 Local.Exit();
4321 GlobalInstantiations.perform();
4322 }
4323
4324 // Find actual definition
4325 Def = PatternDecl->getDefinition(getASTContext());
69
Value assigned to 'Def'
4326 } else {
4327 // If this is a static data member, find its out-of-line definition.
4328 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4328, __extension__ __PRETTY_FUNCTION__))
;
4329 PatternDecl = Var->getInstantiatedFromStaticDataMember();
4330
4331 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4331, __extension__ __PRETTY_FUNCTION__))
;
4332 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4332, __extension__ __PRETTY_FUNCTION__))
;
4333 Def = PatternDecl->getDefinition();
4334 }
4335
4336 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
4337
4338 // If we don't have a definition of the variable template, we won't perform
4339 // any instantiation. Rather, we rely on the user to instantiate this
4340 // definition (or provide a specialization for it) in another translation
4341 // unit.
4342 if (!Def && !DefinitionRequired) {
7
Assuming 'Def' is non-null
70
Assuming 'Def' is null
71
Assuming pointer value is null
72
Taking true branch
4343 if (TSK == TSK_ExplicitInstantiationDefinition) {
73
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDefinition
74
Taking false branch
4344 PendingInstantiations.push_back(
4345 std::make_pair(Var, PointOfInstantiation));
4346 } else if (TSK == TSK_ImplicitInstantiation) {
75
Assuming 'TSK' is not equal to TSK_ImplicitInstantiation
76
Taking false branch
4347 // Warn about missing definition at the end of translation unit.
4348 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4349 !getSourceManager().isInSystemHeader(PatternDecl->getLocStart())) {
4350 Diag(PointOfInstantiation, diag::warn_var_template_missing)
4351 << Var;
4352 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4353 if (getLangOpts().CPlusPlus11)
4354 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
4355 }
4356 return;
4357 }
4358
4359 }
4360
4361 // FIXME: We need to track the instantiation stack in order to know which
4362 // definitions should be visible within this instantiation.
4363 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
4364 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
8
Assuming the condition is false
9
Taking false branch
77
Assuming the condition is false
78
Taking false branch
4365 /*InstantiatedFromMember*/false,
4366 PatternDecl, Def, TSK,
4367 /*Complain*/DefinitionRequired))
4368 return;
4369
4370
4371 // Never instantiate an explicit specialization.
4372 if (TSK == TSK_ExplicitSpecialization)
10
Assuming 'TSK' is not equal to TSK_ExplicitSpecialization
11
Taking false branch
79
Assuming 'TSK' is not equal to TSK_ExplicitSpecialization
80
Taking false branch
4373 return;
4374
4375 // C++11 [temp.explicit]p10:
4376 // Except for inline functions, const variables of literal types, variables
4377 // of reference types, [...] explicit instantiation declarations
4378 // have the effect of suppressing the implicit instantiation of the entity
4379 // to which they refer.
4380 if (TSK == TSK_ExplicitInstantiationDeclaration &&
12
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDeclaration
81
Assuming 'TSK' is not equal to TSK_ExplicitInstantiationDeclaration
4381 !Var->isUsableInConstantExpressions(getASTContext()))
4382 return;
4383
4384 // Make sure to pass the instantiated variable to the consumer at the end.
4385 struct PassToConsumerRAII {
4386 ASTConsumer &Consumer;
4387 VarDecl *Var;
4388
4389 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
4390 : Consumer(Consumer), Var(Var) { }
4391
4392 ~PassToConsumerRAII() {
4393 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
4394 }
4395 } PassToConsumerRAII(Consumer, Var);
4396
4397 // If we already have a definition, we're done.
4398 if (VarDecl *Def = Var->getDefinition()) {
13
Assuming 'Def' is null
14
Taking false branch
82
Assuming 'Def' is null
83
Taking false branch
4399 // We may be explicitly instantiating something we've already implicitly
4400 // instantiated.
4401 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
4402 PointOfInstantiation);
4403 return;
4404 }
4405
4406 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
4407 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
15
Assuming the condition is false
16
Assuming the condition is false
17
Taking false branch
84
Assuming the condition is false
85
Assuming the condition is false
86
Taking false branch
4408 return;
4409 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4410 "instantiating variable definition");
4411
4412 // If we're performing recursive template instantiation, create our own
4413 // queue of pending implicit instantiations that we will instantiate later,
4414 // while we're still within our own instantiation context.
4415 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4416 /*Enabled=*/Recursive);
4417
4418 // Enter the scope of this instantiation. We don't use
4419 // PushDeclContext because we don't have a scope.
4420 ContextRAII PreviousContext(*this, Var->getDeclContext());
4421 LocalInstantiationScope Local(*this);
4422
4423 LocalEagerInstantiationScope LocalInstantiations(*this);
4424
4425 VarDecl *OldVar = Var;
4426 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
87
Called C++ object pointer is null
4427 // We're instantiating an inline static data member whose definition was
4428 // provided inside the class.
4429 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4430 } else if (!VarSpec) {
18
Taking false branch
4431 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
4432 TemplateArgs));
4433 } else if (Var->isStaticDataMember() &&
4434 Var->getLexicalDeclContext()->isRecord()) {
4435 // We need to instantiate the definition of a static data member template,
4436 // and all we have is the in-class declaration of it. Instantiate a separate
4437 // declaration of the definition.
4438 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
4439 TemplateArgs);
4440 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
4441 VarSpec->getSpecializedTemplate(), Def, nullptr,
4442 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
4443 if (Var) {
4444 llvm::PointerUnion<VarTemplateDecl *,
4445 VarTemplatePartialSpecializationDecl *> PatternPtr =
4446 VarSpec->getSpecializedTemplateOrPartial();
4447 if (VarTemplatePartialSpecializationDecl *Partial =
4448 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
4449 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
4450 Partial, &VarSpec->getTemplateInstantiationArgs());
4451
4452 // Merge the definition with the declaration.
4453 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
4454 LookupOrdinaryName, forRedeclarationInCurContext());
4455 R.addDecl(OldVar);
4456 MergeVarDecl(Var, R);
4457
4458 // Attach the initializer.
4459 InstantiateVariableInitializer(Var, Def, TemplateArgs);
4460 }
4461 } else
4462 // Complete the existing variable's definition with an appropriately
4463 // substituted type and initializer.
4464 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
4465
4466 PreviousContext.pop();
4467
4468 if (Var) {
19
Taking true branch
4469 PassToConsumerRAII.Var = Var;
4470 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
4471 OldVar->getPointOfInstantiation());
4472 }
4473
4474 // This variable may have local implicit instantiations that need to be
4475 // instantiated within this scope.
4476 LocalInstantiations.perform();
20
Calling 'LocalEagerInstantiationScope::perform'
4477 Local.Exit();
4478 GlobalInstantiations.perform();
4479}
4480
4481void
4482Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4483 const CXXConstructorDecl *Tmpl,
4484 const MultiLevelTemplateArgumentList &TemplateArgs) {
4485
4486 SmallVector<CXXCtorInitializer*, 4> NewInits;
4487 bool AnyErrors = Tmpl->isInvalidDecl();
4488
4489 // Instantiate all the initializers.
4490 for (const auto *Init : Tmpl->inits()) {
4491 // Only instantiate written initializers, let Sema re-construct implicit
4492 // ones.
4493 if (!Init->isWritten())
4494 continue;
4495
4496 SourceLocation EllipsisLoc;
4497
4498 if (Init->isPackExpansion()) {
4499 // This is a pack expansion. We should expand it now.
4500 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
4501 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
4502 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
4503 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
4504 bool ShouldExpand = false;
4505 bool RetainExpansion = false;
4506 Optional<unsigned> NumExpansions;
4507 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
4508 BaseTL.getSourceRange(),
4509 Unexpanded,
4510 TemplateArgs, ShouldExpand,
4511 RetainExpansion,
4512 NumExpansions)) {
4513 AnyErrors = true;
4514 New->setInvalidDecl();
4515 continue;
4516 }
4517 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4517, __extension__ __PRETTY_FUNCTION__))
;
4518
4519 // Loop over all of the arguments in the argument pack(s),
4520 for (unsigned I = 0; I != *NumExpansions; ++I) {
4521 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4522
4523 // Instantiate the initializer.
4524 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4525 /*CXXDirectInit=*/true);
4526 if (TempInit.isInvalid()) {
4527 AnyErrors = true;
4528 break;
4529 }
4530
4531 // Instantiate the base type.
4532 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
4533 TemplateArgs,
4534 Init->getSourceLocation(),
4535 New->getDeclName());
4536 if (!BaseTInfo) {
4537 AnyErrors = true;
4538 break;
4539 }
4540
4541 // Build the initializer.
4542 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
4543 BaseTInfo, TempInit.get(),
4544 New->getParent(),
4545 SourceLocation());
4546 if (NewInit.isInvalid()) {
4547 AnyErrors = true;
4548 break;
4549 }
4550
4551 NewInits.push_back(NewInit.get());
4552 }
4553
4554 continue;
4555 }
4556
4557 // Instantiate the initializer.
4558 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4559 /*CXXDirectInit=*/true);
4560 if (TempInit.isInvalid()) {
4561 AnyErrors = true;
4562 continue;
4563 }
4564
4565 MemInitResult NewInit;
4566 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4567 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4568 TemplateArgs,
4569 Init->getSourceLocation(),
4570 New->getDeclName());
4571 if (!TInfo) {
4572 AnyErrors = true;
4573 New->setInvalidDecl();
4574 continue;
4575 }
4576
4577 if (Init->isBaseInitializer())
4578 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
4579 New->getParent(), EllipsisLoc);
4580 else
4581 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
4582 cast<CXXRecordDecl>(CurContext->getParent()));
4583 } else if (Init->isMemberInitializer()) {
4584 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
4585 Init->getMemberLocation(),
4586 Init->getMember(),
4587 TemplateArgs));
4588 if (!Member) {
4589 AnyErrors = true;
4590 New->setInvalidDecl();
4591 continue;
4592 }
4593
4594 NewInit = BuildMemberInitializer(Member, TempInit.get(),
4595 Init->getSourceLocation());
4596 } else if (Init->isIndirectMemberInitializer()) {
4597 IndirectFieldDecl *IndirectMember =
4598 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
4599 Init->getMemberLocation(),
4600 Init->getIndirectMember(), TemplateArgs));
4601
4602 if (!IndirectMember) {
4603 AnyErrors = true;
4604 New->setInvalidDecl();
4605 continue;
4606 }
4607
4608 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
4609 Init->getSourceLocation());
4610 }
4611
4612 if (NewInit.isInvalid()) {
4613 AnyErrors = true;
4614 New->setInvalidDecl();
4615 } else {
4616 NewInits.push_back(NewInit.get());
4617 }
4618 }
4619
4620 // Assign all the initializers to the new constructor.
4621 ActOnMemInitializers(New,
4622 /*FIXME: ColonLoc */
4623 SourceLocation(),
4624 NewInits,
4625 AnyErrors);
4626}
4627
4628// TODO: this could be templated if the various decl types used the
4629// same method name.
4630static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4631 ClassTemplateDecl *Instance) {
4632 Pattern = Pattern->getCanonicalDecl();
4633
4634 do {
4635 Instance = Instance->getCanonicalDecl();
4636 if (Pattern == Instance) return true;
4637 Instance = Instance->getInstantiatedFromMemberTemplate();
4638 } while (Instance);
4639
4640 return false;
4641}
4642
4643static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4644 FunctionTemplateDecl *Instance) {
4645 Pattern = Pattern->getCanonicalDecl();
4646
4647 do {
4648 Instance = Instance->getCanonicalDecl();
4649 if (Pattern == Instance) return true;
4650 Instance = Instance->getInstantiatedFromMemberTemplate();
4651 } while (Instance);
4652
4653 return false;
4654}
4655
4656static bool
4657isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4658 ClassTemplatePartialSpecializationDecl *Instance) {
4659 Pattern
4660 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4661 do {
4662 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4663 Instance->getCanonicalDecl());
4664 if (Pattern == Instance)
4665 return true;
4666 Instance = Instance->getInstantiatedFromMember();
4667 } while (Instance);
4668
4669 return false;
4670}
4671
4672static bool isInstantiationOf(CXXRecordDecl *Pattern,
4673 CXXRecordDecl *Instance) {
4674 Pattern = Pattern->getCanonicalDecl();
4675
4676 do {
4677 Instance = Instance->getCanonicalDecl();
4678 if (Pattern == Instance) return true;
4679 Instance = Instance->getInstantiatedFromMemberClass();
4680 } while (Instance);
4681
4682 return false;
4683}
4684
4685static bool isInstantiationOf(FunctionDecl *Pattern,
4686 FunctionDecl *Instance) {
4687 Pattern = Pattern->getCanonicalDecl();
4688
4689 do {
4690 Instance = Instance->getCanonicalDecl();
4691 if (Pattern == Instance) return true;
4692 Instance = Instance->getInstantiatedFromMemberFunction();
4693 } while (Instance);
4694
4695 return false;
4696}
4697
4698static bool isInstantiationOf(EnumDecl *Pattern,
4699 EnumDecl *Instance) {
4700 Pattern = Pattern->getCanonicalDecl();
4701
4702 do {
4703 Instance = Instance->getCanonicalDecl();
4704 if (Pattern == Instance) return true;
4705 Instance = Instance->getInstantiatedFromMemberEnum();
4706 } while (Instance);
4707
4708 return false;
4709}
4710
4711static bool isInstantiationOf(UsingShadowDecl *Pattern,
4712 UsingShadowDecl *Instance,
4713 ASTContext &C) {
4714 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
4715 Pattern);
4716}
4717
4718static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
4719 ASTContext &C) {
4720 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
4721}
4722
4723template<typename T>
4724static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
4725 ASTContext &Ctx) {
4726 // An unresolved using declaration can instantiate to an unresolved using
4727 // declaration, or to a using declaration or a using declaration pack.
4728 //
4729 // Multiple declarations can claim to be instantiated from an unresolved
4730 // using declaration if it's a pack expansion. We want the UsingPackDecl
4731 // in that case, not the individual UsingDecls within the pack.
4732 bool OtherIsPackExpansion;
4733 NamedDecl *OtherFrom;
4734 if (auto *OtherUUD = dyn_cast<T>(Other)) {
4735 OtherIsPackExpansion = OtherUUD->isPackExpansion();
4736 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
4737 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
4738 OtherIsPackExpansion = true;
4739 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
4740 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
4741 OtherIsPackExpansion = false;
4742 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
4743 } else {
4744 return false;
4745 }
4746 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
4747 declaresSameEntity(OtherFrom, Pattern);
4748}
4749
4750static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4751 VarDecl *Instance) {
4752 assert(Instance->isStaticDataMember())(static_cast <bool> (Instance->isStaticDataMember())
? void (0) : __assert_fail ("Instance->isStaticDataMember()"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4752, __extension__ __PRETTY_FUNCTION__))
;
4753
4754 Pattern = Pattern->getCanonicalDecl();
4755
4756 do {
4757 Instance = Instance->getCanonicalDecl();
4758 if (Pattern == Instance) return true;
4759 Instance = Instance->getInstantiatedFromStaticDataMember();
4760 } while (Instance);
4761
4762 return false;
4763}
4764
4765// Other is the prospective instantiation
4766// D is the prospective pattern
4767static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
4768 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
4769 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
4770
4771 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
4772 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
4773
4774 if (D->getKind() != Other->getKind())
4775 return false;
4776
4777 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
4778 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
4779
4780 if (auto *Function = dyn_cast<FunctionDecl>(Other))
4781 return isInstantiationOf(cast<FunctionDecl>(D), Function);
4782
4783 if (auto *Enum = dyn_cast<EnumDecl>(Other))
4784 return isInstantiationOf(cast<EnumDecl>(D), Enum);
4785
4786 if (auto *Var = dyn_cast<VarDecl>(Other))
4787 if (Var->isStaticDataMember())
4788 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4789
4790 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
4791 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
4792
4793 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4794 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4795
4796 if (auto *PartialSpec =
4797 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4798 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4799 PartialSpec);
4800
4801 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
4802 if (!Field->getDeclName()) {
4803 // This is an unnamed field.
4804 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
4805 cast<FieldDecl>(D));
4806 }
4807 }
4808
4809 if (auto *Using = dyn_cast<UsingDecl>(Other))
4810 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4811
4812 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
4813 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4814
4815 return D->getDeclName() &&
4816 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4817}
4818
4819template<typename ForwardIterator>
4820static NamedDecl *findInstantiationOf(ASTContext &Ctx,
4821 NamedDecl *D,
4822 ForwardIterator first,
4823 ForwardIterator last) {
4824 for (; first != last; ++first)
4825 if (isInstantiationOf(Ctx, D, *first))
4826 return cast<NamedDecl>(*first);
4827
4828 return nullptr;
4829}
4830
4831/// \brief Finds the instantiation of the given declaration context
4832/// within the current instantiation.
4833///
4834/// \returns NULL if there was an error
4835DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
4836 const MultiLevelTemplateArgumentList &TemplateArgs) {
4837 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
4838 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
4839 return cast_or_null<DeclContext>(ID);
4840 } else return DC;
4841}
4842
4843/// \brief Find the instantiation of the given declaration within the
4844/// current instantiation.
4845///
4846/// This routine is intended to be used when \p D is a declaration
4847/// referenced from within a template, that needs to mapped into the
4848/// corresponding declaration within an instantiation. For example,
4849/// given:
4850///
4851/// \code
4852/// template<typename T>
4853/// struct X {
4854/// enum Kind {
4855/// KnownValue = sizeof(T)
4856/// };
4857///
4858/// bool getKind() const { return KnownValue; }
4859/// };
4860///
4861/// template struct X<int>;
4862/// \endcode
4863///
4864/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4865/// \p EnumConstantDecl for \p KnownValue (which refers to
4866/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4867/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4868/// this mapping from within the instantiation of <tt>X<int></tt>.
4869NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
4870 const MultiLevelTemplateArgumentList &TemplateArgs,
4871 bool FindingInstantiatedContext) {
4872 DeclContext *ParentDC = D->getDeclContext();
4873 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4874 // parameters (p below) can have their ParentDC set to the translation-unit
4875 // - thus we can not consistently check if the ParentDC of such a parameter
4876 // is Dependent or/and a FunctionOrMethod.
4877 // For e.g. this code, during Template argument deduction tries to
4878 // find an instantiated decl for (T y) when the ParentDC for y is
4879 // the translation unit.
4880 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4881 // float baz(float(*)()) { return 0.0; }
4882 // Foo(baz);
4883 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4884 // it gets here, always has a FunctionOrMethod as its ParentDC??
4885 // For now:
4886 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4887 // whose type is not instantiation dependent, do nothing to the decl
4888 // - otherwise find its instantiated decl.
4889 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4890 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4891 return D;
4892 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
4893 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
4894 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4895 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
4896 // D is a local of some kind. Look into the map of local
4897 // declarations to their instantiations.
4898 if (CurrentInstantiationScope) {
4899 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
4900 if (Decl *FD = Found->dyn_cast<Decl *>())
4901 return cast<NamedDecl>(FD);
4902
4903 int PackIdx = ArgumentPackSubstitutionIndex;
4904 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4905, __extension__ __PRETTY_FUNCTION__))
4905 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4905, __extension__ __PRETTY_FUNCTION__))
;
4906 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4907 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4908 }
4909 }
4910
4911 // If we're performing a partial substitution during template argument
4912 // deduction, we may not have values for template parameters yet. They
4913 // just map to themselves.
4914 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4915 isa<TemplateTemplateParmDecl>(D))
4916 return D;
4917
4918 if (D->isInvalidDecl())
4919 return nullptr;
4920
4921 // Normally this function only searches for already instantiated declaration
4922 // however we have to make an exclusion for local types used before
4923 // definition as in the code:
4924 //
4925 // template<typename T> void f1() {
4926 // void g1(struct x1);
4927 // struct x1 {};
4928 // }
4929 //
4930 // In this case instantiation of the type of 'g1' requires definition of
4931 // 'x1', which is defined later. Error recovery may produce an enum used
4932 // before definition. In these cases we need to instantiate relevant
4933 // declarations here.
4934 bool NeedInstantiate = false;
4935 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4936 NeedInstantiate = RD->isLocalClass();
4937 else
4938 NeedInstantiate = isa<EnumDecl>(D);
4939 if (NeedInstantiate) {
4940 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4941 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4942 return cast<TypeDecl>(Inst);
4943 }
4944
4945 // If we didn't find the decl, then we must have a label decl that hasn't
4946 // been found yet. Lazily instantiate it and return it now.
4947 assert(isa<LabelDecl>(D))(static_cast <bool> (isa<LabelDecl>(D)) ? void (0
) : __assert_fail ("isa<LabelDecl>(D)", "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4947, __extension__ __PRETTY_FUNCTION__))
;
4948
4949 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4950 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4950, __extension__ __PRETTY_FUNCTION__))
;
4951
4952 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4953 return cast<LabelDecl>(Inst);
4954 }
4955
4956 // For variable template specializations, update those that are still
4957 // type-dependent.
4958 if (VarTemplateSpecializationDecl *VarSpec =
4959 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4960 bool InstantiationDependent = false;
4961 const TemplateArgumentListInfo &VarTemplateArgs =
4962 VarSpec->getTemplateArgsInfo();
4963 if (TemplateSpecializationType::anyDependentTemplateArguments(
4964 VarTemplateArgs, InstantiationDependent))
4965 D = cast<NamedDecl>(
4966 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4967 return D;
4968 }
4969
4970 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4971 if (!Record->isDependentContext())
4972 return D;
4973
4974 // Determine whether this record is the "templated" declaration describing
4975 // a class template or class template partial specialization.
4976 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
4977 if (ClassTemplate)
4978 ClassTemplate = ClassTemplate->getCanonicalDecl();
4979 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4980 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4981 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
4982
4983 // Walk the current context to find either the record or an instantiation of
4984 // it.
4985 DeclContext *DC = CurContext;
4986 while (!DC->isFileContext()) {
4987 // If we're performing substitution while we're inside the template
4988 // definition, we'll find our own context. We're done.
4989 if (DC->Equals(Record))
4990 return Record;
4991
4992 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4993 // Check whether we're in the process of instantiating a class template
4994 // specialization of the template we're mapping.
4995 if (ClassTemplateSpecializationDecl *InstSpec
4996 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4997 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4998 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4999 return InstRecord;
5000 }
5001
5002 // Check whether we're in the process of instantiating a member class.
5003 if (isInstantiationOf(Record, InstRecord))
5004 return InstRecord;
5005 }
5006
5007 // Move to the outer template scope.
5008 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
5009 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
5010 DC = FD->getLexicalDeclContext();
5011 continue;
5012 }
5013 // An implicit deduction guide acts as if it's within the class template
5014 // specialization described by its name and first N template params.
5015 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
5016 if (Guide && Guide->isImplicit()) {
5017 TemplateDecl *TD = Guide->getDeducedTemplate();
5018 // Convert the arguments to an "as-written" list.
5019 TemplateArgumentListInfo Args(Loc, Loc);
5020 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
5021 TD->getTemplateParameters()->size())) {
5022 ArrayRef<TemplateArgument> Unpacked(Arg);
5023 if (Arg.getKind() == TemplateArgument::Pack)
5024 Unpacked = Arg.pack_elements();
5025 for (TemplateArgument UnpackedArg : Unpacked)
5026 Args.addArgument(
5027 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
5028 }
5029 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
5030 if (T.isNull())
5031 return nullptr;
5032 auto *SubstRecord = T->getAsCXXRecordDecl();
5033 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5033, __extension__ __PRETTY_FUNCTION__))
;
5034 // Check that this template-id names the primary template and not a
5035 // partial or explicit specialization. (In the latter cases, it's
5036 // meaningless to attempt to find an instantiation of D within the
5037 // specialization.)
5038 // FIXME: The standard doesn't say what should happen here.
5039 if (FindingInstantiatedContext &&
5040 usesPartialOrExplicitSpecialization(
5041 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
5042 Diag(Loc, diag::err_specialization_not_primary_template)
5043 << T << (SubstRecord->getTemplateSpecializationKind() ==
5044 TSK_ExplicitSpecialization);
5045 return nullptr;
5046 }
5047 DC = SubstRecord;
5048 continue;
5049 }
5050 }
5051
5052 DC = DC->getParent();
5053 }
5054
5055 // Fall through to deal with other dependent record types (e.g.,
5056 // anonymous unions in class templates).
5057 }
5058
5059 if (!ParentDC->isDependentContext())
5060 return D;
5061
5062 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
5063 if (!ParentDC)
5064 return nullptr;
5065
5066 if (ParentDC != D->getDeclContext()) {
5067 // We performed some kind of instantiation in the parent context,
5068 // so now we need to look into the instantiated parent context to
5069 // find the instantiation of the declaration D.
5070
5071 // If our context used to be dependent, we may need to instantiate
5072 // it before performing lookup into that context.
5073 bool IsBeingInstantiated = false;
5074 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
5075 if (!Spec->isDependentContext()) {
5076 QualType T = Context.getTypeDeclType(Spec);
5077 const RecordType *Tag = T->getAs<RecordType>();
5078 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5078, __extension__ __PRETTY_FUNCTION__))
;
5079 if (Tag->isBeingDefined())
5080 IsBeingInstantiated = true;
5081 if (!Tag->isBeingDefined() &&
5082 RequireCompleteType(Loc, T, diag::err_incomplete_type))
5083 return nullptr;
5084
5085 ParentDC = Tag->getDecl();
5086 }
5087 }
5088
5089 NamedDecl *Result = nullptr;
5090 // FIXME: If the name is a dependent name, this lookup won't necessarily
5091 // find it. Does that ever matter?
5092 if (auto Name = D->getDeclName()) {
5093 DeclarationNameInfo NameInfo(Name, D->getLocation());
5094 Name = SubstDeclarationNameInfo(NameInfo, TemplateArgs).getName();
5095 if (!Name)
5096 return nullptr;
5097 DeclContext::lookup_result Found = ParentDC->lookup(Name);
5098 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
5099 } else {
5100 // Since we don't have a name for the entity we're looking for,
5101 // our only option is to walk through all of the declarations to
5102 // find that name. This will occur in a few cases:
5103 //
5104 // - anonymous struct/union within a template
5105 // - unnamed class/struct/union/enum within a template
5106 //
5107 // FIXME: Find a better way to find these instantiations!
5108 Result = findInstantiationOf(Context, D,
5109 ParentDC->decls_begin(),
5110 ParentDC->decls_end());
5111 }
5112
5113 if (!Result) {
5114 if (isa<UsingShadowDecl>(D)) {
5115 // UsingShadowDecls can instantiate to nothing because of using hiding.
5116 } else if (Diags.hasErrorOccurred()) {
5117 // We've already complained about something, so most likely this
5118 // declaration failed to instantiate. There's no point in complaining
5119 // further, since this is normal in invalid code.
5120 } else if (IsBeingInstantiated) {
5121 // The class in which this member exists is currently being
5122 // instantiated, and we haven't gotten around to instantiating this
5123 // member yet. This can happen when the code uses forward declarations
5124 // of member classes, and introduces ordering dependencies via
5125 // template instantiation.
5126 Diag(Loc, diag::err_member_not_yet_instantiated)
5127 << D->getDeclName()
5128 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
5129 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
5130 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
5131 // This enumeration constant was found when the template was defined,
5132 // but can't be found in the instantiation. This can happen if an
5133 // unscoped enumeration member is explicitly specialized.
5134 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
5135 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
5136 TemplateArgs));
5137 assert(Spec->getTemplateSpecializationKind() ==(static_cast <bool> (Spec->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization) ? void (0) : __assert_fail (
"Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5138, __extension__ __PRETTY_FUNCTION__))
5138 TSK_ExplicitSpecialization)(static_cast <bool> (Spec->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization) ? void (0) : __assert_fail (
"Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5138, __extension__ __PRETTY_FUNCTION__))
;
5139 Diag(Loc, diag::err_enumerator_does_not_exist)
5140 << D->getDeclName()
5141 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
5142 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
5143 << Context.getTypeDeclType(Spec);
5144 } else {
5145 // We should have found something, but didn't.
5146 llvm_unreachable("Unable to find instantiation of declaration!")::llvm::llvm_unreachable_internal("Unable to find instantiation of declaration!"
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5146)
;
5147 }
5148 }
5149
5150 D = Result;
5151 }
5152
5153 return D;
5154}
5155
5156/// \brief Performs template instantiation for all implicit template
5157/// instantiations we have seen until this point.
5158void Sema::PerformPendingInstantiations(bool LocalOnly) {
5159 while (!PendingLocalImplicitInstantiations.empty() ||
22
Assuming the condition is true
52
Assuming the condition is true
5160 (!LocalOnly && !PendingInstantiations.empty())) {
5161 PendingImplicitInstantiation Inst;
5162
5163 if (PendingLocalImplicitInstantiations.empty()) {
23
Assuming the condition is false
24
Taking false branch
53
Assuming the condition is false
54
Taking false branch
5164 Inst = PendingInstantiations.front();
5165 PendingInstantiations.pop_front();
5166 } else {
5167 Inst = PendingLocalImplicitInstantiations.front();
5168 PendingLocalImplicitInstantiations.pop_front();
5169 }
5170
5171 // Instantiate function definitions
5172 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
25
Assuming 'Function' is non-null
26
Taking true branch
55
Taking false branch
5173 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
27
Assuming the condition is false
5174 TSK_ExplicitInstantiationDefinition;
5175 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
28
Calling 'Sema::InstantiateFunctionDefinition'
5176 DefinitionRequired, true);
5177 if (Function->isDefined())
5178 Function->setInstantiationIsPending(false);
5179 continue;
5180 }
5181
5182 // Instantiate variable definitions
5183 VarDecl *Var = cast<VarDecl>(Inst.first);
5184
5185 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5188, __extension__ __PRETTY_FUNCTION__))
5186 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5188, __extension__ __PRETTY_FUNCTION__))
5187 "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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5188, __extension__ __PRETTY_FUNCTION__))
5188 " 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~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5188, __extension__ __PRETTY_FUNCTION__))
;
5189
5190 // Don't try to instantiate declarations if the most recent redeclaration
5191 // is invalid.
5192 if (Var->getMostRecentDecl()->isInvalidDecl())
56
Assuming the condition is false
57
Taking false branch
5193 continue;
5194
5195 // Check if the most recent declaration has changed the specialization kind
5196 // and removed the need for implicit instantiation.
5197 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
58
Control jumps to 'case TSK_ImplicitInstantiation:' at line 5209
5198 case TSK_Undeclared:
5199 llvm_unreachable("Cannot instantitiate an undeclared specialization.")::llvm::llvm_unreachable_internal("Cannot instantitiate an undeclared specialization."
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 5199)
;
5200 case TSK_ExplicitInstantiationDeclaration:
5201 case TSK_ExplicitSpecialization:
5202 continue; // No longer need to instantiate this type.
5203 case TSK_ExplicitInstantiationDefinition:
5204 // We only need an instantiation if the pending instantiation *is* the
5205 // explicit instantiation.
5206 if (Var != Var->getMostRecentDecl())
5207 continue;
5208 break;
5209 case TSK_ImplicitInstantiation:
5210 break;
59
Execution continues on line 5213
5211 }
5212
5213 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
5214 "instantiating variable definition");
5215 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
60
Assuming the condition is false
5216 TSK_ExplicitInstantiationDefinition;
5217
5218 // Instantiate static data member definitions or variable template
5219 // specializations.
5220 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
61
Calling 'Sema::InstantiateVariableDefinition'
5221 DefinitionRequired, true);
5222 }
5223}
5224
5225void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
5226 const MultiLevelTemplateArgumentList &TemplateArgs) {
5227 for (auto DD : Pattern->ddiags()) {
5228 switch (DD->getKind()) {
5229 case DependentDiagnostic::Access:
5230 HandleDependentAccessCheck(*DD, TemplateArgs);
5231 break;
5232 }
5233 }
5234}

/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- 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// This file defines the Sema class, which performs semantic analysis and
11// builds ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_SEMA_SEMA_H
16#define LLVM_CLANG_SEMA_SEMA_H
17
18#include "clang/AST/Attr.h"
19#include "clang/AST/Availability.h"
20#include "clang/AST/DeclarationName.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/ExternalASTSource.h"
25#include "clang/AST/LocInfoType.h"
26#include "clang/AST/MangleNumberingContext.h"
27#include "clang/AST/NSAPI.h"
28#include "clang/AST/PrettyPrinter.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/TypeLoc.h"
31#include "clang/AST/TypeOrdering.h"
32#include "clang/Basic/ExpressionTraits.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/OpenMPKinds.h"
36#include "clang/Basic/PragmaKinds.h"
37#include "clang/Basic/Specifiers.h"
38#include "clang/Basic/TemplateKinds.h"
39#include "clang/Basic/TypeTraits.h"
40#include "clang/Sema/AnalysisBasedWarnings.h"
41#include "clang/Sema/CleanupInfo.h"
42#include "clang/Sema/DeclSpec.h"
43#include "clang/Sema/ExternalSemaSource.h"
44#include "clang/Sema/IdentifierResolver.h"
45#include "clang/Sema/ObjCMethodList.h"
46#include "clang/Sema/Ownership.h"
47#include "clang/Sema/Scope.h"
48#include "clang/Sema/ScopeInfo.h"
49#include "clang/Sema/TypoCorrection.h"
50#include "clang/Sema/Weak.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/Optional.h"
53#include "llvm/ADT/SetVector.h"
54#include "llvm/ADT/SmallPtrSet.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/TinyPtrVector.h"
57#include <deque>
58#include <memory>
59#include <string>
60#include <vector>
61
62namespace llvm {
63 class APSInt;
64 template <typename ValueT> struct DenseMapInfo;
65 template <typename ValueT, typename ValueInfoT> class DenseSet;
66 class SmallBitVector;
67 struct InlineAsmIdentifierInfo;
68}
69
70namespace clang {
71 class ADLResult;
72 class ASTConsumer;
73 class ASTContext;
74 class ASTMutationListener;
75 class ASTReader;
76 class ASTWriter;
77 class ArrayType;
78 class AttributeList;
79 class BindingDecl;
80 class BlockDecl;
81 class CapturedDecl;
82 class CXXBasePath;
83 class CXXBasePaths;
84 class CXXBindTemporaryExpr;
85 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
86 class CXXConstructorDecl;
87 class CXXConversionDecl;
88 class CXXDeleteExpr;
89 class CXXDestructorDecl;
90 class CXXFieldCollector;
91 class CXXMemberCallExpr;
92 class CXXMethodDecl;
93 class CXXScopeSpec;
94 class CXXTemporary;
95 class CXXTryStmt;
96 class CallExpr;
97 class ClassTemplateDecl;
98 class ClassTemplatePartialSpecializationDecl;
99 class ClassTemplateSpecializationDecl;
100 class VarTemplatePartialSpecializationDecl;
101 class CodeCompleteConsumer;
102 class CodeCompletionAllocator;
103 class CodeCompletionTUInfo;
104 class CodeCompletionResult;
105 class CoroutineBodyStmt;
106 class Decl;
107 class DeclAccessPair;
108 class DeclContext;
109 class DeclRefExpr;
110 class DeclaratorDecl;
111 class DeducedTemplateArgument;
112 class DependentDiagnostic;
113 class DesignatedInitExpr;
114 class Designation;
115 class EnableIfAttr;
116 class EnumConstantDecl;
117 class Expr;
118 class ExtVectorType;
119 class FormatAttr;
120 class FriendDecl;
121 class FunctionDecl;
122 class FunctionProtoType;
123 class FunctionTemplateDecl;
124 class ImplicitConversionSequence;
125 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
126 class InitListExpr;
127 class InitializationKind;
128 class InitializationSequence;
129 class InitializedEntity;
130 class IntegerLiteral;
131 class LabelStmt;
132 class LambdaExpr;
133 class LangOptions;
134 class LocalInstantiationScope;
135 class LookupResult;
136 class MacroInfo;
137 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
138 class ModuleLoader;
139 class MultiLevelTemplateArgumentList;
140 class NamedDecl;
141 class ObjCCategoryDecl;
142 class ObjCCategoryImplDecl;
143 class ObjCCompatibleAliasDecl;
144 class ObjCContainerDecl;
145 class ObjCImplDecl;
146 class ObjCImplementationDecl;
147 class ObjCInterfaceDecl;
148 class ObjCIvarDecl;
149 template <class T> class ObjCList;
150 class ObjCMessageExpr;
151 class ObjCMethodDecl;
152 class ObjCPropertyDecl;
153 class ObjCProtocolDecl;
154 class OMPThreadPrivateDecl;
155 class OMPDeclareReductionDecl;
156 class OMPDeclareSimdDecl;
157 class OMPClause;
158 struct OverloadCandidate;
159 class OverloadCandidateSet;
160 class OverloadExpr;
161 class ParenListExpr;
162 class ParmVarDecl;
163 class Preprocessor;
164 class PseudoDestructorTypeStorage;
165 class PseudoObjectExpr;
166 class QualType;
167 class StandardConversionSequence;
168 class Stmt;
169 class StringLiteral;
170 class SwitchStmt;
171 class TemplateArgument;
172 class TemplateArgumentList;
173 class TemplateArgumentLoc;
174 class TemplateDecl;
175 class TemplateInstantiationCallback;
176 class TemplateParameterList;
177 class TemplatePartialOrderingContext;
178 class TemplateTemplateParmDecl;
179 class Token;
180 class TypeAliasDecl;
181 class TypedefDecl;
182 class TypedefNameDecl;
183 class TypeLoc;
184 class TypoCorrectionConsumer;
185 class UnqualifiedId;
186 class UnresolvedLookupExpr;
187 class UnresolvedMemberExpr;
188 class UnresolvedSetImpl;
189 class UnresolvedSetIterator;
190 class UsingDecl;
191 class UsingShadowDecl;
192 class ValueDecl;
193 class VarDecl;
194 class VarTemplateSpecializationDecl;
195 class VisibilityAttr;
196 class VisibleDeclConsumer;
197 class IndirectFieldDecl;
198 struct DeductionFailureInfo;
199 class TemplateSpecCandidateSet;
200
201namespace sema {
202 class AccessedEntity;
203 class BlockScopeInfo;
204 class CapturedRegionScopeInfo;
205 class CapturingScopeInfo;
206 class CompoundScopeInfo;
207 class DelayedDiagnostic;
208 class DelayedDiagnosticPool;
209 class FunctionScopeInfo;
210 class LambdaScopeInfo;
211 class PossiblyUnreachableDiag;
212 class SemaPPCallbacks;
213 class TemplateDeductionInfo;
214}
215
216namespace threadSafety {
217 class BeforeSet;
218 void threadSafetyCleanup(BeforeSet* Cache);
219}
220
221// FIXME: No way to easily map from TemplateTypeParmTypes to
222// TemplateTypeParmDecls, so we have this horrible PointerUnion.
223typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
224 SourceLocation> UnexpandedParameterPack;
225
226/// Describes whether we've seen any nullability information for the given
227/// file.
228struct FileNullability {
229 /// The first pointer declarator (of any pointer kind) in the file that does
230 /// not have a corresponding nullability annotation.
231 SourceLocation PointerLoc;
232
233 /// The end location for the first pointer declarator in the file. Used for
234 /// placing fix-its.
235 SourceLocation PointerEndLoc;
236
237 /// Which kind of pointer declarator we saw.
238 uint8_t PointerKind;
239
240 /// Whether we saw any type nullability annotations in the given file.
241 bool SawTypeNullability = false;
242};
243
244/// A mapping from file IDs to a record of whether we've seen nullability
245/// information in that file.
246class FileNullabilityMap {
247 /// A mapping from file IDs to the nullability information for each file ID.
248 llvm::DenseMap<FileID, FileNullability> Map;
249
250 /// A single-element cache based on the file ID.
251 struct {
252 FileID File;
253 FileNullability Nullability;
254 } Cache;
255
256public:
257 FileNullability &operator[](FileID file) {
258 // Check the single-element cache.
259 if (file == Cache.File)
260 return Cache.Nullability;
261
262 // It's not in the single-element cache; flush the cache if we have one.
263 if (!Cache.File.isInvalid()) {
264 Map[Cache.File] = Cache.Nullability;
265 }
266
267 // Pull this entry into the cache.
268 Cache.File = file;
269 Cache.Nullability = Map[file];
270 return Cache.Nullability;
271 }
272};
273
274/// Sema - This implements semantic analysis and AST building for C.
275class Sema {
276 Sema(const Sema &) = delete;
277 void operator=(const Sema &) = delete;
278
279 ///\brief Source of additional semantic information.
280 ExternalSemaSource *ExternalSource;
281
282 ///\brief Whether Sema has generated a multiplexer and has to delete it.
283 bool isMultiplexExternalSource;
284
285 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
286
287 bool isVisibleSlow(const NamedDecl *D);
288
289 /// Determine whether two declarations should be linked together, given that
290 /// the old declaration might not be visible and the new declaration might
291 /// not have external linkage.
292 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
293 const NamedDecl *New) {
294 if (isVisible(Old))
295 return true;
296 // See comment in below overload for why it's safe to compute the linkage
297 // of the new declaration here.
298 if (New->isExternallyDeclarable()) {
299 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 300, __extension__ __PRETTY_FUNCTION__))
300 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 300, __extension__ __PRETTY_FUNCTION__))
;
301 return true;
302 }
303 return false;
304 }
305 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
306
307public:
308 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
309 typedef OpaquePtr<TemplateName> TemplateTy;
310 typedef OpaquePtr<QualType> TypeTy;
311
312 OpenCLOptions OpenCLFeatures;
313 FPOptions FPFeatures;
314
315 const LangOptions &LangOpts;
316 Preprocessor &PP;
317 ASTContext &Context;
318 ASTConsumer &Consumer;
319 DiagnosticsEngine &Diags;
320 SourceManager &SourceMgr;
321
322 /// \brief Flag indicating whether or not to collect detailed statistics.
323 bool CollectStats;
324
325 /// \brief Code-completion consumer.
326 CodeCompleteConsumer *CodeCompleter;
327
328 /// CurContext - This is the current declaration context of parsing.
329 DeclContext *CurContext;
330
331 /// \brief Generally null except when we temporarily switch decl contexts,
332 /// like in \see ActOnObjCTemporaryExitContainerContext.
333 DeclContext *OriginalLexicalContext;
334
335 /// VAListTagName - The declaration name corresponding to __va_list_tag.
336 /// This is used as part of a hack to omit that class from ADL results.
337 DeclarationName VAListTagName;
338
339 bool MSStructPragmaOn; // True when \#pragma ms_struct on
340
341 /// \brief Controls member pointer representation format under the MS ABI.
342 LangOptions::PragmaMSPointersToMembersKind
343 MSPointerToMemberRepresentationMethod;
344
345 /// Stack of active SEH __finally scopes. Can be empty.
346 SmallVector<Scope*, 2> CurrentSEHFinally;
347
348 /// \brief Source location for newly created implicit MSInheritanceAttrs
349 SourceLocation ImplicitMSInheritanceAttrLoc;
350
351 /// \brief pragma clang section kind
352 enum PragmaClangSectionKind {
353 PCSK_Invalid = 0,
354 PCSK_BSS = 1,
355 PCSK_Data = 2,
356 PCSK_Rodata = 3,
357 PCSK_Text = 4
358 };
359
360 enum PragmaClangSectionAction {
361 PCSA_Set = 0,
362 PCSA_Clear = 1
363 };
364
365 struct PragmaClangSection {
366 std::string SectionName;
367 bool Valid = false;
368 SourceLocation PragmaLocation;
369
370 void Act(SourceLocation PragmaLocation,
371 PragmaClangSectionAction Action,
372 StringLiteral* Name);
373 };
374
375 PragmaClangSection PragmaClangBSSSection;
376 PragmaClangSection PragmaClangDataSection;
377 PragmaClangSection PragmaClangRodataSection;
378 PragmaClangSection PragmaClangTextSection;
379
380 enum PragmaMsStackAction {
381 PSK_Reset = 0x0, // #pragma ()
382 PSK_Set = 0x1, // #pragma (value)
383 PSK_Push = 0x2, // #pragma (push[, id])
384 PSK_Pop = 0x4, // #pragma (pop[, id])
385 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
386 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
387 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
388 };
389
390 template<typename ValueType>
391 struct PragmaStack {
392 struct Slot {
393 llvm::StringRef StackSlotLabel;
394 ValueType Value;
395 SourceLocation PragmaLocation;
396 SourceLocation PragmaPushLocation;
397 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
398 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
399 : StackSlotLabel(StackSlotLabel), Value(Value),
400 PragmaLocation(PragmaLocation),
401 PragmaPushLocation(PragmaPushLocation) {}
402 };
403 void Act(SourceLocation PragmaLocation,
404 PragmaMsStackAction Action,
405 llvm::StringRef StackSlotLabel,
406 ValueType Value);
407
408 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
409 // method body to restore the stacks on exit, so it works like this:
410 //
411 // struct S {
412 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
413 // void Method {}
414 // #pragma <name>(pop, InternalPragmaSlot)
415 // };
416 //
417 // It works even with #pragma vtordisp, although MSVC doesn't support
418 // #pragma vtordisp(push [, id], n)
419 // syntax.
420 //
421 // Push / pop a named sentinel slot.
422 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
423 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 424, __extension__ __PRETTY_FUNCTION__))
424 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/tools/clang/include/clang/Sema/Sema.h"
, 424, __extension__ __PRETTY_FUNCTION__))
;
425 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
426 }
427
428 // Constructors.
429 explicit PragmaStack(const ValueType &Default)
430 : DefaultValue(Default), CurrentValue(Default) {}
431
432 bool hasValue() const { return CurrentValue != DefaultValue; }
433
434 SmallVector<Slot, 2> Stack;
435 ValueType DefaultValue; // Value used for PSK_Reset action.
436 ValueType CurrentValue;
437 SourceLocation CurrentPragmaLocation;
438 };
439 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
440 // we shouldn't do so if they're in a module).
441
442 /// \brief Whether to insert vtordisps prior to virtual bases in the Microsoft
443 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
444 ///
445 /// 0: Suppress all vtordisps
446 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
447 /// structors
448 /// 2: Always insert vtordisps to support RTTI on partially constructed
449 /// objects
450 PragmaStack<MSVtorDispAttr::Mode> VtorDispStack;
451 // #pragma pack.
452 // Sentinel to represent when the stack is set to mac68k alignment.
453 static const unsigned kMac68kAlignmentSentinel = ~0U;
454 PragmaStack<unsigned> PackStack;
455 // The current #pragma pack values and locations at each #include.
456 struct PackIncludeState {
457 unsigned CurrentValue;
458 SourceLocation CurrentPragmaLocation;
459 bool HasNonDefaultValue, ShouldWarnOnInclude;
460 };
461 SmallVector<PackIncludeState, 8> PackIncludeStack;
462 // Segment #pragmas.
463 PragmaStack<StringLiteral *> DataSegStack;
464 PragmaStack<StringLiteral *> BSSSegStack;
465 PragmaStack<StringLiteral *> ConstSegStack;
466 PragmaStack<StringLiteral *> CodeSegStack;
467
468 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
469 // Actions should be performed only if we enter / exit a C++ method body.
470 class PragmaStackSentinelRAII {
471 public:
472 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
473 ~PragmaStackSentinelRAII();
474
475 private:
476 Sema &S;
477 StringRef SlotLabel;
478 bool ShouldAct;
479 };
480
481 /// A mapping that describes the nullability we've seen in each header file.
482 FileNullabilityMap NullabilityMap;
483
484 /// Last section used with #pragma init_seg.
485 StringLiteral *CurInitSeg;
486 SourceLocation CurInitSegLoc;
487
488 /// VisContext - Manages the stack for \#pragma GCC visibility.
489 void *VisContext; // Really a "PragmaVisStack*"
490
491 /// \brief This represents the stack of attributes that were pushed by
492 /// \#pragma clang attribute.
493 struct PragmaAttributeEntry {
494 SourceLocation Loc;
495 AttributeList *Attribute;
496 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
497 bool IsUsed;
498 };
499 SmallVector<PragmaAttributeEntry, 2> PragmaAttributeStack;
500
501 /// \brief The declaration that is currently receiving an attribute from the
502 /// #pragma attribute stack.
503 const Decl *PragmaAttributeCurrentTargetDecl;
504
505 /// \brief This represents the last location of a "#pragma clang optimize off"
506 /// directive if such a directive has not been closed by an "on" yet. If
507 /// optimizations are currently "on", this is set to an invalid location.
508 SourceLocation OptimizeOffPragmaLocation;
509
510 /// \brief Flag indicating if Sema is building a recovery call expression.
511 ///
512 /// This flag is used to avoid building recovery call expressions
513 /// if Sema is already doing so, which would cause infinite recursions.
514 bool IsBuildingRecoveryCallExpr;
515
516 /// Used to control the generation of ExprWithCleanups.
517 CleanupInfo Cleanup;
518
519 /// ExprCleanupObjects - This is the stack of objects requiring
520 /// cleanup that are created by the current full expression. The
521 /// element type here is ExprWithCleanups::Object.
522 SmallVector<BlockDecl*, 8> ExprCleanupObjects;
523
524 /// \brief Store a list of either DeclRefExprs or MemberExprs
525 /// that contain a reference to a variable (constant) that may or may not
526 /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue
527 /// and discarded value conversions have been applied to all subexpressions
528 /// of the enclosing full expression. This is cleared at the end of each
529 /// full expression.
530 llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs;
531
532 /// \brief Stack containing information about each of the nested
533 /// function, block, and method scopes that are currently active.
534 ///
535 /// This array is never empty. Clients should ignore the first
536 /// element, which is used to cache a single FunctionScopeInfo
537 /// that's used to parse every top-level function.
538 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
539
540 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
541 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
542 ExtVectorDeclsType;
543
544 /// ExtVectorDecls - This is a list all the extended vector types. This allows
545 /// us to associate a raw vector type with one of the ext_vector type names.
546 /// This is only necessary for issuing pretty diagnostics.
547 ExtVectorDeclsType ExtVectorDecls;
548
549 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
550<