Bug Summary

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

Annotated Source Code

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