Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaTemplate.cpp
Warning:line 1401, column 5
Value stored to 'RD' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplate.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaTemplate.cpp
1//===------- SemaTemplate.cpp - Semantic Analysis for C++ Templates -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===//
7//
8// This file implements semantic analysis for C++ templates.
9//===----------------------------------------------------------------------===//
10
11#include "TreeTransform.h"
12#include "clang/AST/ASTConsumer.h"
13#include "clang/AST/ASTContext.h"
14#include "clang/AST/Decl.h"
15#include "clang/AST/DeclFriend.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/RecursiveASTVisitor.h"
20#include "clang/AST/TemplateName.h"
21#include "clang/AST/TypeVisitor.h"
22#include "clang/Basic/Builtins.h"
23#include "clang/Basic/DiagnosticSema.h"
24#include "clang/Basic/LangOptions.h"
25#include "clang/Basic/PartialDiagnostic.h"
26#include "clang/Basic/Stack.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/Initialization.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Overload.h"
32#include "clang/Sema/ParsedTemplate.h"
33#include "clang/Sema/Scope.h"
34#include "clang/Sema/SemaInternal.h"
35#include "clang/Sema/Template.h"
36#include "clang/Sema/TemplateDeduction.h"
37#include "llvm/ADT/SmallBitVector.h"
38#include "llvm/ADT/SmallString.h"
39#include "llvm/ADT/StringExtras.h"
40
41#include <iterator>
42using namespace clang;
43using namespace sema;
44
45// Exported for use by Parser.
46SourceRange
47clang::getTemplateParamsRange(TemplateParameterList const * const *Ps,
48 unsigned N) {
49 if (!N) return SourceRange();
50 return SourceRange(Ps[0]->getTemplateLoc(), Ps[N-1]->getRAngleLoc());
51}
52
53unsigned Sema::getTemplateDepth(Scope *S) const {
54 unsigned Depth = 0;
55
56 // Each template parameter scope represents one level of template parameter
57 // depth.
58 for (Scope *TempParamScope = S->getTemplateParamParent(); TempParamScope;
59 TempParamScope = TempParamScope->getParent()->getTemplateParamParent()) {
60 ++Depth;
61 }
62
63 // Note that there are template parameters with the given depth.
64 auto ParamsAtDepth = [&](unsigned D) { Depth = std::max(Depth, D + 1); };
65
66 // Look for parameters of an enclosing generic lambda. We don't create a
67 // template parameter scope for these.
68 for (FunctionScopeInfo *FSI : getFunctionScopes()) {
69 if (auto *LSI = dyn_cast<LambdaScopeInfo>(FSI)) {
70 if (!LSI->TemplateParams.empty()) {
71 ParamsAtDepth(LSI->AutoTemplateParameterDepth);
72 break;
73 }
74 if (LSI->GLTemplateParameterList) {
75 ParamsAtDepth(LSI->GLTemplateParameterList->getDepth());
76 break;
77 }
78 }
79 }
80
81 // Look for parameters of an enclosing terse function template. We don't
82 // create a template parameter scope for these either.
83 for (const InventedTemplateParameterInfo &Info :
84 getInventedParameterInfos()) {
85 if (!Info.TemplateParams.empty()) {
86 ParamsAtDepth(Info.AutoTemplateParameterDepth);
87 break;
88 }
89 }
90
91 return Depth;
92}
93
94/// \brief Determine whether the declaration found is acceptable as the name
95/// of a template and, if so, return that template declaration. Otherwise,
96/// returns null.
97///
98/// Note that this may return an UnresolvedUsingValueDecl if AllowDependent
99/// is true. In all other cases it will return a TemplateDecl (or null).
100NamedDecl *Sema::getAsTemplateNameDecl(NamedDecl *D,
101 bool AllowFunctionTemplates,
102 bool AllowDependent) {
103 D = D->getUnderlyingDecl();
104
105 if (isa<TemplateDecl>(D)) {
106 if (!AllowFunctionTemplates && isa<FunctionTemplateDecl>(D))
107 return nullptr;
108
109 return D;
110 }
111
112 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
113 // C++ [temp.local]p1:
114 // Like normal (non-template) classes, class templates have an
115 // injected-class-name (Clause 9). The injected-class-name
116 // can be used with or without a template-argument-list. When
117 // it is used without a template-argument-list, it is
118 // equivalent to the injected-class-name followed by the
119 // template-parameters of the class template enclosed in
120 // <>. When it is used with a template-argument-list, it
121 // refers to the specified class template specialization,
122 // which could be the current specialization or another
123 // specialization.
124 if (Record->isInjectedClassName()) {
125 Record = cast<CXXRecordDecl>(Record->getDeclContext());
126 if (Record->getDescribedClassTemplate())
127 return Record->getDescribedClassTemplate();
128
129 if (ClassTemplateSpecializationDecl *Spec
130 = dyn_cast<ClassTemplateSpecializationDecl>(Record))
131 return Spec->getSpecializedTemplate();
132 }
133
134 return nullptr;
135 }
136
137 // 'using Dependent::foo;' can resolve to a template name.
138 // 'using typename Dependent::foo;' cannot (not even if 'foo' is an
139 // injected-class-name).
140 if (AllowDependent && isa<UnresolvedUsingValueDecl>(D))
141 return D;
142
143 return nullptr;
144}
145
146void Sema::FilterAcceptableTemplateNames(LookupResult &R,
147 bool AllowFunctionTemplates,
148 bool AllowDependent) {
149 LookupResult::Filter filter = R.makeFilter();
150 while (filter.hasNext()) {
151 NamedDecl *Orig = filter.next();
152 if (!getAsTemplateNameDecl(Orig, AllowFunctionTemplates, AllowDependent))
153 filter.erase();
154 }
155 filter.done();
156}
157
158bool Sema::hasAnyAcceptableTemplateNames(LookupResult &R,
159 bool AllowFunctionTemplates,
160 bool AllowDependent,
161 bool AllowNonTemplateFunctions) {
162 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
163 if (getAsTemplateNameDecl(*I, AllowFunctionTemplates, AllowDependent))
164 return true;
165 if (AllowNonTemplateFunctions &&
166 isa<FunctionDecl>((*I)->getUnderlyingDecl()))
167 return true;
168 }
169
170 return false;
171}
172
173TemplateNameKind Sema::isTemplateName(Scope *S,
174 CXXScopeSpec &SS,
175 bool hasTemplateKeyword,
176 const UnqualifiedId &Name,
177 ParsedType ObjectTypePtr,
178 bool EnteringContext,
179 TemplateTy &TemplateResult,
180 bool &MemberOfUnknownSpecialization,
181 bool Disambiguation) {
182 assert(getLangOpts().CPlusPlus && "No template names in C!")(static_cast <bool> (getLangOpts().CPlusPlus &&
"No template names in C!") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"No template names in C!\""
, "clang/lib/Sema/SemaTemplate.cpp", 182, __extension__ __PRETTY_FUNCTION__
))
;
183
184 DeclarationName TName;
185 MemberOfUnknownSpecialization = false;
186
187 switch (Name.getKind()) {
188 case UnqualifiedIdKind::IK_Identifier:
189 TName = DeclarationName(Name.Identifier);
190 break;
191
192 case UnqualifiedIdKind::IK_OperatorFunctionId:
193 TName = Context.DeclarationNames.getCXXOperatorName(
194 Name.OperatorFunctionId.Operator);
195 break;
196
197 case UnqualifiedIdKind::IK_LiteralOperatorId:
198 TName = Context.DeclarationNames.getCXXLiteralOperatorName(Name.Identifier);
199 break;
200
201 default:
202 return TNK_Non_template;
203 }
204
205 QualType ObjectType = ObjectTypePtr.get();
206
207 AssumedTemplateKind AssumedTemplate;
208 LookupResult R(*this, TName, Name.getBeginLoc(), LookupOrdinaryName);
209 if (LookupTemplateName(R, S, SS, ObjectType, EnteringContext,
210 MemberOfUnknownSpecialization, SourceLocation(),
211 &AssumedTemplate,
212 /*AllowTypoCorrection=*/!Disambiguation))
213 return TNK_Non_template;
214
215 if (AssumedTemplate != AssumedTemplateKind::None) {
216 TemplateResult = TemplateTy::make(Context.getAssumedTemplateName(TName));
217 // Let the parser know whether we found nothing or found functions; if we
218 // found nothing, we want to more carefully check whether this is actually
219 // a function template name versus some other kind of undeclared identifier.
220 return AssumedTemplate == AssumedTemplateKind::FoundNothing
221 ? TNK_Undeclared_template
222 : TNK_Function_template;
223 }
224
225 if (R.empty())
226 return TNK_Non_template;
227
228 NamedDecl *D = nullptr;
229 UsingShadowDecl *FoundUsingShadow = dyn_cast<UsingShadowDecl>(*R.begin());
230 if (R.isAmbiguous()) {
231 // If we got an ambiguity involving a non-function template, treat this
232 // as a template name, and pick an arbitrary template for error recovery.
233 bool AnyFunctionTemplates = false;
234 for (NamedDecl *FoundD : R) {
235 if (NamedDecl *FoundTemplate = getAsTemplateNameDecl(FoundD)) {
236 if (isa<FunctionTemplateDecl>(FoundTemplate))
237 AnyFunctionTemplates = true;
238 else {
239 D = FoundTemplate;
240 FoundUsingShadow = dyn_cast<UsingShadowDecl>(FoundD);
241 break;
242 }
243 }
244 }
245
246 // If we didn't find any templates at all, this isn't a template name.
247 // Leave the ambiguity for a later lookup to diagnose.
248 if (!D && !AnyFunctionTemplates) {
249 R.suppressDiagnostics();
250 return TNK_Non_template;
251 }
252
253 // If the only templates were function templates, filter out the rest.
254 // We'll diagnose the ambiguity later.
255 if (!D)
256 FilterAcceptableTemplateNames(R);
257 }
258
259 // At this point, we have either picked a single template name declaration D
260 // or we have a non-empty set of results R containing either one template name
261 // declaration or a set of function templates.
262
263 TemplateName Template;
264 TemplateNameKind TemplateKind;
265
266 unsigned ResultCount = R.end() - R.begin();
267 if (!D && ResultCount > 1) {
268 // We assume that we'll preserve the qualifier from a function
269 // template name in other ways.
270 Template = Context.getOverloadedTemplateName(R.begin(), R.end());
271 TemplateKind = TNK_Function_template;
272
273 // We'll do this lookup again later.
274 R.suppressDiagnostics();
275 } else {
276 if (!D) {
277 D = getAsTemplateNameDecl(*R.begin());
278 assert(D && "unambiguous result is not a template name")(static_cast <bool> (D && "unambiguous result is not a template name"
) ? void (0) : __assert_fail ("D && \"unambiguous result is not a template name\""
, "clang/lib/Sema/SemaTemplate.cpp", 278, __extension__ __PRETTY_FUNCTION__
))
;
279 }
280
281 if (isa<UnresolvedUsingValueDecl>(D)) {
282 // We don't yet know whether this is a template-name or not.
283 MemberOfUnknownSpecialization = true;
284 return TNK_Non_template;
285 }
286
287 TemplateDecl *TD = cast<TemplateDecl>(D);
288 Template =
289 FoundUsingShadow ? TemplateName(FoundUsingShadow) : TemplateName(TD);
290 assert(!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD)(static_cast <bool> (!FoundUsingShadow || FoundUsingShadow
->getTargetDecl() == TD) ? void (0) : __assert_fail ("!FoundUsingShadow || FoundUsingShadow->getTargetDecl() == TD"
, "clang/lib/Sema/SemaTemplate.cpp", 290, __extension__ __PRETTY_FUNCTION__
))
;
291 if (SS.isSet() && !SS.isInvalid()) {
292 NestedNameSpecifier *Qualifier = SS.getScopeRep();
293 Template = Context.getQualifiedTemplateName(Qualifier, hasTemplateKeyword,
294 Template);
295 }
296
297 if (isa<FunctionTemplateDecl>(TD)) {
298 TemplateKind = TNK_Function_template;
299
300 // We'll do this lookup again later.
301 R.suppressDiagnostics();
302 } else {
303 assert(isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) ||(static_cast <bool> (isa<ClassTemplateDecl>(TD) ||
isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl
>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl
>(TD) || isa<ConceptDecl>(TD)) ? void (0) : __assert_fail
("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "clang/lib/Sema/SemaTemplate.cpp", 305, __extension__ __PRETTY_FUNCTION__
))
304 isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) ||(static_cast <bool> (isa<ClassTemplateDecl>(TD) ||
isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl
>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl
>(TD) || isa<ConceptDecl>(TD)) ? void (0) : __assert_fail
("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "clang/lib/Sema/SemaTemplate.cpp", 305, __extension__ __PRETTY_FUNCTION__
))
305 isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD))(static_cast <bool> (isa<ClassTemplateDecl>(TD) ||
isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl
>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl
>(TD) || isa<ConceptDecl>(TD)) ? void (0) : __assert_fail
("isa<ClassTemplateDecl>(TD) || isa<TemplateTemplateParmDecl>(TD) || isa<TypeAliasTemplateDecl>(TD) || isa<VarTemplateDecl>(TD) || isa<BuiltinTemplateDecl>(TD) || isa<ConceptDecl>(TD)"
, "clang/lib/Sema/SemaTemplate.cpp", 305, __extension__ __PRETTY_FUNCTION__
))
;
306 TemplateKind =
307 isa<VarTemplateDecl>(TD) ? TNK_Var_template :
308 isa<ConceptDecl>(TD) ? TNK_Concept_template :
309 TNK_Type_template;
310 }
311 }
312
313 TemplateResult = TemplateTy::make(Template);
314 return TemplateKind;
315}
316
317bool Sema::isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
318 SourceLocation NameLoc,
319 ParsedTemplateTy *Template) {
320 CXXScopeSpec SS;
321 bool MemberOfUnknownSpecialization = false;
322
323 // We could use redeclaration lookup here, but we don't need to: the
324 // syntactic form of a deduction guide is enough to identify it even
325 // if we can't look up the template name at all.
326 LookupResult R(*this, DeclarationName(&Name), NameLoc, LookupOrdinaryName);
327 if (LookupTemplateName(R, S, SS, /*ObjectType*/ QualType(),
328 /*EnteringContext*/ false,
329 MemberOfUnknownSpecialization))
330 return false;
331
332 if (R.empty()) return false;
333 if (R.isAmbiguous()) {
334 // FIXME: Diagnose an ambiguity if we find at least one template.
335 R.suppressDiagnostics();
336 return false;
337 }
338
339 // We only treat template-names that name type templates as valid deduction
340 // guide names.
341 TemplateDecl *TD = R.getAsSingle<TemplateDecl>();
342 if (!TD || !getAsTypeTemplateDecl(TD))
343 return false;
344
345 if (Template)
346 *Template = TemplateTy::make(TemplateName(TD));
347 return true;
348}
349
350bool Sema::DiagnoseUnknownTemplateName(const IdentifierInfo &II,
351 SourceLocation IILoc,
352 Scope *S,
353 const CXXScopeSpec *SS,
354 TemplateTy &SuggestedTemplate,
355 TemplateNameKind &SuggestedKind) {
356 // We can't recover unless there's a dependent scope specifier preceding the
357 // template name.
358 // FIXME: Typo correction?
359 if (!SS || !SS->isSet() || !isDependentScopeSpecifier(*SS) ||
360 computeDeclContext(*SS))
361 return false;
362
363 // The code is missing a 'template' keyword prior to the dependent template
364 // name.
365 NestedNameSpecifier *Qualifier = (NestedNameSpecifier*)SS->getScopeRep();
366 Diag(IILoc, diag::err_template_kw_missing)
367 << Qualifier << II.getName()
368 << FixItHint::CreateInsertion(IILoc, "template ");
369 SuggestedTemplate
370 = TemplateTy::make(Context.getDependentTemplateName(Qualifier, &II));
371 SuggestedKind = TNK_Dependent_template_name;
372 return true;
373}
374
375bool Sema::LookupTemplateName(LookupResult &Found,
376 Scope *S, CXXScopeSpec &SS,
377 QualType ObjectType,
378 bool EnteringContext,
379 bool &MemberOfUnknownSpecialization,
380 RequiredTemplateKind RequiredTemplate,
381 AssumedTemplateKind *ATK,
382 bool AllowTypoCorrection) {
383 if (ATK)
384 *ATK = AssumedTemplateKind::None;
385
386 if (SS.isInvalid())
387 return true;
388
389 Found.setTemplateNameLookup(true);
390
391 // Determine where to perform name lookup
392 MemberOfUnknownSpecialization = false;
393 DeclContext *LookupCtx = nullptr;
394 bool IsDependent = false;
395 if (!ObjectType.isNull()) {
396 // This nested-name-specifier occurs in a member access expression, e.g.,
397 // x->B::f, and we are looking into the type of the object.
398 assert(SS.isEmpty() && "ObjectType and scope specifier cannot coexist")(static_cast <bool> (SS.isEmpty() && "ObjectType and scope specifier cannot coexist"
) ? void (0) : __assert_fail ("SS.isEmpty() && \"ObjectType and scope specifier cannot coexist\""
, "clang/lib/Sema/SemaTemplate.cpp", 398, __extension__ __PRETTY_FUNCTION__
))
;
399 LookupCtx = computeDeclContext(ObjectType);
400 IsDependent = !LookupCtx && ObjectType->isDependentType();
401 assert((IsDependent || !ObjectType->isIncompleteType() ||(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType
() || !ObjectType->getAs<TagType>() || ObjectType->
castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type"
) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__
))
402 !ObjectType->getAs<TagType>() ||(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType
() || !ObjectType->getAs<TagType>() || ObjectType->
castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type"
) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__
))
403 ObjectType->castAs<TagType>()->isBeingDefined()) &&(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType
() || !ObjectType->getAs<TagType>() || ObjectType->
castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type"
) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__
))
404 "Caller should have completed object type")(static_cast <bool> ((IsDependent || !ObjectType->isIncompleteType
() || !ObjectType->getAs<TagType>() || ObjectType->
castAs<TagType>()->isBeingDefined()) && "Caller should have completed object type"
) ? void (0) : __assert_fail ("(IsDependent || !ObjectType->isIncompleteType() || !ObjectType->getAs<TagType>() || ObjectType->castAs<TagType>()->isBeingDefined()) && \"Caller should have completed object type\""
, "clang/lib/Sema/SemaTemplate.cpp", 404, __extension__ __PRETTY_FUNCTION__
))
;
405
406 // Template names cannot appear inside an Objective-C class or object type
407 // or a vector type.
408 //
409 // FIXME: This is wrong. For example:
410 //
411 // template<typename T> using Vec = T __attribute__((ext_vector_type(4)));
412 // Vec<int> vi;
413 // vi.Vec<int>::~Vec<int>();
414 //
415 // ... should be accepted but we will not treat 'Vec' as a template name
416 // here. The right thing to do would be to check if the name is a valid
417 // vector component name, and look up a template name if not. And similarly
418 // for lookups into Objective-C class and object types, where the same
419 // problem can arise.
420 if (ObjectType->isObjCObjectOrInterfaceType() ||
421 ObjectType->isVectorType()) {
422 Found.clear();
423 return false;
424 }
425 } else if (SS.isNotEmpty()) {
426 // This nested-name-specifier occurs after another nested-name-specifier,
427 // so long into the context associated with the prior nested-name-specifier.
428 LookupCtx = computeDeclContext(SS, EnteringContext);
429 IsDependent = !LookupCtx && isDependentScopeSpecifier(SS);
430
431 // The declaration context must be complete.
432 if (LookupCtx && RequireCompleteDeclContext(SS, LookupCtx))
433 return true;
434 }
435
436 bool ObjectTypeSearchedInScope = false;
437 bool AllowFunctionTemplatesInLookup = true;
438 if (LookupCtx) {
439 // Perform "qualified" name lookup into the declaration context we
440 // computed, which is either the type of the base of a member access
441 // expression or the declaration context associated with a prior
442 // nested-name-specifier.
443 LookupQualifiedName(Found, LookupCtx);
444
445 // FIXME: The C++ standard does not clearly specify what happens in the
446 // case where the object type is dependent, and implementations vary. In
447 // Clang, we treat a name after a . or -> as a template-name if lookup
448 // finds a non-dependent member or member of the current instantiation that
449 // is a type template, or finds no such members and lookup in the context
450 // of the postfix-expression finds a type template. In the latter case, the
451 // name is nonetheless dependent, and we may resolve it to a member of an
452 // unknown specialization when we come to instantiate the template.
453 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
454 }
455
456 if (SS.isEmpty() && (ObjectType.isNull() || Found.empty())) {
457 // C++ [basic.lookup.classref]p1:
458 // In a class member access expression (5.2.5), if the . or -> token is
459 // immediately followed by an identifier followed by a <, the
460 // identifier must be looked up to determine whether the < is the
461 // beginning of a template argument list (14.2) or a less-than operator.
462 // The identifier is first looked up in the class of the object
463 // expression. If the identifier is not found, it is then looked up in
464 // the context of the entire postfix-expression and shall name a class
465 // template.
466 if (S)
467 LookupName(Found, S);
468
469 if (!ObjectType.isNull()) {
470 // FIXME: We should filter out all non-type templates here, particularly
471 // variable templates and concepts. But the exclusion of alias templates
472 // and template template parameters is a wording defect.
473 AllowFunctionTemplatesInLookup = false;
474 ObjectTypeSearchedInScope = true;
475 }
476
477 IsDependent |= Found.wasNotFoundInCurrentInstantiation();
478 }
479
480 if (Found.isAmbiguous())
481 return false;
482
483 if (ATK && SS.isEmpty() && ObjectType.isNull() &&
484 !RequiredTemplate.hasTemplateKeyword()) {
485 // C++2a [temp.names]p2:
486 // A name is also considered to refer to a template if it is an
487 // unqualified-id followed by a < and name lookup finds either one or more
488 // functions or finds nothing.
489 //
490 // To keep our behavior consistent, we apply the "finds nothing" part in
491 // all language modes, and diagnose the empty lookup in ActOnCallExpr if we
492 // successfully form a call to an undeclared template-id.
493 bool AllFunctions =
494 getLangOpts().CPlusPlus20 && llvm::all_of(Found, [](NamedDecl *ND) {
495 return isa<FunctionDecl>(ND->getUnderlyingDecl());
496 });
497 if (AllFunctions || (Found.empty() && !IsDependent)) {
498 // If lookup found any functions, or if this is a name that can only be
499 // used for a function, then strongly assume this is a function
500 // template-id.
501 *ATK = (Found.empty() && Found.getLookupName().isIdentifier())
502 ? AssumedTemplateKind::FoundNothing
503 : AssumedTemplateKind::FoundFunctions;
504 Found.clear();
505 return false;
506 }
507 }
508
509 if (Found.empty() && !IsDependent && AllowTypoCorrection) {
510 // If we did not find any names, and this is not a disambiguation, attempt
511 // to correct any typos.
512 DeclarationName Name = Found.getLookupName();
513 Found.clear();
514 // Simple filter callback that, for keywords, only accepts the C++ *_cast
515 DefaultFilterCCC FilterCCC{};
516 FilterCCC.WantTypeSpecifiers = false;
517 FilterCCC.WantExpressionKeywords = false;
518 FilterCCC.WantRemainingKeywords = false;
519 FilterCCC.WantCXXNamedCasts = true;
520 if (TypoCorrection Corrected =
521 CorrectTypo(Found.getLookupNameInfo(), Found.getLookupKind(), S,
522 &SS, FilterCCC, CTK_ErrorRecovery, LookupCtx)) {
523 if (auto *ND = Corrected.getFoundDecl())
524 Found.addDecl(ND);
525 FilterAcceptableTemplateNames(Found);
526 if (Found.isAmbiguous()) {
527 Found.clear();
528 } else if (!Found.empty()) {
529 Found.setLookupName(Corrected.getCorrection());
530 if (LookupCtx) {
531 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
532 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
533 Name.getAsString() == CorrectedStr;
534 diagnoseTypo(Corrected, PDiag(diag::err_no_member_template_suggest)
535 << Name << LookupCtx << DroppedSpecifier
536 << SS.getRange());
537 } else {
538 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest) << Name);
539 }
540 }
541 }
542 }
543
544 NamedDecl *ExampleLookupResult =
545 Found.empty() ? nullptr : Found.getRepresentativeDecl();
546 FilterAcceptableTemplateNames(Found, AllowFunctionTemplatesInLookup);
547 if (Found.empty()) {
548 if (IsDependent) {
549 MemberOfUnknownSpecialization = true;
550 return false;
551 }
552
553 // If a 'template' keyword was used, a lookup that finds only non-template
554 // names is an error.
555 if (ExampleLookupResult && RequiredTemplate) {
556 Diag(Found.getNameLoc(), diag::err_template_kw_refers_to_non_template)
557 << Found.getLookupName() << SS.getRange()
558 << RequiredTemplate.hasTemplateKeyword()
559 << RequiredTemplate.getTemplateKeywordLoc();
560 Diag(ExampleLookupResult->getUnderlyingDecl()->getLocation(),
561 diag::note_template_kw_refers_to_non_template)
562 << Found.getLookupName();
563 return true;
564 }
565
566 return false;
567 }
568
569 if (S && !ObjectType.isNull() && !ObjectTypeSearchedInScope &&
570 !getLangOpts().CPlusPlus11) {
571 // C++03 [basic.lookup.classref]p1:
572 // [...] If the lookup in the class of the object expression finds a
573 // template, the name is also looked up in the context of the entire
574 // postfix-expression and [...]
575 //
576 // Note: C++11 does not perform this second lookup.
577 LookupResult FoundOuter(*this, Found.getLookupName(), Found.getNameLoc(),
578 LookupOrdinaryName);
579 FoundOuter.setTemplateNameLookup(true);
580 LookupName(FoundOuter, S);
581 // FIXME: We silently accept an ambiguous lookup here, in violation of
582 // [basic.lookup]/1.
583 FilterAcceptableTemplateNames(FoundOuter, /*AllowFunctionTemplates=*/false);
584
585 NamedDecl *OuterTemplate;
586 if (FoundOuter.empty()) {
587 // - if the name is not found, the name found in the class of the
588 // object expression is used, otherwise
589 } else if (FoundOuter.isAmbiguous() || !FoundOuter.isSingleResult() ||
590 !(OuterTemplate =
591 getAsTemplateNameDecl(FoundOuter.getFoundDecl()))) {
592 // - if the name is found in the context of the entire
593 // postfix-expression and does not name a class template, the name
594 // found in the class of the object expression is used, otherwise
595 FoundOuter.clear();
596 } else if (!Found.isSuppressingDiagnostics()) {
597 // - if the name found is a class template, it must refer to the same
598 // entity as the one found in the class of the object expression,
599 // otherwise the program is ill-formed.
600 if (!Found.isSingleResult() ||
601 getAsTemplateNameDecl(Found.getFoundDecl())->getCanonicalDecl() !=
602 OuterTemplate->getCanonicalDecl()) {
603 Diag(Found.getNameLoc(),
604 diag::ext_nested_name_member_ref_lookup_ambiguous)
605 << Found.getLookupName()
606 << ObjectType;
607 Diag(Found.getRepresentativeDecl()->getLocation(),
608 diag::note_ambig_member_ref_object_type)
609 << ObjectType;
610 Diag(FoundOuter.getFoundDecl()->getLocation(),
611 diag::note_ambig_member_ref_scope);
612
613 // Recover by taking the template that we found in the object
614 // expression's type.
615 }
616 }
617 }
618
619 return false;
620}
621
622void Sema::diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
623 SourceLocation Less,
624 SourceLocation Greater) {
625 if (TemplateName.isInvalid())
626 return;
627
628 DeclarationNameInfo NameInfo;
629 CXXScopeSpec SS;
630 LookupNameKind LookupKind;
631
632 DeclContext *LookupCtx = nullptr;
633 NamedDecl *Found = nullptr;
634 bool MissingTemplateKeyword = false;
635
636 // Figure out what name we looked up.
637 if (auto *DRE = dyn_cast<DeclRefExpr>(TemplateName.get())) {
638 NameInfo = DRE->getNameInfo();
639 SS.Adopt(DRE->getQualifierLoc());
640 LookupKind = LookupOrdinaryName;
641 Found = DRE->getFoundDecl();
642 } else if (auto *ME = dyn_cast<MemberExpr>(TemplateName.get())) {
643 NameInfo = ME->getMemberNameInfo();
644 SS.Adopt(ME->getQualifierLoc());
645 LookupKind = LookupMemberName;
646 LookupCtx = ME->getBase()->getType()->getAsCXXRecordDecl();
647 Found = ME->getMemberDecl();
648 } else if (auto *DSDRE =
649 dyn_cast<DependentScopeDeclRefExpr>(TemplateName.get())) {
650 NameInfo = DSDRE->getNameInfo();
651 SS.Adopt(DSDRE->getQualifierLoc());
652 MissingTemplateKeyword = true;
653 } else if (auto *DSME =
654 dyn_cast<CXXDependentScopeMemberExpr>(TemplateName.get())) {
655 NameInfo = DSME->getMemberNameInfo();
656 SS.Adopt(DSME->getQualifierLoc());
657 MissingTemplateKeyword = true;
658 } else {
659 llvm_unreachable("unexpected kind of potential template name")::llvm::llvm_unreachable_internal("unexpected kind of potential template name"
, "clang/lib/Sema/SemaTemplate.cpp", 659)
;
660 }
661
662 // If this is a dependent-scope lookup, diagnose that the 'template' keyword
663 // was missing.
664 if (MissingTemplateKeyword) {
665 Diag(NameInfo.getBeginLoc(), diag::err_template_kw_missing)
666 << "" << NameInfo.getName().getAsString() << SourceRange(Less, Greater);
667 return;
668 }
669
670 // Try to correct the name by looking for templates and C++ named casts.
671 struct TemplateCandidateFilter : CorrectionCandidateCallback {
672 Sema &S;
673 TemplateCandidateFilter(Sema &S) : S(S) {
674 WantTypeSpecifiers = false;
675 WantExpressionKeywords = false;
676 WantRemainingKeywords = false;
677 WantCXXNamedCasts = true;
678 };
679 bool ValidateCandidate(const TypoCorrection &Candidate) override {
680 if (auto *ND = Candidate.getCorrectionDecl())
681 return S.getAsTemplateNameDecl(ND);
682 return Candidate.isKeyword();
683 }
684
685 std::unique_ptr<CorrectionCandidateCallback> clone() override {
686 return std::make_unique<TemplateCandidateFilter>(*this);
687 }
688 };
689
690 DeclarationName Name = NameInfo.getName();
691 TemplateCandidateFilter CCC(*this);
692 if (TypoCorrection Corrected = CorrectTypo(NameInfo, LookupKind, S, &SS, CCC,
693 CTK_ErrorRecovery, LookupCtx)) {
694 auto *ND = Corrected.getFoundDecl();
695 if (ND)
696 ND = getAsTemplateNameDecl(ND);
697 if (ND || Corrected.isKeyword()) {
698 if (LookupCtx) {
699 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
700 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
701 Name.getAsString() == CorrectedStr;
702 diagnoseTypo(Corrected,
703 PDiag(diag::err_non_template_in_member_template_id_suggest)
704 << Name << LookupCtx << DroppedSpecifier
705 << SS.getRange(), false);
706 } else {
707 diagnoseTypo(Corrected,
708 PDiag(diag::err_non_template_in_template_id_suggest)
709 << Name, false);
710 }
711 if (Found)
712 Diag(Found->getLocation(),
713 diag::note_non_template_in_template_id_found);
714 return;
715 }
716 }
717
718 Diag(NameInfo.getLoc(), diag::err_non_template_in_template_id)
719 << Name << SourceRange(Less, Greater);
720 if (Found)
721 Diag(Found->getLocation(), diag::note_non_template_in_template_id_found);
722}
723
724/// ActOnDependentIdExpression - Handle a dependent id-expression that
725/// was just parsed. This is only possible with an explicit scope
726/// specifier naming a dependent type.
727ExprResult
728Sema::ActOnDependentIdExpression(const CXXScopeSpec &SS,
729 SourceLocation TemplateKWLoc,
730 const DeclarationNameInfo &NameInfo,
731 bool isAddressOfOperand,
732 const TemplateArgumentListInfo *TemplateArgs) {
733 DeclContext *DC = getFunctionLevelDeclContext();
734
735 // C++11 [expr.prim.general]p12:
736 // An id-expression that denotes a non-static data member or non-static
737 // member function of a class can only be used:
738 // (...)
739 // - if that id-expression denotes a non-static data member and it
740 // appears in an unevaluated operand.
741 //
742 // If this might be the case, form a DependentScopeDeclRefExpr instead of a
743 // CXXDependentScopeMemberExpr. The former can instantiate to either
744 // DeclRefExpr or MemberExpr depending on lookup results, while the latter is
745 // always a MemberExpr.
746 bool MightBeCxx11UnevalField =
747 getLangOpts().CPlusPlus11 && isUnevaluatedContext();
748
749 // Check if the nested name specifier is an enum type.
750 bool IsEnum = false;
751 if (NestedNameSpecifier *NNS = SS.getScopeRep())
752 IsEnum = isa_and_nonnull<EnumType>(NNS->getAsType());
753
754 if (!MightBeCxx11UnevalField && !isAddressOfOperand && !IsEnum &&
755 isa<CXXMethodDecl>(DC) && cast<CXXMethodDecl>(DC)->isInstance()) {
756 QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType();
757
758 // Since the 'this' expression is synthesized, we don't need to
759 // perform the double-lookup check.
760 NamedDecl *FirstQualifierInScope = nullptr;
761
762 return CXXDependentScopeMemberExpr::Create(
763 Context, /*This*/ nullptr, ThisType, /*IsArrow*/ true,
764 /*Op*/ SourceLocation(), SS.getWithLocInContext(Context), TemplateKWLoc,
765 FirstQualifierInScope, NameInfo, TemplateArgs);
766 }
767
768 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
769}
770
771ExprResult
772Sema::BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
773 SourceLocation TemplateKWLoc,
774 const DeclarationNameInfo &NameInfo,
775 const TemplateArgumentListInfo *TemplateArgs) {
776 // DependentScopeDeclRefExpr::Create requires a valid QualifierLoc
777 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
778 if (!QualifierLoc)
779 return ExprError();
780
781 return DependentScopeDeclRefExpr::Create(
782 Context, QualifierLoc, TemplateKWLoc, NameInfo, TemplateArgs);
783}
784
785
786/// Determine whether we would be unable to instantiate this template (because
787/// it either has no definition, or is in the process of being instantiated).
788bool Sema::DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
789 NamedDecl *Instantiation,
790 bool InstantiatedFromMember,
791 const NamedDecl *Pattern,
792 const NamedDecl *PatternDef,
793 TemplateSpecializationKind TSK,
794 bool Complain /*= true*/) {
795 assert(isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) ||(static_cast <bool> (isa<TagDecl>(Instantiation) ||
isa<FunctionDecl>(Instantiation) || isa<VarDecl>
(Instantiation)) ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "clang/lib/Sema/SemaTemplate.cpp", 796, __extension__ __PRETTY_FUNCTION__
))
796 isa<VarDecl>(Instantiation))(static_cast <bool> (isa<TagDecl>(Instantiation) ||
isa<FunctionDecl>(Instantiation) || isa<VarDecl>
(Instantiation)) ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) || isa<FunctionDecl>(Instantiation) || isa<VarDecl>(Instantiation)"
, "clang/lib/Sema/SemaTemplate.cpp", 796, __extension__ __PRETTY_FUNCTION__
))
;
797
798 bool IsEntityBeingDefined = false;
799 if (const TagDecl *TD = dyn_cast_or_null<TagDecl>(PatternDef))
800 IsEntityBeingDefined = TD->isBeingDefined();
801
802 if (PatternDef && !IsEntityBeingDefined) {
803 NamedDecl *SuggestedDef = nullptr;
804 if (!hasReachableDefinition(const_cast<NamedDecl *>(PatternDef),
805 &SuggestedDef,
806 /*OnlyNeedComplete*/ false)) {
807 // If we're allowed to diagnose this and recover, do so.
808 bool Recover = Complain && !isSFINAEContext();
809 if (Complain)
810 diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
811 Sema::MissingImportKind::Definition, Recover);
812 return !Recover;
813 }
814 return false;
815 }
816
817 if (!Complain || (PatternDef && PatternDef->isInvalidDecl()))
818 return true;
819
820 llvm::Optional<unsigned> Note;
821 QualType InstantiationTy;
822 if (TagDecl *TD = dyn_cast<TagDecl>(Instantiation))
823 InstantiationTy = Context.getTypeDeclType(TD);
824 if (PatternDef) {
825 Diag(PointOfInstantiation,
826 diag::err_template_instantiate_within_definition)
827 << /*implicit|explicit*/(TSK != TSK_ImplicitInstantiation)
828 << InstantiationTy;
829 // Not much point in noting the template declaration here, since
830 // we're lexically inside it.
831 Instantiation->setInvalidDecl();
832 } else if (InstantiatedFromMember) {
833 if (isa<FunctionDecl>(Instantiation)) {
834 Diag(PointOfInstantiation,
835 diag::err_explicit_instantiation_undefined_member)
836 << /*member function*/ 1 << Instantiation->getDeclName()
837 << Instantiation->getDeclContext();
838 Note = diag::note_explicit_instantiation_here;
839 } else {
840 assert(isa<TagDecl>(Instantiation) && "Must be a TagDecl!")(static_cast <bool> (isa<TagDecl>(Instantiation) &&
"Must be a TagDecl!") ? void (0) : __assert_fail ("isa<TagDecl>(Instantiation) && \"Must be a TagDecl!\""
, "clang/lib/Sema/SemaTemplate.cpp", 840, __extension__ __PRETTY_FUNCTION__
))
;
841 Diag(PointOfInstantiation,
842 diag::err_implicit_instantiate_member_undefined)
843 << InstantiationTy;
844 Note = diag::note_member_declared_at;
845 }
846 } else {
847 if (isa<FunctionDecl>(Instantiation)) {
848 Diag(PointOfInstantiation,
849 diag::err_explicit_instantiation_undefined_func_template)
850 << Pattern;
851 Note = diag::note_explicit_instantiation_here;
852 } else if (isa<TagDecl>(Instantiation)) {
853 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
854 << (TSK != TSK_ImplicitInstantiation)
855 << InstantiationTy;
856 Note = diag::note_template_decl_here;
857 } else {
858 assert(isa<VarDecl>(Instantiation) && "Must be a VarDecl!")(static_cast <bool> (isa<VarDecl>(Instantiation) &&
"Must be a VarDecl!") ? void (0) : __assert_fail ("isa<VarDecl>(Instantiation) && \"Must be a VarDecl!\""
, "clang/lib/Sema/SemaTemplate.cpp", 858, __extension__ __PRETTY_FUNCTION__
))
;
859 if (isa<VarTemplateSpecializationDecl>(Instantiation)) {
860 Diag(PointOfInstantiation,
861 diag::err_explicit_instantiation_undefined_var_template)
862 << Instantiation;
863 Instantiation->setInvalidDecl();
864 } else
865 Diag(PointOfInstantiation,
866 diag::err_explicit_instantiation_undefined_member)
867 << /*static data member*/ 2 << Instantiation->getDeclName()
868 << Instantiation->getDeclContext();
869 Note = diag::note_explicit_instantiation_here;
870 }
871 }
872 if (Note) // Diagnostics were emitted.
873 Diag(Pattern->getLocation(), *Note);
874
875 // In general, Instantiation isn't marked invalid to get more than one
876 // error for multiple undefined instantiations. But the code that does
877 // explicit declaration -> explicit definition conversion can't handle
878 // invalid declarations, so mark as invalid in that case.
879 if (TSK == TSK_ExplicitInstantiationDeclaration)
880 Instantiation->setInvalidDecl();
881 return true;
882}
883
884/// DiagnoseTemplateParameterShadow - Produce a diagnostic complaining
885/// that the template parameter 'PrevDecl' is being shadowed by a new
886/// declaration at location Loc. Returns true to indicate that this is
887/// an error, and false otherwise.
888void Sema::DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl) {
889 assert(PrevDecl->isTemplateParameter() && "Not a template parameter")(static_cast <bool> (PrevDecl->isTemplateParameter()
&& "Not a template parameter") ? void (0) : __assert_fail
("PrevDecl->isTemplateParameter() && \"Not a template parameter\""
, "clang/lib/Sema/SemaTemplate.cpp", 889, __extension__ __PRETTY_FUNCTION__
))
;
890
891 // C++ [temp.local]p4:
892 // A template-parameter shall not be redeclared within its
893 // scope (including nested scopes).
894 //
895 // Make this a warning when MSVC compatibility is requested.
896 unsigned DiagId = getLangOpts().MSVCCompat ? diag::ext_template_param_shadow
897 : diag::err_template_param_shadow;
898 Diag(Loc, DiagId) << cast<NamedDecl>(PrevDecl)->getDeclName();
899 Diag(PrevDecl->getLocation(), diag::note_template_param_here);
900}
901
902/// AdjustDeclIfTemplate - If the given decl happens to be a template, reset
903/// the parameter D to reference the templated declaration and return a pointer
904/// to the template declaration. Otherwise, do nothing to D and return null.
905TemplateDecl *Sema::AdjustDeclIfTemplate(Decl *&D) {
906 if (TemplateDecl *Temp = dyn_cast_or_null<TemplateDecl>(D)) {
907 D = Temp->getTemplatedDecl();
908 return Temp;
909 }
910 return nullptr;
911}
912
913ParsedTemplateArgument ParsedTemplateArgument::getTemplatePackExpansion(
914 SourceLocation EllipsisLoc) const {
915 assert(Kind == Template &&(static_cast <bool> (Kind == Template && "Only template template arguments can be pack expansions here"
) ? void (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "clang/lib/Sema/SemaTemplate.cpp", 916, __extension__ __PRETTY_FUNCTION__
))
916 "Only template template arguments can be pack expansions here")(static_cast <bool> (Kind == Template && "Only template template arguments can be pack expansions here"
) ? void (0) : __assert_fail ("Kind == Template && \"Only template template arguments can be pack expansions here\""
, "clang/lib/Sema/SemaTemplate.cpp", 916, __extension__ __PRETTY_FUNCTION__
))
;
917 assert(getAsTemplate().get().containsUnexpandedParameterPack() &&(static_cast <bool> (getAsTemplate().get().containsUnexpandedParameterPack
() && "Template template argument pack expansion without packs"
) ? void (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "clang/lib/Sema/SemaTemplate.cpp", 918, __extension__ __PRETTY_FUNCTION__
))
918 "Template template argument pack expansion without packs")(static_cast <bool> (getAsTemplate().get().containsUnexpandedParameterPack
() && "Template template argument pack expansion without packs"
) ? void (0) : __assert_fail ("getAsTemplate().get().containsUnexpandedParameterPack() && \"Template template argument pack expansion without packs\""
, "clang/lib/Sema/SemaTemplate.cpp", 918, __extension__ __PRETTY_FUNCTION__
))
;
919 ParsedTemplateArgument Result(*this);
920 Result.EllipsisLoc = EllipsisLoc;
921 return Result;
922}
923
924static TemplateArgumentLoc translateTemplateArgument(Sema &SemaRef,
925 const ParsedTemplateArgument &Arg) {
926
927 switch (Arg.getKind()) {
928 case ParsedTemplateArgument::Type: {
929 TypeSourceInfo *DI;
930 QualType T = SemaRef.GetTypeFromParser(Arg.getAsType(), &DI);
931 if (!DI)
932 DI = SemaRef.Context.getTrivialTypeSourceInfo(T, Arg.getLocation());
933 return TemplateArgumentLoc(TemplateArgument(T), DI);
934 }
935
936 case ParsedTemplateArgument::NonType: {
937 Expr *E = static_cast<Expr *>(Arg.getAsExpr());
938 return TemplateArgumentLoc(TemplateArgument(E), E);
939 }
940
941 case ParsedTemplateArgument::Template: {
942 TemplateName Template = Arg.getAsTemplate().get();
943 TemplateArgument TArg;
944 if (Arg.getEllipsisLoc().isValid())
945 TArg = TemplateArgument(Template, Optional<unsigned int>());
946 else
947 TArg = Template;
948 return TemplateArgumentLoc(
949 SemaRef.Context, TArg,
950 Arg.getScopeSpec().getWithLocInContext(SemaRef.Context),
951 Arg.getLocation(), Arg.getEllipsisLoc());
952 }
953 }
954
955 llvm_unreachable("Unhandled parsed template argument")::llvm::llvm_unreachable_internal("Unhandled parsed template argument"
, "clang/lib/Sema/SemaTemplate.cpp", 955)
;
956}
957
958/// Translates template arguments as provided by the parser
959/// into template arguments used by semantic analysis.
960void Sema::translateTemplateArguments(const ASTTemplateArgsPtr &TemplateArgsIn,
961 TemplateArgumentListInfo &TemplateArgs) {
962 for (unsigned I = 0, Last = TemplateArgsIn.size(); I != Last; ++I)
963 TemplateArgs.addArgument(translateTemplateArgument(*this,
964 TemplateArgsIn[I]));
965}
966
967static void maybeDiagnoseTemplateParameterShadow(Sema &SemaRef, Scope *S,
968 SourceLocation Loc,
969 IdentifierInfo *Name) {
970 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
971 S, Name, Loc, Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
972 if (PrevDecl && PrevDecl->isTemplateParameter())
973 SemaRef.DiagnoseTemplateParameterShadow(Loc, PrevDecl);
974}
975
976/// Convert a parsed type into a parsed template argument. This is mostly
977/// trivial, except that we may have parsed a C++17 deduced class template
978/// specialization type, in which case we should form a template template
979/// argument instead of a type template argument.
980ParsedTemplateArgument Sema::ActOnTemplateTypeArgument(TypeResult ParsedType) {
981 TypeSourceInfo *TInfo;
982 QualType T = GetTypeFromParser(ParsedType.get(), &TInfo);
983 if (T.isNull())
984 return ParsedTemplateArgument();
985 assert(TInfo && "template argument with no location")(static_cast <bool> (TInfo && "template argument with no location"
) ? void (0) : __assert_fail ("TInfo && \"template argument with no location\""
, "clang/lib/Sema/SemaTemplate.cpp", 985, __extension__ __PRETTY_FUNCTION__
))
;
986
987 // If we might have formed a deduced template specialization type, convert
988 // it to a template template argument.
989 if (getLangOpts().CPlusPlus17) {
990 TypeLoc TL = TInfo->getTypeLoc();
991 SourceLocation EllipsisLoc;
992 if (auto PET = TL.getAs<PackExpansionTypeLoc>()) {
993 EllipsisLoc = PET.getEllipsisLoc();
994 TL = PET.getPatternLoc();
995 }
996
997 CXXScopeSpec SS;
998 if (auto ET = TL.getAs<ElaboratedTypeLoc>()) {
999 SS.Adopt(ET.getQualifierLoc());
1000 TL = ET.getNamedTypeLoc();
1001 }
1002
1003 if (auto DTST = TL.getAs<DeducedTemplateSpecializationTypeLoc>()) {
1004 TemplateName Name = DTST.getTypePtr()->getTemplateName();
1005 if (SS.isSet())
1006 Name = Context.getQualifiedTemplateName(SS.getScopeRep(),
1007 /*HasTemplateKeyword=*/false,
1008 Name);
1009 ParsedTemplateArgument Result(SS, TemplateTy::make(Name),
1010 DTST.getTemplateNameLoc());
1011 if (EllipsisLoc.isValid())
1012 Result = Result.getTemplatePackExpansion(EllipsisLoc);
1013 return Result;
1014 }
1015 }
1016
1017 // This is a normal type template argument. Note, if the type template
1018 // argument is an injected-class-name for a template, it has a dual nature
1019 // and can be used as either a type or a template. We handle that in
1020 // convertTypeTemplateArgumentToTemplate.
1021 return ParsedTemplateArgument(ParsedTemplateArgument::Type,
1022 ParsedType.get().getAsOpaquePtr(),
1023 TInfo->getTypeLoc().getBeginLoc());
1024}
1025
1026/// ActOnTypeParameter - Called when a C++ template type parameter
1027/// (e.g., "typename T") has been parsed. Typename specifies whether
1028/// the keyword "typename" was used to declare the type parameter
1029/// (otherwise, "class" was used), and KeyLoc is the location of the
1030/// "class" or "typename" keyword. ParamName is the name of the
1031/// parameter (NULL indicates an unnamed template parameter) and
1032/// ParamNameLoc is the location of the parameter name (if any).
1033/// If the type parameter has a default argument, it will be added
1034/// later via ActOnTypeParameterDefault.
1035NamedDecl *Sema::ActOnTypeParameter(Scope *S, bool Typename,
1036 SourceLocation EllipsisLoc,
1037 SourceLocation KeyLoc,
1038 IdentifierInfo *ParamName,
1039 SourceLocation ParamNameLoc,
1040 unsigned Depth, unsigned Position,
1041 SourceLocation EqualLoc,
1042 ParsedType DefaultArg,
1043 bool HasTypeConstraint) {
1044 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"Template type parameter not in template parameter scope!") ?
void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "clang/lib/Sema/SemaTemplate.cpp", 1045, __extension__ __PRETTY_FUNCTION__
))
1045 "Template type parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() &&
"Template type parameter not in template parameter scope!") ?
void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template type parameter not in template parameter scope!\""
, "clang/lib/Sema/SemaTemplate.cpp", 1045, __extension__ __PRETTY_FUNCTION__
))
;
1046
1047 bool IsParameterPack = EllipsisLoc.isValid();
1048 TemplateTypeParmDecl *Param
1049 = TemplateTypeParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1050 KeyLoc, ParamNameLoc, Depth, Position,
1051 ParamName, Typename, IsParameterPack,
1052 HasTypeConstraint);
1053 Param->setAccess(AS_public);
1054
1055 if (Param->isParameterPack())
1056 if (auto *LSI = getEnclosingLambda())
1057 LSI->LocalPacks.push_back(Param);
1058
1059 if (ParamName) {
1060 maybeDiagnoseTemplateParameterShadow(*this, S, ParamNameLoc, ParamName);
1061
1062 // Add the template parameter into the current scope.
1063 S->AddDecl(Param);
1064 IdResolver.AddDecl(Param);
1065 }
1066
1067 // C++0x [temp.param]p9:
1068 // A default template-argument may be specified for any kind of
1069 // template-parameter that is not a template parameter pack.
1070 if (DefaultArg && IsParameterPack) {
1071 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1072 DefaultArg = nullptr;
1073 }
1074
1075 // Handle the default argument, if provided.
1076 if (DefaultArg) {
1077 TypeSourceInfo *DefaultTInfo;
1078 GetTypeFromParser(DefaultArg, &DefaultTInfo);
1079
1080 assert(DefaultTInfo && "expected source information for type")(static_cast <bool> (DefaultTInfo && "expected source information for type"
) ? void (0) : __assert_fail ("DefaultTInfo && \"expected source information for type\""
, "clang/lib/Sema/SemaTemplate.cpp", 1080, __extension__ __PRETTY_FUNCTION__
))
;
1081
1082 // Check for unexpanded parameter packs.
1083 if (DiagnoseUnexpandedParameterPack(ParamNameLoc, DefaultTInfo,
1084 UPPC_DefaultArgument))
1085 return Param;
1086
1087 // Check the template argument itself.
1088 if (CheckTemplateArgument(DefaultTInfo)) {
1089 Param->setInvalidDecl();
1090 return Param;
1091 }
1092
1093 Param->setDefaultArgument(DefaultTInfo);
1094 }
1095
1096 return Param;
1097}
1098
1099/// Convert the parser's template argument list representation into our form.
1100static TemplateArgumentListInfo
1101makeTemplateArgumentListInfo(Sema &S, TemplateIdAnnotation &TemplateId) {
1102 TemplateArgumentListInfo TemplateArgs(TemplateId.LAngleLoc,
1103 TemplateId.RAngleLoc);
1104 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId.getTemplateArgs(),
1105 TemplateId.NumArgs);
1106 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgs);
1107 return TemplateArgs;
1108}
1109
1110bool Sema::ActOnTypeConstraint(const CXXScopeSpec &SS,
1111 TemplateIdAnnotation *TypeConstr,
1112 TemplateTypeParmDecl *ConstrainedParameter,
1113 SourceLocation EllipsisLoc) {
1114 return BuildTypeConstraint(SS, TypeConstr, ConstrainedParameter, EllipsisLoc,
1115 false);
1116}
1117
1118bool Sema::BuildTypeConstraint(const CXXScopeSpec &SS,
1119 TemplateIdAnnotation *TypeConstr,
1120 TemplateTypeParmDecl *ConstrainedParameter,
1121 SourceLocation EllipsisLoc,
1122 bool AllowUnexpandedPack) {
1123 TemplateName TN = TypeConstr->Template.get();
1124 ConceptDecl *CD = cast<ConceptDecl>(TN.getAsTemplateDecl());
1125
1126 // C++2a [temp.param]p4:
1127 // [...] The concept designated by a type-constraint shall be a type
1128 // concept ([temp.concept]).
1129 if (!CD->isTypeConcept()) {
1130 Diag(TypeConstr->TemplateNameLoc,
1131 diag::err_type_constraint_non_type_concept);
1132 return true;
1133 }
1134
1135 bool WereArgsSpecified = TypeConstr->LAngleLoc.isValid();
1136
1137 if (!WereArgsSpecified &&
1138 CD->getTemplateParameters()->getMinRequiredArguments() > 1) {
1139 Diag(TypeConstr->TemplateNameLoc,
1140 diag::err_type_constraint_missing_arguments) << CD;
1141 return true;
1142 }
1143
1144 DeclarationNameInfo ConceptName(DeclarationName(TypeConstr->Name),
1145 TypeConstr->TemplateNameLoc);
1146
1147 TemplateArgumentListInfo TemplateArgs;
1148 if (TypeConstr->LAngleLoc.isValid()) {
1149 TemplateArgs =
1150 makeTemplateArgumentListInfo(*this, *TypeConstr);
1151
1152 if (EllipsisLoc.isInvalid() && !AllowUnexpandedPack) {
1153 for (TemplateArgumentLoc Arg : TemplateArgs.arguments()) {
1154 if (DiagnoseUnexpandedParameterPack(Arg, UPPC_TypeConstraint))
1155 return true;
1156 }
1157 }
1158 }
1159 return AttachTypeConstraint(
1160 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1161 ConceptName, CD,
1162 TypeConstr->LAngleLoc.isValid() ? &TemplateArgs : nullptr,
1163 ConstrainedParameter, EllipsisLoc);
1164}
1165
1166template<typename ArgumentLocAppender>
1167static ExprResult formImmediatelyDeclaredConstraint(
1168 Sema &S, NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo,
1169 ConceptDecl *NamedConcept, SourceLocation LAngleLoc,
1170 SourceLocation RAngleLoc, QualType ConstrainedType,
1171 SourceLocation ParamNameLoc, ArgumentLocAppender Appender,
1172 SourceLocation EllipsisLoc) {
1173
1174 TemplateArgumentListInfo ConstraintArgs;
1175 ConstraintArgs.addArgument(
1176 S.getTrivialTemplateArgumentLoc(TemplateArgument(ConstrainedType),
1177 /*NTTPType=*/QualType(), ParamNameLoc));
1178
1179 ConstraintArgs.setRAngleLoc(RAngleLoc);
1180 ConstraintArgs.setLAngleLoc(LAngleLoc);
1181 Appender(ConstraintArgs);
1182
1183 // C++2a [temp.param]p4:
1184 // [...] This constraint-expression E is called the immediately-declared
1185 // constraint of T. [...]
1186 CXXScopeSpec SS;
1187 SS.Adopt(NS);
1188 ExprResult ImmediatelyDeclaredConstraint = S.CheckConceptTemplateId(
1189 SS, /*TemplateKWLoc=*/SourceLocation(), NameInfo,
1190 /*FoundDecl=*/NamedConcept, NamedConcept, &ConstraintArgs);
1191 if (ImmediatelyDeclaredConstraint.isInvalid() || !EllipsisLoc.isValid())
1192 return ImmediatelyDeclaredConstraint;
1193
1194 // C++2a [temp.param]p4:
1195 // [...] If T is not a pack, then E is E', otherwise E is (E' && ...).
1196 //
1197 // We have the following case:
1198 //
1199 // template<typename T> concept C1 = true;
1200 // template<C1... T> struct s1;
1201 //
1202 // The constraint: (C1<T> && ...)
1203 //
1204 // Note that the type of C1<T> is known to be 'bool', so we don't need to do
1205 // any unqualified lookups for 'operator&&' here.
1206 return S.BuildCXXFoldExpr(/*UnqualifiedLookup=*/nullptr,
1207 /*LParenLoc=*/SourceLocation(),
1208 ImmediatelyDeclaredConstraint.get(), BO_LAnd,
1209 EllipsisLoc, /*RHS=*/nullptr,
1210 /*RParenLoc=*/SourceLocation(),
1211 /*NumExpansions=*/None);
1212}
1213
1214/// Attach a type-constraint to a template parameter.
1215/// \returns true if an error occurred. This can happen if the
1216/// immediately-declared constraint could not be formed (e.g. incorrect number
1217/// of arguments for the named concept).
1218bool Sema::AttachTypeConstraint(NestedNameSpecifierLoc NS,
1219 DeclarationNameInfo NameInfo,
1220 ConceptDecl *NamedConcept,
1221 const TemplateArgumentListInfo *TemplateArgs,
1222 TemplateTypeParmDecl *ConstrainedParameter,
1223 SourceLocation EllipsisLoc) {
1224 // C++2a [temp.param]p4:
1225 // [...] If Q is of the form C<A1, ..., An>, then let E' be
1226 // C<T, A1, ..., An>. Otherwise, let E' be C<T>. [...]
1227 const ASTTemplateArgumentListInfo *ArgsAsWritten =
1228 TemplateArgs ? ASTTemplateArgumentListInfo::Create(Context,
1229 *TemplateArgs) : nullptr;
1230
1231 QualType ParamAsArgument(ConstrainedParameter->getTypeForDecl(), 0);
1232
1233 ExprResult ImmediatelyDeclaredConstraint =
1234 formImmediatelyDeclaredConstraint(
1235 *this, NS, NameInfo, NamedConcept,
1236 TemplateArgs ? TemplateArgs->getLAngleLoc() : SourceLocation(),
1237 TemplateArgs ? TemplateArgs->getRAngleLoc() : SourceLocation(),
1238 ParamAsArgument, ConstrainedParameter->getLocation(),
1239 [&] (TemplateArgumentListInfo &ConstraintArgs) {
1240 if (TemplateArgs)
1241 for (const auto &ArgLoc : TemplateArgs->arguments())
1242 ConstraintArgs.addArgument(ArgLoc);
1243 }, EllipsisLoc);
1244 if (ImmediatelyDeclaredConstraint.isInvalid())
1245 return true;
1246
1247 ConstrainedParameter->setTypeConstraint(NS, NameInfo,
1248 /*FoundDecl=*/NamedConcept,
1249 NamedConcept, ArgsAsWritten,
1250 ImmediatelyDeclaredConstraint.get());
1251 return false;
1252}
1253
1254bool Sema::AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *NTTP,
1255 SourceLocation EllipsisLoc) {
1256 if (NTTP->getType() != TL.getType() ||
1257 TL.getAutoKeyword() != AutoTypeKeyword::Auto) {
1258 Diag(NTTP->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
1259 diag::err_unsupported_placeholder_constraint)
1260 << NTTP->getTypeSourceInfo()->getTypeLoc().getSourceRange();
1261 return true;
1262 }
1263 // FIXME: Concepts: This should be the type of the placeholder, but this is
1264 // unclear in the wording right now.
1265 DeclRefExpr *Ref =
1266 BuildDeclRefExpr(NTTP, NTTP->getType(), VK_PRValue, NTTP->getLocation());
1267 if (!Ref)
1268 return true;
1269 ExprResult ImmediatelyDeclaredConstraint = formImmediatelyDeclaredConstraint(
1270 *this, TL.getNestedNameSpecifierLoc(), TL.getConceptNameInfo(),
1271 TL.getNamedConcept(), TL.getLAngleLoc(), TL.getRAngleLoc(),
1272 BuildDecltypeType(Ref), NTTP->getLocation(),
1273 [&](TemplateArgumentListInfo &ConstraintArgs) {
1274 for (unsigned I = 0, C = TL.getNumArgs(); I != C; ++I)
1275 ConstraintArgs.addArgument(TL.getArgLoc(I));
1276 },
1277 EllipsisLoc);
1278 if (ImmediatelyDeclaredConstraint.isInvalid() ||
1279 !ImmediatelyDeclaredConstraint.isUsable())
1280 return true;
1281
1282 NTTP->setPlaceholderTypeConstraint(ImmediatelyDeclaredConstraint.get());
1283 return false;
1284}
1285
1286/// Check that the type of a non-type template parameter is
1287/// well-formed.
1288///
1289/// \returns the (possibly-promoted) parameter type if valid;
1290/// otherwise, produces a diagnostic and returns a NULL type.
1291QualType Sema::CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
1292 SourceLocation Loc) {
1293 if (TSI->getType()->isUndeducedType()) {
1294 // C++17 [temp.dep.expr]p3:
1295 // An id-expression is type-dependent if it contains
1296 // - an identifier associated by name lookup with a non-type
1297 // template-parameter declared with a type that contains a
1298 // placeholder type (7.1.7.4),
1299 TSI = SubstAutoTypeSourceInfoDependent(TSI);
1300 }
1301
1302 return CheckNonTypeTemplateParameterType(TSI->getType(), Loc);
1303}
1304
1305/// Require the given type to be a structural type, and diagnose if it is not.
1306///
1307/// \return \c true if an error was produced.
1308bool Sema::RequireStructuralType(QualType T, SourceLocation Loc) {
1309 if (T->isDependentType())
1310 return false;
1311
1312 if (RequireCompleteType(Loc, T, diag::err_template_nontype_parm_incomplete))
1313 return true;
1314
1315 if (T->isStructuralType())
1316 return false;
1317
1318 // Structural types are required to be object types or lvalue references.
1319 if (T->isRValueReferenceType()) {
1320 Diag(Loc, diag::err_template_nontype_parm_rvalue_ref) << T;
1321 return true;
1322 }
1323
1324 // Don't mention structural types in our diagnostic prior to C++20. Also,
1325 // there's not much more we can say about non-scalar non-class types --
1326 // because we can't see functions or arrays here, those can only be language
1327 // extensions.
1328 if (!getLangOpts().CPlusPlus20 ||
1329 (!T->isScalarType() && !T->isRecordType())) {
1330 Diag(Loc, diag::err_template_nontype_parm_bad_type) << T;
1331 return true;
1332 }
1333
1334 // Structural types are required to be literal types.
1335 if (RequireLiteralType(Loc, T, diag::err_template_nontype_parm_not_literal))
1336 return true;
1337
1338 Diag(Loc, diag::err_template_nontype_parm_not_structural) << T;
1339
1340 // Drill down into the reason why the class is non-structural.
1341 while (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
1342 // All members are required to be public and non-mutable, and can't be of
1343 // rvalue reference type. Check these conditions first to prefer a "local"
1344 // reason over a more distant one.
1345 for (const FieldDecl *FD : RD->fields()) {
1346 if (FD->getAccess() != AS_public) {
1347 Diag(FD->getLocation(), diag::note_not_structural_non_public) << T << 0;
1348 return true;
1349 }
1350 if (FD->isMutable()) {
1351 Diag(FD->getLocation(), diag::note_not_structural_mutable_field) << T;
1352 return true;
1353 }
1354 if (FD->getType()->isRValueReferenceType()) {
1355 Diag(FD->getLocation(), diag::note_not_structural_rvalue_ref_field)
1356 << T;
1357 return true;
1358 }
1359 }
1360
1361 // All bases are required to be public.
1362 for (const auto &BaseSpec : RD->bases()) {
1363 if (BaseSpec.getAccessSpecifier() != AS_public) {
1364 Diag(BaseSpec.getBaseTypeLoc(), diag::note_not_structural_non_public)
1365 << T << 1;
1366 return true;
1367 }
1368 }
1369
1370 // All subobjects are required to be of structural types.
1371 SourceLocation SubLoc;
1372 QualType SubType;
1373 int Kind = -1;
1374
1375 for (const FieldDecl *FD : RD->fields()) {
1376 QualType T = Context.getBaseElementType(FD->getType());
1377 if (!T->isStructuralType()) {
1378 SubLoc = FD->getLocation();
1379 SubType = T;
1380 Kind = 0;
1381 break;
1382 }
1383 }
1384
1385 if (Kind == -1) {
1386 for (const auto &BaseSpec : RD->bases()) {
1387 QualType T = BaseSpec.getType();
1388 if (!T->isStructuralType()) {
1389 SubLoc = BaseSpec.getBaseTypeLoc();
1390 SubType = T;
1391 Kind = 1;
1392 break;
1393 }
1394 }
1395 }
1396
1397 assert(Kind != -1 && "couldn't find reason why type is not structural")(static_cast <bool> (Kind != -1 && "couldn't find reason why type is not structural"
) ? void (0) : __assert_fail ("Kind != -1 && \"couldn't find reason why type is not structural\""
, "clang/lib/Sema/SemaTemplate.cpp", 1397, __extension__ __PRETTY_FUNCTION__
))
;
1398 Diag(SubLoc, diag::note_not_structural_subobject)
1399 << T << Kind << SubType;
1400 T = SubType;
1401 RD = T->getAsCXXRecordDecl();
Value stored to 'RD' is never read
1402 }
1403
1404 return true;
1405}
1406
1407QualType Sema::CheckNonTypeTemplateParameterType(QualType T,
1408 SourceLocation Loc) {
1409 // We don't allow variably-modified types as the type of non-type template
1410 // parameters.
1411 if (T->isVariablyModifiedType()) {
1412 Diag(Loc, diag::err_variably_modified_nontype_template_param)
1413 << T;
1414 return QualType();
1415 }
1416
1417 // C++ [temp.param]p4:
1418 //
1419 // A non-type template-parameter shall have one of the following
1420 // (optionally cv-qualified) types:
1421 //
1422 // -- integral or enumeration type,
1423 if (T->isIntegralOrEnumerationType() ||
1424 // -- pointer to object or pointer to function,
1425 T->isPointerType() ||
1426 // -- lvalue reference to object or lvalue reference to function,
1427 T->isLValueReferenceType() ||
1428 // -- pointer to member,
1429 T->isMemberPointerType() ||
1430 // -- std::nullptr_t, or
1431 T->isNullPtrType() ||
1432 // -- a type that contains a placeholder type.
1433 T->isUndeducedType()) {
1434 // C++ [temp.param]p5: The top-level cv-qualifiers on the template-parameter
1435 // are ignored when determining its type.
1436 return T.getUnqualifiedType();
1437 }
1438
1439 // C++ [temp.param]p8:
1440 //
1441 // A non-type template-parameter of type "array of T" or
1442 // "function returning T" is adjusted to be of type "pointer to
1443 // T" or "pointer to function returning T", respectively.
1444 if (T->isArrayType() || T->isFunctionType())
1445 return Context.getDecayedType(T);
1446
1447 // If T is a dependent type, we can't do the check now, so we
1448 // assume that it is well-formed. Note that stripping off the
1449 // qualifiers here is not really correct if T turns out to be
1450 // an array type, but we'll recompute the type everywhere it's
1451 // used during instantiation, so that should be OK. (Using the
1452 // qualified type is equally wrong.)
1453 if (T->isDependentType())
1454 return T.getUnqualifiedType();
1455
1456 // C++20 [temp.param]p6:
1457 // -- a structural type
1458 if (RequireStructuralType(T, Loc))
1459 return QualType();
1460
1461 if (!getLangOpts().CPlusPlus20) {
1462 // FIXME: Consider allowing structural types as an extension in C++17. (In
1463 // earlier language modes, the template argument evaluation rules are too
1464 // inflexible.)
1465 Diag(Loc, diag::err_template_nontype_parm_bad_structural_type) << T;
1466 return QualType();
1467 }
1468
1469 Diag(Loc, diag::warn_cxx17_compat_template_nontype_parm_type) << T;
1470 return T.getUnqualifiedType();
1471}
1472
1473NamedDecl *Sema::ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
1474 unsigned Depth,
1475 unsigned Position,
1476 SourceLocation EqualLoc,
1477 Expr *Default) {
1478 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
1479
1480 // Check that we have valid decl-specifiers specified.
1481 auto CheckValidDeclSpecifiers = [this, &D] {
1482 // C++ [temp.param]
1483 // p1
1484 // template-parameter:
1485 // ...
1486 // parameter-declaration
1487 // p2
1488 // ... A storage class shall not be specified in a template-parameter
1489 // declaration.
1490 // [dcl.typedef]p1:
1491 // The typedef specifier [...] shall not be used in the decl-specifier-seq
1492 // of a parameter-declaration
1493 const DeclSpec &DS = D.getDeclSpec();
1494 auto EmitDiag = [this](SourceLocation Loc) {
1495 Diag(Loc, diag::err_invalid_decl_specifier_in_nontype_parm)
1496 << FixItHint::CreateRemoval(Loc);
1497 };
1498 if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified)
1499 EmitDiag(DS.getStorageClassSpecLoc());
1500
1501 if (DS.getThreadStorageClassSpec() != TSCS_unspecified)
1502 EmitDiag(DS.getThreadStorageClassSpecLoc());
1503
1504 // [dcl.inline]p1:
1505 // The inline specifier can be applied only to the declaration or
1506 // definition of a variable or function.
1507
1508 if (DS.isInlineSpecified())
1509 EmitDiag(DS.getInlineSpecLoc());
1510
1511 // [dcl.constexpr]p1:
1512 // The constexpr specifier shall be applied only to the definition of a
1513 // variable or variable template or the declaration of a function or
1514 // function template.
1515
1516 if (DS.hasConstexprSpecifier())
1517 EmitDiag(DS.getConstexprSpecLoc());
1518
1519 // [dcl.fct.spec]p1:
1520 // Function-specifiers can be used only in function declarations.
1521
1522 if (DS.isVirtualSpecified())
1523 EmitDiag(DS.getVirtualSpecLoc());
1524
1525 if (DS.hasExplicitSpecifier())
1526 EmitDiag(DS.getExplicitSpecLoc());
1527
1528 if (DS.isNoreturnSpecified())
1529 EmitDiag(DS.getNoreturnSpecLoc());
1530 };
1531
1532 CheckValidDeclSpecifiers();
1533
1534 if (TInfo->getType()->isUndeducedType()) {
1535 Diag(D.getIdentifierLoc(),
1536 diag::warn_cxx14_compat_template_nontype_parm_auto_type)
1537 << QualType(TInfo->getType()->getContainedAutoType(), 0);
1538 }
1539
1540 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"Non-type template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "clang/lib/Sema/SemaTemplate.cpp", 1541, __extension__ __PRETTY_FUNCTION__
))
1541 "Non-type template parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() &&
"Non-type template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Non-type template parameter not in template parameter scope!\""
, "clang/lib/Sema/SemaTemplate.cpp", 1541, __extension__ __PRETTY_FUNCTION__
))
;
1542 bool Invalid = false;
1543
1544 QualType T = CheckNonTypeTemplateParameterType(TInfo, D.getIdentifierLoc());
1545 if (T.isNull()) {
1546 T = Context.IntTy; // Recover with an 'int' type.
1547 Invalid = true;
1548 }
1549
1550 CheckFunctionOrTemplateParamDeclarator(S, D);
1551
1552 IdentifierInfo *ParamName = D.getIdentifier();
1553 bool IsParameterPack = D.hasEllipsis();
1554 NonTypeTemplateParmDecl *Param = NonTypeTemplateParmDecl::Create(
1555 Context, Context.getTranslationUnitDecl(), D.getBeginLoc(),
1556 D.getIdentifierLoc(), Depth, Position, ParamName, T, IsParameterPack,
1557 TInfo);
1558 Param->setAccess(AS_public);
1559
1560 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc())
1561 if (TL.isConstrained())
1562 if (AttachTypeConstraint(TL, Param, D.getEllipsisLoc()))
1563 Invalid = true;
1564
1565 if (Invalid)
1566 Param->setInvalidDecl();
1567
1568 if (Param->isParameterPack())
1569 if (auto *LSI = getEnclosingLambda())
1570 LSI->LocalPacks.push_back(Param);
1571
1572 if (ParamName) {
1573 maybeDiagnoseTemplateParameterShadow(*this, S, D.getIdentifierLoc(),
1574 ParamName);
1575
1576 // Add the template parameter into the current scope.
1577 S->AddDecl(Param);
1578 IdResolver.AddDecl(Param);
1579 }
1580
1581 // C++0x [temp.param]p9:
1582 // A default template-argument may be specified for any kind of
1583 // template-parameter that is not a template parameter pack.
1584 if (Default && IsParameterPack) {
1585 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1586 Default = nullptr;
1587 }
1588
1589 // Check the well-formedness of the default template argument, if provided.
1590 if (Default) {
1591 // Check for unexpanded parameter packs.
1592 if (DiagnoseUnexpandedParameterPack(Default, UPPC_DefaultArgument))
1593 return Param;
1594
1595 TemplateArgument Converted;
1596 ExprResult DefaultRes =
1597 CheckTemplateArgument(Param, Param->getType(), Default, Converted);
1598 if (DefaultRes.isInvalid()) {
1599 Param->setInvalidDecl();
1600 return Param;
1601 }
1602 Default = DefaultRes.get();
1603
1604 Param->setDefaultArgument(Default);
1605 }
1606
1607 return Param;
1608}
1609
1610/// ActOnTemplateTemplateParameter - Called when a C++ template template
1611/// parameter (e.g. T in template <template \<typename> class T> class array)
1612/// has been parsed. S is the current scope.
1613NamedDecl *Sema::ActOnTemplateTemplateParameter(Scope* S,
1614 SourceLocation TmpLoc,
1615 TemplateParameterList *Params,
1616 SourceLocation EllipsisLoc,
1617 IdentifierInfo *Name,
1618 SourceLocation NameLoc,
1619 unsigned Depth,
1620 unsigned Position,
1621 SourceLocation EqualLoc,
1622 ParsedTemplateArgument Default) {
1623 assert(S->isTemplateParamScope() &&(static_cast <bool> (S->isTemplateParamScope() &&
"Template template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "clang/lib/Sema/SemaTemplate.cpp", 1624, __extension__ __PRETTY_FUNCTION__
))
1624 "Template template parameter not in template parameter scope!")(static_cast <bool> (S->isTemplateParamScope() &&
"Template template parameter not in template parameter scope!"
) ? void (0) : __assert_fail ("S->isTemplateParamScope() && \"Template template parameter not in template parameter scope!\""
, "clang/lib/Sema/SemaTemplate.cpp", 1624, __extension__ __PRETTY_FUNCTION__
))
;
1625
1626 // Construct the parameter object.
1627 bool IsParameterPack = EllipsisLoc.isValid();
1628 TemplateTemplateParmDecl *Param =
1629 TemplateTemplateParmDecl::Create(Context, Context.getTranslationUnitDecl(),
1630 NameLoc.isInvalid()? TmpLoc : NameLoc,
1631 Depth, Position, IsParameterPack,
1632 Name, Params);
1633 Param->setAccess(AS_public);
1634
1635 if (Param->isParameterPack())
1636 if (auto *LSI = getEnclosingLambda())
1637 LSI->LocalPacks.push_back(Param);
1638
1639 // If the template template parameter has a name, then link the identifier
1640 // into the scope and lookup mechanisms.
1641 if (Name) {
1642 maybeDiagnoseTemplateParameterShadow(*this, S, NameLoc, Name);
1643
1644 S->AddDecl(Param);
1645 IdResolver.AddDecl(Param);
1646 }
1647
1648 if (Params->size() == 0) {
1649 Diag(Param->getLocation(), diag::err_template_template_parm_no_parms)
1650 << SourceRange(Params->getLAngleLoc(), Params->getRAngleLoc());
1651 Param->setInvalidDecl();
1652 }
1653
1654 // C++0x [temp.param]p9:
1655 // A default template-argument may be specified for any kind of
1656 // template-parameter that is not a template parameter pack.
1657 if (IsParameterPack && !Default.isInvalid()) {
1658 Diag(EqualLoc, diag::err_template_param_pack_default_arg);
1659 Default = ParsedTemplateArgument();
1660 }
1661
1662 if (!Default.isInvalid()) {
1663 // Check only that we have a template template argument. We don't want to
1664 // try to check well-formedness now, because our template template parameter
1665 // might have dependent types in its template parameters, which we wouldn't
1666 // be able to match now.
1667 //
1668 // If none of the template template parameter's template arguments mention
1669 // other template parameters, we could actually perform more checking here.
1670 // However, it isn't worth doing.
1671 TemplateArgumentLoc DefaultArg = translateTemplateArgument(*this, Default);
1672 if (DefaultArg.getArgument().getAsTemplate().isNull()) {
1673 Diag(DefaultArg.getLocation(), diag::err_template_arg_not_valid_template)
1674 << DefaultArg.getSourceRange();
1675 return Param;
1676 }
1677
1678 // Check for unexpanded parameter packs.
1679 if (DiagnoseUnexpandedParameterPack(DefaultArg.getLocation(),
1680 DefaultArg.getArgument().getAsTemplate(),
1681 UPPC_DefaultArgument))
1682 return Param;
1683
1684 Param->setDefaultArgument(Context, DefaultArg);
1685 }
1686
1687 return Param;
1688}
1689
1690/// ActOnTemplateParameterList - Builds a TemplateParameterList, optionally
1691/// constrained by RequiresClause, that contains the template parameters in
1692/// Params.
1693TemplateParameterList *
1694Sema::ActOnTemplateParameterList(unsigned Depth,
1695 SourceLocation ExportLoc,
1696 SourceLocation TemplateLoc,
1697 SourceLocation LAngleLoc,
1698 ArrayRef<NamedDecl *> Params,
1699 SourceLocation RAngleLoc,
1700 Expr *RequiresClause) {
1701 if (ExportLoc.isValid())
1702 Diag(ExportLoc, diag::warn_template_export_unsupported);
1703
1704 for (NamedDecl *P : Params)
1705 warnOnReservedIdentifier(P);
1706
1707 return TemplateParameterList::Create(
1708 Context, TemplateLoc, LAngleLoc,
1709 llvm::makeArrayRef(Params.data(), Params.size()),
1710 RAngleLoc, RequiresClause);
1711}
1712
1713static void SetNestedNameSpecifier(Sema &S, TagDecl *T,
1714 const CXXScopeSpec &SS) {
1715 if (SS.isSet())
1716 T->setQualifierInfo(SS.getWithLocInContext(S.Context));
1717}
1718
1719DeclResult Sema::CheckClassTemplate(
1720 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
1721 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
1722 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
1723 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
1724 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
1725 TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody) {
1726 assert(TemplateParams && TemplateParams->size() > 0 &&(static_cast <bool> (TemplateParams && TemplateParams
->size() > 0 && "No template parameters") ? void
(0) : __assert_fail ("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "clang/lib/Sema/SemaTemplate.cpp", 1727, __extension__ __PRETTY_FUNCTION__
))
1727 "No template parameters")(static_cast <bool> (TemplateParams && TemplateParams
->size() > 0 && "No template parameters") ? void
(0) : __assert_fail ("TemplateParams && TemplateParams->size() > 0 && \"No template parameters\""
, "clang/lib/Sema/SemaTemplate.cpp", 1727, __extension__ __PRETTY_FUNCTION__
))
;
1728 assert(TUK != TUK_Reference && "Can only declare or define class templates")(static_cast <bool> (TUK != TUK_Reference && "Can only declare or define class templates"
) ? void (0) : __assert_fail ("TUK != TUK_Reference && \"Can only declare or define class templates\""
, "clang/lib/Sema/SemaTemplate.cpp", 1728, __extension__ __PRETTY_FUNCTION__
))
;
1729 bool Invalid = false;
1730
1731 // Check that we can declare a template here.
1732 if (CheckTemplateDeclScope(S, TemplateParams))
1733 return true;
1734
1735 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
1736 assert(Kind != TTK_Enum && "can't build template of enumerated type")(static_cast <bool> (Kind != TTK_Enum && "can't build template of enumerated type"
) ? void (0) : __assert_fail ("Kind != TTK_Enum && \"can't build template of enumerated type\""
, "clang/lib/Sema/SemaTemplate.cpp", 1736, __extension__ __PRETTY_FUNCTION__
))
;
1737
1738 // There is no such thing as an unnamed class template.
1739 if (!Name) {
1740 Diag(KWLoc, diag::err_template_unnamed_class);
1741 return true;
1742 }
1743
1744 // Find any previous declaration with this name. For a friend with no
1745 // scope explicitly specified, we only look for tag declarations (per
1746 // C++11 [basic.lookup.elab]p2).
1747 DeclContext *SemanticContext;
1748 LookupResult Previous(*this, Name, NameLoc,
1749 (SS.isEmpty() && TUK == TUK_Friend)
1750 ? LookupTagName : LookupOrdinaryName,
1751 forRedeclarationInCurContext());
1752 if (SS.isNotEmpty() && !SS.isInvalid()) {
1753 SemanticContext = computeDeclContext(SS, true);
1754 if (!SemanticContext) {
1755 // FIXME: Horrible, horrible hack! We can't currently represent this
1756 // in the AST, and historically we have just ignored such friend
1757 // class templates, so don't complain here.
1758 Diag(NameLoc, TUK == TUK_Friend
1759 ? diag::warn_template_qualified_friend_ignored
1760 : diag::err_template_qualified_declarator_no_match)
1761 << SS.getScopeRep() << SS.getRange();
1762 return TUK != TUK_Friend;
1763 }
1764
1765 if (RequireCompleteDeclContext(SS, SemanticContext))
1766 return true;
1767
1768 // If we're adding a template to a dependent context, we may need to
1769 // rebuilding some of the types used within the template parameter list,
1770 // now that we know what the current instantiation is.
1771 if (SemanticContext->isDependentContext()) {
1772 ContextRAII SavedContext(*this, SemanticContext);
1773 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
1774 Invalid = true;
1775 } else if (TUK != TUK_Friend && TUK != TUK_Reference)
1776 diagnoseQualifiedDeclaration(SS, SemanticContext, Name, NameLoc, false);
1777
1778 LookupQualifiedName(Previous, SemanticContext);
1779 } else {
1780 SemanticContext = CurContext;
1781
1782 // C++14 [class.mem]p14:
1783 // If T is the name of a class, then each of the following shall have a
1784 // name different from T:
1785 // -- every member template of class T
1786 if (TUK != TUK_Friend &&
1787 DiagnoseClassNameShadow(SemanticContext,
1788 DeclarationNameInfo(Name, NameLoc)))
1789 return true;
1790
1791 LookupName(Previous, S);
1792 }
1793
1794 if (Previous.isAmbiguous())
1795 return true;
1796
1797 NamedDecl *PrevDecl = nullptr;
1798 if (Previous.begin() != Previous.end())
1799 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1800
1801 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1802 // Maybe we will complain about the shadowed template parameter.
1803 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
1804 // Just pretend that we didn't see the previous declaration.
1805 PrevDecl = nullptr;
1806 }
1807
1808 // If there is a previous declaration with the same name, check
1809 // whether this is a valid redeclaration.
1810 ClassTemplateDecl *PrevClassTemplate =
1811 dyn_cast_or_null<ClassTemplateDecl>(PrevDecl);
1812
1813 // We may have found the injected-class-name of a class template,
1814 // class template partial specialization, or class template specialization.
1815 // In these cases, grab the template that is being defined or specialized.
1816 if (!PrevClassTemplate && PrevDecl && isa<CXXRecordDecl>(PrevDecl) &&
1817 cast<CXXRecordDecl>(PrevDecl)->isInjectedClassName()) {
1818 PrevDecl = cast<CXXRecordDecl>(PrevDecl->getDeclContext());
1819 PrevClassTemplate
1820 = cast<CXXRecordDecl>(PrevDecl)->getDescribedClassTemplate();
1821 if (!PrevClassTemplate && isa<ClassTemplateSpecializationDecl>(PrevDecl)) {
1822 PrevClassTemplate
1823 = cast<ClassTemplateSpecializationDecl>(PrevDecl)
1824 ->getSpecializedTemplate();
1825 }
1826 }
1827
1828 if (TUK == TUK_Friend) {
1829 // C++ [namespace.memdef]p3:
1830 // [...] When looking for a prior declaration of a class or a function
1831 // declared as a friend, and when the name of the friend class or
1832 // function is neither a qualified name nor a template-id, scopes outside
1833 // the innermost enclosing namespace scope are not considered.
1834 if (!SS.isSet()) {
1835 DeclContext *OutermostContext = CurContext;
1836 while (!OutermostContext->isFileContext())
1837 OutermostContext = OutermostContext->getLookupParent();
1838
1839 if (PrevDecl &&
1840 (OutermostContext->Equals(PrevDecl->getDeclContext()) ||
1841 OutermostContext->Encloses(PrevDecl->getDeclContext()))) {
1842 SemanticContext = PrevDecl->getDeclContext();
1843 } else {
1844 // Declarations in outer scopes don't matter. However, the outermost
1845 // context we computed is the semantic context for our new
1846 // declaration.
1847 PrevDecl = PrevClassTemplate = nullptr;
1848 SemanticContext = OutermostContext;
1849
1850 // Check that the chosen semantic context doesn't already contain a
1851 // declaration of this name as a non-tag type.
1852 Previous.clear(LookupOrdinaryName);
1853 DeclContext *LookupContext = SemanticContext;
1854 while (LookupContext->isTransparentContext())
1855 LookupContext = LookupContext->getLookupParent();
1856 LookupQualifiedName(Previous, LookupContext);
1857
1858 if (Previous.isAmbiguous())
1859 return true;
1860
1861 if (Previous.begin() != Previous.end())
1862 PrevDecl = (*Previous.begin())->getUnderlyingDecl();
1863 }
1864 }
1865 } else if (PrevDecl &&
1866 !isDeclInScope(Previous.getRepresentativeDecl(), SemanticContext,
1867 S, SS.isValid()))
1868 PrevDecl = PrevClassTemplate = nullptr;
1869
1870 if (auto *Shadow = dyn_cast_or_null<UsingShadowDecl>(
1871 PrevDecl ? Previous.getRepresentativeDecl() : nullptr)) {
1872 if (SS.isEmpty() &&
1873 !(PrevClassTemplate &&
1874 PrevClassTemplate->getDeclContext()->getRedeclContext()->Equals(
1875 SemanticContext->getRedeclContext()))) {
1876 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
1877 Diag(Shadow->getTargetDecl()->getLocation(),
1878 diag::note_using_decl_target);
1879 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
1880 // Recover by ignoring the old declaration.
1881 PrevDecl = PrevClassTemplate = nullptr;
1882 }
1883 }
1884
1885 if (PrevClassTemplate) {
1886 // Ensure that the template parameter lists are compatible. Skip this check
1887 // for a friend in a dependent context: the template parameter list itself
1888 // could be dependent.
1889 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1890 !TemplateParameterListsAreEqual(TemplateParams,
1891 PrevClassTemplate->getTemplateParameters(),
1892 /*Complain=*/true,
1893 TPL_TemplateMatch))
1894 return true;
1895
1896 // C++ [temp.class]p4:
1897 // In a redeclaration, partial specialization, explicit
1898 // specialization or explicit instantiation of a class template,
1899 // the class-key shall agree in kind with the original class
1900 // template declaration (7.1.5.3).
1901 RecordDecl *PrevRecordDecl = PrevClassTemplate->getTemplatedDecl();
1902 if (!isAcceptableTagRedeclaration(PrevRecordDecl, Kind,
1903 TUK == TUK_Definition, KWLoc, Name)) {
1904 Diag(KWLoc, diag::err_use_with_wrong_tag)
1905 << Name
1906 << FixItHint::CreateReplacement(KWLoc, PrevRecordDecl->getKindName());
1907 Diag(PrevRecordDecl->getLocation(), diag::note_previous_use);
1908 Kind = PrevRecordDecl->getTagKind();
1909 }
1910
1911 // Check for redefinition of this class template.
1912 if (TUK == TUK_Definition) {
1913 if (TagDecl *Def = PrevRecordDecl->getDefinition()) {
1914 // If we have a prior definition that is not visible, treat this as
1915 // simply making that previous definition visible.
1916 NamedDecl *Hidden = nullptr;
1917 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
1918 SkipBody->ShouldSkip = true;
1919 SkipBody->Previous = Def;
1920 auto *Tmpl = cast<CXXRecordDecl>(Hidden)->getDescribedClassTemplate();
1921 assert(Tmpl && "original definition of a class template is not a "(static_cast <bool> (Tmpl && "original definition of a class template is not a "
"class template?") ? void (0) : __assert_fail ("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "clang/lib/Sema/SemaTemplate.cpp", 1922, __extension__ __PRETTY_FUNCTION__
))
1922 "class template?")(static_cast <bool> (Tmpl && "original definition of a class template is not a "
"class template?") ? void (0) : __assert_fail ("Tmpl && \"original definition of a class template is not a \" \"class template?\""
, "clang/lib/Sema/SemaTemplate.cpp", 1922, __extension__ __PRETTY_FUNCTION__
))
;
1923 makeMergedDefinitionVisible(Hidden);
1924 makeMergedDefinitionVisible(Tmpl);
1925 } else {
1926 Diag(NameLoc, diag::err_redefinition) << Name;
1927 Diag(Def->getLocation(), diag::note_previous_definition);
1928 // FIXME: Would it make sense to try to "forget" the previous
1929 // definition, as part of error recovery?
1930 return true;
1931 }
1932 }
1933 }
1934 } else if (PrevDecl) {
1935 // C++ [temp]p5:
1936 // A class template shall not have the same name as any other
1937 // template, class, function, object, enumeration, enumerator,
1938 // namespace, or type in the same scope (3.3), except as specified
1939 // in (14.5.4).
1940 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
1941 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1942 return true;
1943 }
1944
1945 // Check the template parameter list of this declaration, possibly
1946 // merging in the template parameter list from the previous class
1947 // template declaration. Skip this check for a friend in a dependent
1948 // context, because the template parameter list might be dependent.
1949 if (!(TUK == TUK_Friend && CurContext->isDependentContext()) &&
1950 CheckTemplateParameterList(
1951 TemplateParams,
1952 PrevClassTemplate
1953 ? PrevClassTemplate->getMostRecentDecl()->getTemplateParameters()
1954 : nullptr,
1955 (SS.isSet() && SemanticContext && SemanticContext->isRecord() &&
1956 SemanticContext->isDependentContext())
1957 ? TPC_ClassTemplateMember
1958 : TUK == TUK_Friend ? TPC_FriendClassTemplate : TPC_ClassTemplate,
1959 SkipBody))
1960 Invalid = true;
1961
1962 if (SS.isSet()) {
1963 // If the name of the template was qualified, we must be defining the
1964 // template out-of-line.
1965 if (!SS.isInvalid() && !Invalid && !PrevClassTemplate) {
1966 Diag(NameLoc, TUK == TUK_Friend ? diag::err_friend_decl_does_not_match
1967 : diag::err_member_decl_does_not_match)
1968 << Name << SemanticContext << /*IsDefinition*/true << SS.getRange();
1969 Invalid = true;
1970 }
1971 }
1972
1973 // If this is a templated friend in a dependent context we should not put it
1974 // on the redecl chain. In some cases, the templated friend can be the most
1975 // recent declaration tricking the template instantiator to make substitutions
1976 // there.
1977 // FIXME: Figure out how to combine with shouldLinkDependentDeclWithPrevious
1978 bool ShouldAddRedecl
1979 = !(TUK == TUK_Friend && CurContext->isDependentContext());
1980
1981 CXXRecordDecl *NewClass =
1982 CXXRecordDecl::Create(Context, Kind, SemanticContext, KWLoc, NameLoc, Name,
1983 PrevClassTemplate && ShouldAddRedecl ?
1984 PrevClassTemplate->getTemplatedDecl() : nullptr,
1985 /*DelayTypeCreation=*/true);
1986 SetNestedNameSpecifier(*this, NewClass, SS);
1987 if (NumOuterTemplateParamLists > 0)
1988 NewClass->setTemplateParameterListsInfo(
1989 Context, llvm::makeArrayRef(OuterTemplateParamLists,
1990 NumOuterTemplateParamLists));
1991
1992 // Add alignment attributes if necessary; these attributes are checked when
1993 // the ASTContext lays out the structure.
1994 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
1995 AddAlignmentAttributesForRecord(NewClass);
1996 AddMsStructLayoutForRecord(NewClass);
1997 }
1998
1999 ClassTemplateDecl *NewTemplate
2000 = ClassTemplateDecl::Create(Context, SemanticContext, NameLoc,
2001 DeclarationName(Name), TemplateParams,
2002 NewClass);
2003
2004 if (ShouldAddRedecl)
2005 NewTemplate->setPreviousDecl(PrevClassTemplate);
2006
2007 NewClass->setDescribedClassTemplate(NewTemplate);
2008
2009 if (ModulePrivateLoc.isValid())
2010 NewTemplate->setModulePrivate();
2011
2012 // Build the type for the class template declaration now.
2013 QualType T = NewTemplate->getInjectedClassNameSpecialization();
2014 T = Context.getInjectedClassNameType(NewClass, T);
2015 assert(T->isDependentType() && "Class template type is not dependent?")(static_cast <bool> (T->isDependentType() &&
"Class template type is not dependent?") ? void (0) : __assert_fail
("T->isDependentType() && \"Class template type is not dependent?\""
, "clang/lib/Sema/SemaTemplate.cpp", 2015, __extension__ __PRETTY_FUNCTION__
))
;
2016 (void)T;
2017
2018 // If we are providing an explicit specialization of a member that is a
2019 // class template, make a note of that.
2020 if (PrevClassTemplate &&
2021 PrevClassTemplate->getInstantiatedFromMemberTemplate())
2022 PrevClassTemplate->setMemberSpecialization();
2023
2024 // Set the access specifier.
2025 if (!Invalid && TUK != TUK_Friend && NewTemplate->getDeclContext()->isRecord())
2026 SetMemberAccessSpecifier(NewTemplate, PrevClassTemplate, AS);
2027
2028 // Set the lexical context of these templates
2029 NewClass->setLexicalDeclContext(CurContext);
2030 NewTemplate->setLexicalDeclContext(CurContext);
2031
2032 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
2033 NewClass->startDefinition();
2034
2035 ProcessDeclAttributeList(S, NewClass, Attr);
2036
2037 if (PrevClassTemplate)
2038 mergeDeclAttributes(NewClass, PrevClassTemplate->getTemplatedDecl());
2039
2040 AddPushedVisibilityAttribute(NewClass);
2041 inferGslOwnerPointerAttribute(NewClass);
2042
2043 if (TUK != TUK_Friend) {
2044 // Per C++ [basic.scope.temp]p2, skip the template parameter scopes.
2045 Scope *Outer = S;
2046 while ((Outer->getFlags() & Scope::TemplateParamScope) != 0)
2047 Outer = Outer->getParent();
2048 PushOnScopeChains(NewTemplate, Outer);
2049 } else {
2050 if (PrevClassTemplate && PrevClassTemplate->getAccess() != AS_none) {
2051 NewTemplate->setAccess(PrevClassTemplate->getAccess());
2052 NewClass->setAccess(PrevClassTemplate->getAccess());
2053 }
2054
2055 NewTemplate->setObjectOfFriendDecl();
2056
2057 // Friend templates are visible in fairly strange ways.
2058 if (!CurContext->isDependentContext()) {
2059 DeclContext *DC = SemanticContext->getRedeclContext();
2060 DC->makeDeclVisibleInContext(NewTemplate);
2061 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
2062 PushOnScopeChains(NewTemplate, EnclosingScope,
2063 /* AddToContext = */ false);
2064 }
2065
2066 FriendDecl *Friend = FriendDecl::Create(
2067 Context, CurContext, NewClass->getLocation(), NewTemplate, FriendLoc);
2068 Friend->setAccess(AS_public);
2069 CurContext->addDecl(Friend);
2070 }
2071
2072 if (PrevClassTemplate)
2073 CheckRedeclarationInModule(NewTemplate, PrevClassTemplate);
2074
2075 if (Invalid) {
2076 NewTemplate->setInvalidDecl();
2077 NewClass->setInvalidDecl();
2078 }
2079
2080 ActOnDocumentableDecl(NewTemplate);
2081
2082 if (SkipBody && SkipBody->ShouldSkip)
2083 return SkipBody->Previous;
2084
2085 return NewTemplate;
2086}
2087
2088namespace {
2089/// Tree transform to "extract" a transformed type from a class template's
2090/// constructor to a deduction guide.
2091class ExtractTypeForDeductionGuide
2092 : public TreeTransform<ExtractTypeForDeductionGuide> {
2093 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs;
2094
2095public:
2096 typedef TreeTransform<ExtractTypeForDeductionGuide> Base;
2097 ExtractTypeForDeductionGuide(
2098 Sema &SemaRef,
2099 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs)
2100 : Base(SemaRef), MaterializedTypedefs(MaterializedTypedefs) {}
2101
2102 TypeSourceInfo *transform(TypeSourceInfo *TSI) { return TransformType(TSI); }
2103
2104 QualType TransformTypedefType(TypeLocBuilder &TLB, TypedefTypeLoc TL) {
2105 ASTContext &Context = SemaRef.getASTContext();
2106 TypedefNameDecl *OrigDecl = TL.getTypedefNameDecl();
2107 TypedefNameDecl *Decl = OrigDecl;
2108 // Transform the underlying type of the typedef and clone the Decl only if
2109 // the typedef has a dependent context.
2110 if (OrigDecl->getDeclContext()->isDependentContext()) {
2111 TypeLocBuilder InnerTLB;
2112 QualType Transformed =
2113 TransformType(InnerTLB, OrigDecl->getTypeSourceInfo()->getTypeLoc());
2114 TypeSourceInfo *TSI = InnerTLB.getTypeSourceInfo(Context, Transformed);
2115 if (isa<TypeAliasDecl>(OrigDecl))
2116 Decl = TypeAliasDecl::Create(
2117 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2118 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2119 else {
2120 assert(isa<TypedefDecl>(OrigDecl) && "Not a Type alias or typedef")(static_cast <bool> (isa<TypedefDecl>(OrigDecl) &&
"Not a Type alias or typedef") ? void (0) : __assert_fail ("isa<TypedefDecl>(OrigDecl) && \"Not a Type alias or typedef\""
, "clang/lib/Sema/SemaTemplate.cpp", 2120, __extension__ __PRETTY_FUNCTION__
))
;
2121 Decl = TypedefDecl::Create(
2122 Context, Context.getTranslationUnitDecl(), OrigDecl->getBeginLoc(),
2123 OrigDecl->getLocation(), OrigDecl->getIdentifier(), TSI);
2124 }
2125 MaterializedTypedefs.push_back(Decl);
2126 }
2127
2128 QualType TDTy = Context.getTypedefType(Decl);
2129 TypedefTypeLoc TypedefTL = TLB.push<TypedefTypeLoc>(TDTy);
2130 TypedefTL.setNameLoc(TL.getNameLoc());
2131
2132 return TDTy;
2133 }
2134};
2135
2136/// Transform to convert portions of a constructor declaration into the
2137/// corresponding deduction guide, per C++1z [over.match.class.deduct]p1.
2138struct ConvertConstructorToDeductionGuideTransform {
2139 ConvertConstructorToDeductionGuideTransform(Sema &S,
2140 ClassTemplateDecl *Template)
2141 : SemaRef(S), Template(Template) {}
2142
2143 Sema &SemaRef;
2144 ClassTemplateDecl *Template;
2145
2146 DeclContext *DC = Template->getDeclContext();
2147 CXXRecordDecl *Primary = Template->getTemplatedDecl();
2148 DeclarationName DeductionGuideName =
2149 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(Template);
2150
2151 QualType DeducedType = SemaRef.Context.getTypeDeclType(Primary);
2152
2153 // Index adjustment to apply to convert depth-1 template parameters into
2154 // depth-0 template parameters.
2155 unsigned Depth1IndexAdjustment = Template->getTemplateParameters()->size();
2156
2157 /// Transform a constructor declaration into a deduction guide.
2158 NamedDecl *transformConstructor(FunctionTemplateDecl *FTD,
2159 CXXConstructorDecl *CD) {
2160 SmallVector<TemplateArgument, 16> SubstArgs;
2161
2162 LocalInstantiationScope Scope(SemaRef);
2163
2164 // C++ [over.match.class.deduct]p1:
2165 // -- For each constructor of the class template designated by the
2166 // template-name, a function template with the following properties:
2167
2168 // -- The template parameters are the template parameters of the class
2169 // template followed by the template parameters (including default
2170 // template arguments) of the constructor, if any.
2171 TemplateParameterList *TemplateParams = Template->getTemplateParameters();
2172 if (FTD) {
2173 TemplateParameterList *InnerParams = FTD->getTemplateParameters();
2174 SmallVector<NamedDecl *, 16> AllParams;
2175 AllParams.reserve(TemplateParams->size() + InnerParams->size());
2176 AllParams.insert(AllParams.begin(),
2177 TemplateParams->begin(), TemplateParams->end());
2178 SubstArgs.reserve(InnerParams->size());
2179
2180 // Later template parameters could refer to earlier ones, so build up
2181 // a list of substituted template arguments as we go.
2182 for (NamedDecl *Param : *InnerParams) {
2183 MultiLevelTemplateArgumentList Args;
2184 Args.setKind(TemplateSubstitutionKind::Rewrite);
2185 Args.addOuterTemplateArguments(SubstArgs);
2186 Args.addOuterRetainedLevel();
2187 NamedDecl *NewParam = transformTemplateParameter(Param, Args);
2188 if (!NewParam)
2189 return nullptr;
2190 AllParams.push_back(NewParam);
2191 SubstArgs.push_back(SemaRef.Context.getCanonicalTemplateArgument(
2192 SemaRef.Context.getInjectedTemplateArg(NewParam)));
2193 }
2194
2195 // Substitute new template parameters into requires-clause if present.
2196 Expr *RequiresClause = nullptr;
2197 if (Expr *InnerRC = InnerParams->getRequiresClause()) {
2198 MultiLevelTemplateArgumentList Args;
2199 Args.setKind(TemplateSubstitutionKind::Rewrite);
2200 Args.addOuterTemplateArguments(SubstArgs);
2201 Args.addOuterRetainedLevel();
2202 ExprResult E = SemaRef.SubstExpr(InnerRC, Args);
2203 if (E.isInvalid())
2204 return nullptr;
2205 RequiresClause = E.getAs<Expr>();
2206 }
2207
2208 TemplateParams = TemplateParameterList::Create(
2209 SemaRef.Context, InnerParams->getTemplateLoc(),
2210 InnerParams->getLAngleLoc(), AllParams, InnerParams->getRAngleLoc(),
2211 RequiresClause);
2212 }
2213
2214 // If we built a new template-parameter-list, track that we need to
2215 // substitute references to the old parameters into references to the
2216 // new ones.
2217 MultiLevelTemplateArgumentList Args;
2218 Args.setKind(TemplateSubstitutionKind::Rewrite);
2219 if (FTD) {
2220 Args.addOuterTemplateArguments(SubstArgs);
2221 Args.addOuterRetainedLevel();
2222 }
2223
2224 FunctionProtoTypeLoc FPTL = CD->getTypeSourceInfo()->getTypeLoc()
2225 .getAsAdjusted<FunctionProtoTypeLoc>();
2226 assert(FPTL && "no prototype for constructor declaration")(static_cast <bool> (FPTL && "no prototype for constructor declaration"
) ? void (0) : __assert_fail ("FPTL && \"no prototype for constructor declaration\""
, "clang/lib/Sema/SemaTemplate.cpp", 2226, __extension__ __PRETTY_FUNCTION__
))
;
2227
2228 // Transform the type of the function, adjusting the return type and
2229 // replacing references to the old parameters with references to the
2230 // new ones.
2231 TypeLocBuilder TLB;
2232 SmallVector<ParmVarDecl*, 8> Params;
2233 SmallVector<TypedefNameDecl *, 4> MaterializedTypedefs;
2234 QualType NewType = transformFunctionProtoType(TLB, FPTL, Params, Args,
2235 MaterializedTypedefs);
2236 if (NewType.isNull())
2237 return nullptr;
2238 TypeSourceInfo *NewTInfo = TLB.getTypeSourceInfo(SemaRef.Context, NewType);
2239
2240 return buildDeductionGuide(TemplateParams, CD, CD->getExplicitSpecifier(),
2241 NewTInfo, CD->getBeginLoc(), CD->getLocation(),
2242 CD->getEndLoc(), MaterializedTypedefs);
2243 }
2244
2245 /// Build a deduction guide with the specified parameter types.
2246 NamedDecl *buildSimpleDeductionGuide(MutableArrayRef<QualType> ParamTypes) {
2247 SourceLocation Loc = Template->getLocation();
2248
2249 // Build the requested type.
2250 FunctionProtoType::ExtProtoInfo EPI;
2251 EPI.HasTrailingReturn = true;
2252 QualType Result = SemaRef.BuildFunctionType(DeducedType, ParamTypes, Loc,
2253 DeductionGuideName, EPI);
2254 TypeSourceInfo *TSI = SemaRef.Context.getTrivialTypeSourceInfo(Result, Loc);
2255
2256 FunctionProtoTypeLoc FPTL =
2257 TSI->getTypeLoc().castAs<FunctionProtoTypeLoc>();
2258
2259 // Build the parameters, needed during deduction / substitution.
2260 SmallVector<ParmVarDecl*, 4> Params;
2261 for (auto T : ParamTypes) {
2262 ParmVarDecl *NewParam = ParmVarDecl::Create(
2263 SemaRef.Context, DC, Loc, Loc, nullptr, T,
2264 SemaRef.Context.getTrivialTypeSourceInfo(T, Loc), SC_None, nullptr);
2265 NewParam->setScopeInfo(0, Params.size());
2266 FPTL.setParam(Params.size(), NewParam);
2267 Params.push_back(NewParam);
2268 }
2269
2270 return buildDeductionGuide(Template->getTemplateParameters(), nullptr,
2271 ExplicitSpecifier(), TSI, Loc, Loc, Loc);
2272 }
2273
2274private:
2275 /// Transform a constructor template parameter into a deduction guide template
2276 /// parameter, rebuilding any internal references to earlier parameters and
2277 /// renumbering as we go.
2278 NamedDecl *transformTemplateParameter(NamedDecl *TemplateParam,
2279 MultiLevelTemplateArgumentList &Args) {
2280 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(TemplateParam)) {
2281 // TemplateTypeParmDecl's index cannot be changed after creation, so
2282 // substitute it directly.
2283 auto *NewTTP = TemplateTypeParmDecl::Create(
2284 SemaRef.Context, DC, TTP->getBeginLoc(), TTP->getLocation(),
2285 /*Depth*/ 0, Depth1IndexAdjustment + TTP->getIndex(),
2286 TTP->getIdentifier(), TTP->wasDeclaredWithTypename(),
2287 TTP->isParameterPack(), TTP->hasTypeConstraint(),
2288 TTP->isExpandedParameterPack() ?
2289 llvm::Optional<unsigned>(TTP->getNumExpansionParameters()) : None);
2290 if (const auto *TC = TTP->getTypeConstraint())
2291 SemaRef.SubstTypeConstraint(NewTTP, TC, Args);
2292 if (TTP->hasDefaultArgument()) {
2293 TypeSourceInfo *InstantiatedDefaultArg =
2294 SemaRef.SubstType(TTP->getDefaultArgumentInfo(), Args,
2295 TTP->getDefaultArgumentLoc(), TTP->getDeclName());
2296 if (InstantiatedDefaultArg)
2297 NewTTP->setDefaultArgument(InstantiatedDefaultArg);
2298 }
2299 SemaRef.CurrentInstantiationScope->InstantiatedLocal(TemplateParam,
2300 NewTTP);
2301 return NewTTP;
2302 }
2303
2304 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TemplateParam))
2305 return transformTemplateParameterImpl(TTP, Args);
2306
2307 return transformTemplateParameterImpl(
2308 cast<NonTypeTemplateParmDecl>(TemplateParam), Args);
2309 }
2310 template<typename TemplateParmDecl>
2311 TemplateParmDecl *
2312 transformTemplateParameterImpl(TemplateParmDecl *OldParam,
2313 MultiLevelTemplateArgumentList &Args) {
2314 // Ask the template instantiator to do the heavy lifting for us, then adjust
2315 // the index of the parameter once it's done.
2316 auto *NewParam =
2317 cast<TemplateParmDecl>(SemaRef.SubstDecl(OldParam, DC, Args));
2318 assert(NewParam->getDepth() == 0 && "unexpected template param depth")(static_cast <bool> (NewParam->getDepth() == 0 &&
"unexpected template param depth") ? void (0) : __assert_fail
("NewParam->getDepth() == 0 && \"unexpected template param depth\""
, "clang/lib/Sema/SemaTemplate.cpp", 2318, __extension__ __PRETTY_FUNCTION__
))
;
2319 NewParam->setPosition(NewParam->getPosition() + Depth1IndexAdjustment);
2320 return NewParam;
2321 }
2322
2323 QualType transformFunctionProtoType(
2324 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL,
2325 SmallVectorImpl<ParmVarDecl *> &Params,
2326 MultiLevelTemplateArgumentList &Args,
2327 SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2328 SmallVector<QualType, 4> ParamTypes;
2329 const FunctionProtoType *T = TL.getTypePtr();
2330
2331 // -- The types of the function parameters are those of the constructor.
2332 for (auto *OldParam : TL.getParams()) {
2333 ParmVarDecl *NewParam =
2334 transformFunctionTypeParam(OldParam, Args, MaterializedTypedefs);
2335 if (!NewParam)
2336 return QualType();
2337 ParamTypes.push_back(NewParam->getType());
2338 Params.push_back(NewParam);
2339 }
2340
2341 // -- The return type is the class template specialization designated by
2342 // the template-name and template arguments corresponding to the
2343 // template parameters obtained from the class template.
2344 //
2345 // We use the injected-class-name type of the primary template instead.
2346 // This has the convenient property that it is different from any type that
2347 // the user can write in a deduction-guide (because they cannot enter the
2348 // context of the template), so implicit deduction guides can never collide
2349 // with explicit ones.
2350 QualType ReturnType = DeducedType;
2351 TLB.pushTypeSpec(ReturnType).setNameLoc(Primary->getLocation());
2352
2353 // Resolving a wording defect, we also inherit the variadicness of the
2354 // constructor.
2355 FunctionProtoType::ExtProtoInfo EPI;
2356 EPI.Variadic = T->isVariadic();
2357 EPI.HasTrailingReturn = true;
2358
2359 QualType Result = SemaRef.BuildFunctionType(
2360 ReturnType, ParamTypes, TL.getBeginLoc(), DeductionGuideName, EPI);
2361 if (Result.isNull())
2362 return QualType();
2363
2364 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
2365 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
2366 NewTL.setLParenLoc(TL.getLParenLoc());
2367 NewTL.setRParenLoc(TL.getRParenLoc());
2368 NewTL.setExceptionSpecRange(SourceRange());
2369 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
2370 for (unsigned I = 0, E = NewTL.getNumParams(); I != E; ++I)
2371 NewTL.setParam(I, Params[I]);
2372
2373 return Result;
2374 }
2375
2376 ParmVarDecl *transformFunctionTypeParam(
2377 ParmVarDecl *OldParam, MultiLevelTemplateArgumentList &Args,
2378 llvm::SmallVectorImpl<TypedefNameDecl *> &MaterializedTypedefs) {
2379 TypeSourceInfo *OldDI = OldParam->getTypeSourceInfo();
2380 TypeSourceInfo *NewDI;
2381 if (auto PackTL = OldDI->getTypeLoc().getAs<PackExpansionTypeLoc>()) {
2382 // Expand out the one and only element in each inner pack.
2383 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, 0);
2384 NewDI =
2385 SemaRef.SubstType(PackTL.getPatternLoc(), Args,
2386 OldParam->getLocation(), OldParam->getDeclName());
2387 if (!NewDI) return nullptr;
2388 NewDI =
2389 SemaRef.CheckPackExpansion(NewDI, PackTL.getEllipsisLoc(),
2390 PackTL.getTypePtr()->getNumExpansions());
2391 } else
2392 NewDI = SemaRef.SubstType(OldDI, Args, OldParam->getLocation(),
2393 OldParam->getDeclName());
2394 if (!NewDI)
2395 return nullptr;
2396
2397 // Extract the type. This (for instance) replaces references to typedef
2398 // members of the current instantiations with the definitions of those
2399 // typedefs, avoiding triggering instantiation of the deduced type during
2400 // deduction.
2401 NewDI = ExtractTypeForDeductionGuide(SemaRef, MaterializedTypedefs)
2402 .transform(NewDI);
2403
2404 // Resolving a wording defect, we also inherit default arguments from the
2405 // constructor.
2406 ExprResult NewDefArg;
2407 if (OldParam->hasDefaultArg()) {
2408 // We don't care what the value is (we won't use it); just create a
2409 // placeholder to indicate there is a default argument.
2410 QualType ParamTy = NewDI->getType();
2411 NewDefArg = new (SemaRef.Context)
2412 OpaqueValueExpr(OldParam->getDefaultArg()->getBeginLoc(),
2413 ParamTy.getNonLValueExprType(SemaRef.Context),
2414 ParamTy->isLValueReferenceType() ? VK_LValue
2415 : ParamTy->isRValueReferenceType() ? VK_XValue
2416 : VK_PRValue);
2417 }
2418
2419 ParmVarDecl *NewParam = ParmVarDecl::Create(SemaRef.Context, DC,
2420 OldParam->getInnerLocStart(),
2421 OldParam->getLocation(),
2422 OldParam->getIdentifier(),
2423 NewDI->getType(),
2424 NewDI,
2425 OldParam->getStorageClass(),
2426 NewDefArg.get());
2427 NewParam->setScopeInfo(OldParam->getFunctionScopeDepth(),
2428 OldParam->getFunctionScopeIndex());
2429 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam, NewParam);
2430 return NewParam;
2431 }
2432
2433 FunctionTemplateDecl *buildDeductionGuide(
2434 TemplateParameterList *TemplateParams, CXXConstructorDecl *Ctor,
2435 ExplicitSpecifier ES, TypeSourceInfo *TInfo, SourceLocation LocStart,
2436 SourceLocation Loc, SourceLocation LocEnd,
2437 llvm::ArrayRef<TypedefNameDecl *> MaterializedTypedefs = {}) {
2438 DeclarationNameInfo Name(DeductionGuideName, Loc);
2439 ArrayRef<ParmVarDecl *> Params =
2440 TInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams();
2441
2442 // Build the implicit deduction guide template.
2443 auto *Guide =
2444 CXXDeductionGuideDecl::Create(SemaRef.Context, DC, LocStart, ES, Name,
2445 TInfo->getType(), TInfo, LocEnd, Ctor);
2446 Guide->setImplicit();
2447 Guide->setParams(Params);
2448
2449 for (auto *Param : Params)
2450 Param->setDeclContext(Guide);
2451 for (auto *TD : MaterializedTypedefs)
2452 TD->setDeclContext(Guide);
2453
2454 auto *GuideTemplate = FunctionTemplateDecl::Create(
2455 SemaRef.Context, DC, Loc, DeductionGuideName, TemplateParams, Guide);
2456 GuideTemplate->setImplicit();
2457 Guide->setDescribedFunctionTemplate(GuideTemplate);
2458
2459 if (isa<CXXRecordDecl>(DC)) {
2460 Guide->setAccess(AS_public);
2461 GuideTemplate->setAccess(AS_public);
2462 }
2463
2464 DC->addDecl(GuideTemplate);
2465 return GuideTemplate;
2466 }
2467};
2468}
2469
2470void Sema::DeclareImplicitDeductionGuides(TemplateDecl *Template,
2471 SourceLocation Loc) {
2472 if (CXXRecordDecl *DefRecord =
2473 cast<CXXRecordDecl>(Template->getTemplatedDecl())->getDefinition()) {
2474 TemplateDecl *DescribedTemplate = DefRecord->getDescribedClassTemplate();
2475 Template = DescribedTemplate ? DescribedTemplate : Template;
2476 }
2477
2478 DeclContext *DC = Template->getDeclContext();
2479 if (DC->isDependentContext())
2480 return;
2481
2482 ConvertConstructorToDeductionGuideTransform Transform(
2483 *this, cast<ClassTemplateDecl>(Template));
2484 if (!isCompleteType(Loc, Transform.DeducedType))
2485 return;
2486
2487 // Check whether we've already declared deduction guides for this template.
2488 // FIXME: Consider storing a flag on the template to indicate this.
2489 auto Existing = DC->lookup(Transform.DeductionGuideName);
2490 for (auto *D : Existing)
2491 if (D->isImplicit())
2492 return;
2493
2494 // In case we were expanding a pack when we attempted to declare deduction
2495 // guides, turn off pack expansion for everything we're about to do.
2496 ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2497 // Create a template instantiation record to track the "instantiation" of
2498 // constructors into deduction guides.
2499 // FIXME: Add a kind for this to give more meaningful diagnostics. But can
2500 // this substitution process actually fail?
2501 InstantiatingTemplate BuildingDeductionGuides(*this, Loc, Template);
2502 if (BuildingDeductionGuides.isInvalid())
2503 return;
2504
2505 // Convert declared constructors into deduction guide templates.
2506 // FIXME: Skip constructors for which deduction must necessarily fail (those
2507 // for which some class template parameter without a default argument never
2508 // appears in a deduced context).
2509 bool AddedAny = false;
2510 for (NamedDecl *D : LookupConstructors(Transform.Primary)) {
2511 D = D->getUnderlyingDecl();
2512 if (D->isInvalidDecl() || D->isImplicit())
2513 continue;
2514 D = cast<NamedDecl>(D->getCanonicalDecl());
2515
2516 auto *FTD = dyn_cast<FunctionTemplateDecl>(D);
2517 auto *CD =
2518 dyn_cast_or_null<CXXConstructorDecl>(FTD ? FTD->getTemplatedDecl() : D);
2519 // Class-scope explicit specializations (MS extension) do not result in
2520 // deduction guides.
2521 if (!CD || (!FTD && CD->isFunctionTemplateSpecialization()))
2522 continue;
2523
2524 // Cannot make a deduction guide when unparsed arguments are present.
2525 if (llvm::any_of(CD->parameters(), [](ParmVarDecl *P) {
2526 return !P || P->hasUnparsedDefaultArg();
2527 }))
2528 continue;
2529
2530 Transform.transformConstructor(FTD, CD);
2531 AddedAny = true;
2532 }
2533
2534 // C++17 [over.match.class.deduct]
2535 // -- If C is not defined or does not declare any constructors, an
2536 // additional function template derived as above from a hypothetical
2537 // constructor C().
2538 if (!AddedAny)
2539 Transform.buildSimpleDeductionGuide(None);
2540
2541 // -- An additional function template derived as above from a hypothetical
2542 // constructor C(C), called the copy deduction candidate.
2543 cast<CXXDeductionGuideDecl>(
2544 cast<FunctionTemplateDecl>(
2545 Transform.buildSimpleDeductionGuide(Transform.DeducedType))
2546 ->getTemplatedDecl())
2547 ->setIsCopyDeductionCandidate();
2548}
2549
2550/// Diagnose the presence of a default template argument on a
2551/// template parameter, which is ill-formed in certain contexts.
2552///
2553/// \returns true if the default template argument should be dropped.
2554static bool DiagnoseDefaultTemplateArgument(Sema &S,
2555 Sema::TemplateParamListContext TPC,
2556 SourceLocation ParamLoc,
2557 SourceRange DefArgRange) {
2558 switch (TPC) {
2559 case Sema::TPC_ClassTemplate:
2560 case Sema::TPC_VarTemplate:
2561 case Sema::TPC_TypeAliasTemplate:
2562 return false;
2563
2564 case Sema::TPC_FunctionTemplate:
2565 case Sema::TPC_FriendFunctionTemplateDefinition:
2566 // C++ [temp.param]p9:
2567 // A default template-argument shall not be specified in a
2568 // function template declaration or a function template
2569 // definition [...]
2570 // If a friend function template declaration specifies a default
2571 // template-argument, that declaration shall be a definition and shall be
2572 // the only declaration of the function template in the translation unit.
2573 // (C++98/03 doesn't have this wording; see DR226).
2574 S.Diag(ParamLoc, S.getLangOpts().CPlusPlus11 ?
2575 diag::warn_cxx98_compat_template_parameter_default_in_function_template
2576 : diag::ext_template_parameter_default_in_function_template)
2577 << DefArgRange;
2578 return false;
2579
2580 case Sema::TPC_ClassTemplateMember:
2581 // C++0x [temp.param]p9:
2582 // A default template-argument shall not be specified in the
2583 // template-parameter-lists of the definition of a member of a
2584 // class template that appears outside of the member's class.
2585 S.Diag(ParamLoc, diag::err_template_parameter_default_template_member)
2586 << DefArgRange;
2587 return true;
2588
2589 case Sema::TPC_FriendClassTemplate:
2590 case Sema::TPC_FriendFunctionTemplate:
2591 // C++ [temp.param]p9:
2592 // A default template-argument shall not be specified in a
2593 // friend template declaration.
2594 S.Diag(ParamLoc, diag::err_template_parameter_default_friend_template)
2595 << DefArgRange;
2596 return true;
2597
2598 // FIXME: C++0x [temp.param]p9 allows default template-arguments
2599 // for friend function templates if there is only a single
2600 // declaration (and it is a definition). Strange!
2601 }
2602
2603 llvm_unreachable("Invalid TemplateParamListContext!")::llvm::llvm_unreachable_internal("Invalid TemplateParamListContext!"
, "clang/lib/Sema/SemaTemplate.cpp", 2603)
;
2604}
2605
2606/// Check for unexpanded parameter packs within the template parameters
2607/// of a template template parameter, recursively.
2608static bool DiagnoseUnexpandedParameterPacks(Sema &S,
2609 TemplateTemplateParmDecl *TTP) {
2610 // A template template parameter which is a parameter pack is also a pack
2611 // expansion.
2612 if (TTP->isParameterPack())
2613 return false;
2614
2615 TemplateParameterList *Params = TTP->getTemplateParameters();
2616 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2617 NamedDecl *P = Params->getParam(I);
2618 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(P)) {
2619 if (!TTP->isParameterPack())
2620 if (const TypeConstraint *TC = TTP->getTypeConstraint())
2621 if (TC->hasExplicitTemplateArgs())
2622 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2623 if (S.DiagnoseUnexpandedParameterPack(ArgLoc,
2624 Sema::UPPC_TypeConstraint))
2625 return true;
2626 continue;
2627 }
2628
2629 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
2630 if (!NTTP->isParameterPack() &&
2631 S.DiagnoseUnexpandedParameterPack(NTTP->getLocation(),
2632 NTTP->getTypeSourceInfo(),
2633 Sema::UPPC_NonTypeTemplateParameterType))
2634 return true;
2635
2636 continue;
2637 }
2638
2639 if (TemplateTemplateParmDecl *InnerTTP
2640 = dyn_cast<TemplateTemplateParmDecl>(P))
2641 if (DiagnoseUnexpandedParameterPacks(S, InnerTTP))
2642 return true;
2643 }
2644
2645 return false;
2646}
2647
2648/// Checks the validity of a template parameter list, possibly
2649/// considering the template parameter list from a previous
2650/// declaration.
2651///
2652/// If an "old" template parameter list is provided, it must be
2653/// equivalent (per TemplateParameterListsAreEqual) to the "new"
2654/// template parameter list.
2655///
2656/// \param NewParams Template parameter list for a new template
2657/// declaration. This template parameter list will be updated with any
2658/// default arguments that are carried through from the previous
2659/// template parameter list.
2660///
2661/// \param OldParams If provided, template parameter list from a
2662/// previous declaration of the same template. Default template
2663/// arguments will be merged from the old template parameter list to
2664/// the new template parameter list.
2665///
2666/// \param TPC Describes the context in which we are checking the given
2667/// template parameter list.
2668///
2669/// \param SkipBody If we might have already made a prior merged definition
2670/// of this template visible, the corresponding body-skipping information.
2671/// Default argument redefinition is not an error when skipping such a body,
2672/// because (under the ODR) we can assume the default arguments are the same
2673/// as the prior merged definition.
2674///
2675/// \returns true if an error occurred, false otherwise.
2676bool Sema::CheckTemplateParameterList(TemplateParameterList *NewParams,
2677 TemplateParameterList *OldParams,
2678 TemplateParamListContext TPC,
2679 SkipBodyInfo *SkipBody) {
2680 bool Invalid = false;
2681
2682 // C++ [temp.param]p10:
2683 // The set of default template-arguments available for use with a
2684 // template declaration or definition is obtained by merging the
2685 // default arguments from the definition (if in scope) and all
2686 // declarations in scope in the same way default function
2687 // arguments are (8.3.6).
2688 bool SawDefaultArgument = false;
2689 SourceLocation PreviousDefaultArgLoc;
2690
2691 // Dummy initialization to avoid warnings.
2692 TemplateParameterList::iterator OldParam = NewParams->end();
2693 if (OldParams)
2694 OldParam = OldParams->begin();
2695
2696 bool RemoveDefaultArguments = false;
2697 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2698 NewParamEnd = NewParams->end();
2699 NewParam != NewParamEnd; ++NewParam) {
2700 // Whether we've seen a duplicate default argument in the same translation
2701 // unit.
2702 bool RedundantDefaultArg = false;
2703 // Whether we've found inconsis inconsitent default arguments in different
2704 // translation unit.
2705 bool InconsistentDefaultArg = false;
2706 // The name of the module which contains the inconsistent default argument.
2707 std::string PrevModuleName;
2708
2709 SourceLocation OldDefaultLoc;
2710 SourceLocation NewDefaultLoc;
2711
2712 // Variable used to diagnose missing default arguments
2713 bool MissingDefaultArg = false;
2714
2715 // Variable used to diagnose non-final parameter packs
2716 bool SawParameterPack = false;
2717
2718 if (TemplateTypeParmDecl *NewTypeParm
2719 = dyn_cast<TemplateTypeParmDecl>(*NewParam)) {
2720 // Check the presence of a default argument here.
2721 if (NewTypeParm->hasDefaultArgument() &&
2722 DiagnoseDefaultTemplateArgument(*this, TPC,
2723 NewTypeParm->getLocation(),
2724 NewTypeParm->getDefaultArgumentInfo()->getTypeLoc()
2725 .getSourceRange()))
2726 NewTypeParm->removeDefaultArgument();
2727
2728 // Merge default arguments for template type parameters.
2729 TemplateTypeParmDecl *OldTypeParm
2730 = OldParams? cast<TemplateTypeParmDecl>(*OldParam) : nullptr;
2731 if (NewTypeParm->isParameterPack()) {
2732 assert(!NewTypeParm->hasDefaultArgument() &&(static_cast <bool> (!NewTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "clang/lib/Sema/SemaTemplate.cpp", 2733, __extension__ __PRETTY_FUNCTION__
))
2733 "Parameter packs can't have a default argument!")(static_cast <bool> (!NewTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "clang/lib/Sema/SemaTemplate.cpp", 2733, __extension__ __PRETTY_FUNCTION__
))
;
2734 SawParameterPack = true;
2735 } else if (OldTypeParm && hasVisibleDefaultArgument(OldTypeParm) &&
2736 NewTypeParm->hasDefaultArgument() &&
2737 (!SkipBody || !SkipBody->ShouldSkip)) {
2738 OldDefaultLoc = OldTypeParm->getDefaultArgumentLoc();
2739 NewDefaultLoc = NewTypeParm->getDefaultArgumentLoc();
2740 SawDefaultArgument = true;
2741
2742 if (!OldTypeParm->getOwningModule() ||
2743 isModuleUnitOfCurrentTU(OldTypeParm->getOwningModule()))
2744 RedundantDefaultArg = true;
2745 else if (!getASTContext().isSameDefaultTemplateArgument(OldTypeParm,
2746 NewTypeParm)) {
2747 InconsistentDefaultArg = true;
2748 PrevModuleName =
2749 OldTypeParm->getImportedOwningModule()->getFullModuleName();
2750 }
2751 PreviousDefaultArgLoc = NewDefaultLoc;
2752 } else if (OldTypeParm && OldTypeParm->hasDefaultArgument()) {
2753 // Merge the default argument from the old declaration to the
2754 // new declaration.
2755 NewTypeParm->setInheritedDefaultArgument(Context, OldTypeParm);
2756 PreviousDefaultArgLoc = OldTypeParm->getDefaultArgumentLoc();
2757 } else if (NewTypeParm->hasDefaultArgument()) {
2758 SawDefaultArgument = true;
2759 PreviousDefaultArgLoc = NewTypeParm->getDefaultArgumentLoc();
2760 } else if (SawDefaultArgument)
2761 MissingDefaultArg = true;
2762 } else if (NonTypeTemplateParmDecl *NewNonTypeParm
2763 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam)) {
2764 // Check for unexpanded parameter packs.
2765 if (!NewNonTypeParm->isParameterPack() &&
2766 DiagnoseUnexpandedParameterPack(NewNonTypeParm->getLocation(),
2767 NewNonTypeParm->getTypeSourceInfo(),
2768 UPPC_NonTypeTemplateParameterType)) {
2769 Invalid = true;
2770 continue;
2771 }
2772
2773 // Check the presence of a default argument here.
2774 if (NewNonTypeParm->hasDefaultArgument() &&
2775 DiagnoseDefaultTemplateArgument(*this, TPC,
2776 NewNonTypeParm->getLocation(),
2777 NewNonTypeParm->getDefaultArgument()->getSourceRange())) {
2778 NewNonTypeParm->removeDefaultArgument();
2779 }
2780
2781 // Merge default arguments for non-type template parameters
2782 NonTypeTemplateParmDecl *OldNonTypeParm
2783 = OldParams? cast<NonTypeTemplateParmDecl>(*OldParam) : nullptr;
2784 if (NewNonTypeParm->isParameterPack()) {
2785 assert(!NewNonTypeParm->hasDefaultArgument() &&(static_cast <bool> (!NewNonTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "clang/lib/Sema/SemaTemplate.cpp", 2786, __extension__ __PRETTY_FUNCTION__
))
2786 "Parameter packs can't have a default argument!")(static_cast <bool> (!NewNonTypeParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewNonTypeParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "clang/lib/Sema/SemaTemplate.cpp", 2786, __extension__ __PRETTY_FUNCTION__
))
;
2787 if (!NewNonTypeParm->isPackExpansion())
2788 SawParameterPack = true;
2789 } else if (OldNonTypeParm && hasVisibleDefaultArgument(OldNonTypeParm) &&
2790 NewNonTypeParm->hasDefaultArgument() &&
2791 (!SkipBody || !SkipBody->ShouldSkip)) {
2792 OldDefaultLoc = OldNonTypeParm->getDefaultArgumentLoc();
2793 NewDefaultLoc = NewNonTypeParm->getDefaultArgumentLoc();
2794 SawDefaultArgument = true;
2795 if (!OldNonTypeParm->getOwningModule() ||
2796 isModuleUnitOfCurrentTU(OldNonTypeParm->getOwningModule()))
2797 RedundantDefaultArg = true;
2798 else if (!getASTContext().isSameDefaultTemplateArgument(
2799 OldNonTypeParm, NewNonTypeParm)) {
2800 InconsistentDefaultArg = true;
2801 PrevModuleName =
2802 OldNonTypeParm->getImportedOwningModule()->getFullModuleName();
2803 }
2804 PreviousDefaultArgLoc = NewDefaultLoc;
2805 } else if (OldNonTypeParm && OldNonTypeParm->hasDefaultArgument()) {
2806 // Merge the default argument from the old declaration to the
2807 // new declaration.
2808 NewNonTypeParm->setInheritedDefaultArgument(Context, OldNonTypeParm);
2809 PreviousDefaultArgLoc = OldNonTypeParm->getDefaultArgumentLoc();
2810 } else if (NewNonTypeParm->hasDefaultArgument()) {
2811 SawDefaultArgument = true;
2812 PreviousDefaultArgLoc = NewNonTypeParm->getDefaultArgumentLoc();
2813 } else if (SawDefaultArgument)
2814 MissingDefaultArg = true;
2815 } else {
2816 TemplateTemplateParmDecl *NewTemplateParm
2817 = cast<TemplateTemplateParmDecl>(*NewParam);
2818
2819 // Check for unexpanded parameter packs, recursively.
2820 if (::DiagnoseUnexpandedParameterPacks(*this, NewTemplateParm)) {
2821 Invalid = true;
2822 continue;
2823 }
2824
2825 // Check the presence of a default argument here.
2826 if (NewTemplateParm->hasDefaultArgument() &&
2827 DiagnoseDefaultTemplateArgument(*this, TPC,
2828 NewTemplateParm->getLocation(),
2829 NewTemplateParm->getDefaultArgument().getSourceRange()))
2830 NewTemplateParm->removeDefaultArgument();
2831
2832 // Merge default arguments for template template parameters
2833 TemplateTemplateParmDecl *OldTemplateParm
2834 = OldParams? cast<TemplateTemplateParmDecl>(*OldParam) : nullptr;
2835 if (NewTemplateParm->isParameterPack()) {
2836 assert(!NewTemplateParm->hasDefaultArgument() &&(static_cast <bool> (!NewTemplateParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "clang/lib/Sema/SemaTemplate.cpp", 2837, __extension__ __PRETTY_FUNCTION__
))
2837 "Parameter packs can't have a default argument!")(static_cast <bool> (!NewTemplateParm->hasDefaultArgument
() && "Parameter packs can't have a default argument!"
) ? void (0) : __assert_fail ("!NewTemplateParm->hasDefaultArgument() && \"Parameter packs can't have a default argument!\""
, "clang/lib/Sema/SemaTemplate.cpp", 2837, __extension__ __PRETTY_FUNCTION__
))
;
2838 if (!NewTemplateParm->isPackExpansion())
2839 SawParameterPack = true;
2840 } else if (OldTemplateParm &&
2841 hasVisibleDefaultArgument(OldTemplateParm) &&
2842 NewTemplateParm->hasDefaultArgument() &&
2843 (!SkipBody || !SkipBody->ShouldSkip)) {
2844 OldDefaultLoc = OldTemplateParm->getDefaultArgument().getLocation();
2845 NewDefaultLoc = NewTemplateParm->getDefaultArgument().getLocation();
2846 SawDefaultArgument = true;
2847 if (!OldTemplateParm->getOwningModule() ||
2848 isModuleUnitOfCurrentTU(OldTemplateParm->getOwningModule()))
2849 RedundantDefaultArg = true;
2850 else if (!getASTContext().isSameDefaultTemplateArgument(
2851 OldTemplateParm, NewTemplateParm)) {
2852 InconsistentDefaultArg = true;
2853 PrevModuleName =
2854 OldTemplateParm->getImportedOwningModule()->getFullModuleName();
2855 }
2856 PreviousDefaultArgLoc = NewDefaultLoc;
2857 } else if (OldTemplateParm && OldTemplateParm->hasDefaultArgument()) {
2858 // Merge the default argument from the old declaration to the
2859 // new declaration.
2860 NewTemplateParm->setInheritedDefaultArgument(Context, OldTemplateParm);
2861 PreviousDefaultArgLoc
2862 = OldTemplateParm->getDefaultArgument().getLocation();
2863 } else if (NewTemplateParm->hasDefaultArgument()) {
2864 SawDefaultArgument = true;
2865 PreviousDefaultArgLoc
2866 = NewTemplateParm->getDefaultArgument().getLocation();
2867 } else if (SawDefaultArgument)
2868 MissingDefaultArg = true;
2869 }
2870
2871 // C++11 [temp.param]p11:
2872 // If a template parameter of a primary class template or alias template
2873 // is a template parameter pack, it shall be the last template parameter.
2874 if (SawParameterPack && (NewParam + 1) != NewParamEnd &&
2875 (TPC == TPC_ClassTemplate || TPC == TPC_VarTemplate ||
2876 TPC == TPC_TypeAliasTemplate)) {
2877 Diag((*NewParam)->getLocation(),
2878 diag::err_template_param_pack_must_be_last_template_parameter);
2879 Invalid = true;
2880 }
2881
2882 // [basic.def.odr]/13:
2883 // There can be more than one definition of a
2884 // ...
2885 // default template argument
2886 // ...
2887 // in a program provided that each definition appears in a different
2888 // translation unit and the definitions satisfy the [same-meaning
2889 // criteria of the ODR].
2890 //
2891 // Simply, the design of modules allows the definition of template default
2892 // argument to be repeated across translation unit. Note that the ODR is
2893 // checked elsewhere. But it is still not allowed to repeat template default
2894 // argument in the same translation unit.
2895 if (RedundantDefaultArg) {
2896 Diag(NewDefaultLoc, diag::err_template_param_default_arg_redefinition);
2897 Diag(OldDefaultLoc, diag::note_template_param_prev_default_arg);
2898 Invalid = true;
2899 } else if (InconsistentDefaultArg) {
2900 // We could only diagnose about the case that the OldParam is imported.
2901 // The case NewParam is imported should be handled in ASTReader.
2902 Diag(NewDefaultLoc,
2903 diag::err_template_param_default_arg_inconsistent_redefinition);
2904 Diag(OldDefaultLoc,
2905 diag::note_template_param_prev_default_arg_in_other_module)
2906 << PrevModuleName;
2907 Invalid = true;
2908 } else if (MissingDefaultArg && TPC != TPC_FunctionTemplate) {
2909 // C++ [temp.param]p11:
2910 // If a template-parameter of a class template has a default
2911 // template-argument, each subsequent template-parameter shall either
2912 // have a default template-argument supplied or be a template parameter
2913 // pack.
2914 Diag((*NewParam)->getLocation(),
2915 diag::err_template_param_default_arg_missing);
2916 Diag(PreviousDefaultArgLoc, diag::note_template_param_prev_default_arg);
2917 Invalid = true;
2918 RemoveDefaultArguments = true;
2919 }
2920
2921 // If we have an old template parameter list that we're merging
2922 // in, move on to the next parameter.
2923 if (OldParams)
2924 ++OldParam;
2925 }
2926
2927 // We were missing some default arguments at the end of the list, so remove
2928 // all of the default arguments.
2929 if (RemoveDefaultArguments) {
2930 for (TemplateParameterList::iterator NewParam = NewParams->begin(),
2931 NewParamEnd = NewParams->end();
2932 NewParam != NewParamEnd; ++NewParam) {
2933 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*NewParam))
2934 TTP->removeDefaultArgument();
2935 else if (NonTypeTemplateParmDecl *NTTP
2936 = dyn_cast<NonTypeTemplateParmDecl>(*NewParam))
2937 NTTP->removeDefaultArgument();
2938 else
2939 cast<TemplateTemplateParmDecl>(*NewParam)->removeDefaultArgument();
2940 }
2941 }
2942
2943 return Invalid;
2944}
2945
2946namespace {
2947
2948/// A class which looks for a use of a certain level of template
2949/// parameter.
2950struct DependencyChecker : RecursiveASTVisitor<DependencyChecker> {
2951 typedef RecursiveASTVisitor<DependencyChecker> super;
2952
2953 unsigned Depth;
2954
2955 // Whether we're looking for a use of a template parameter that makes the
2956 // overall construct type-dependent / a dependent type. This is strictly
2957 // best-effort for now; we may fail to match at all for a dependent type
2958 // in some cases if this is set.
2959 bool IgnoreNonTypeDependent;
2960
2961 bool Match;
2962 SourceLocation MatchLoc;
2963
2964 DependencyChecker(unsigned Depth, bool IgnoreNonTypeDependent)
2965 : Depth(Depth), IgnoreNonTypeDependent(IgnoreNonTypeDependent),
2966 Match(false) {}
2967
2968 DependencyChecker(TemplateParameterList *Params, bool IgnoreNonTypeDependent)
2969 : IgnoreNonTypeDependent(IgnoreNonTypeDependent), Match(false) {
2970 NamedDecl *ND = Params->getParam(0);
2971 if (TemplateTypeParmDecl *PD = dyn_cast<TemplateTypeParmDecl>(ND)) {
2972 Depth = PD->getDepth();
2973 } else if (NonTypeTemplateParmDecl *PD =
2974 dyn_cast<NonTypeTemplateParmDecl>(ND)) {
2975 Depth = PD->getDepth();
2976 } else {
2977 Depth = cast<TemplateTemplateParmDecl>(ND)->getDepth();
2978 }
2979 }
2980
2981 bool Matches(unsigned ParmDepth, SourceLocation Loc = SourceLocation()) {
2982 if (ParmDepth >= Depth) {
2983 Match = true;
2984 MatchLoc = Loc;
2985 return true;
2986 }
2987 return false;
2988 }
2989
2990 bool TraverseStmt(Stmt *S, DataRecursionQueue *Q = nullptr) {
2991 // Prune out non-type-dependent expressions if requested. This can
2992 // sometimes result in us failing to find a template parameter reference
2993 // (if a value-dependent expression creates a dependent type), but this
2994 // mode is best-effort only.
2995 if (auto *E = dyn_cast_or_null<Expr>(S))
2996 if (IgnoreNonTypeDependent && !E->isTypeDependent())
2997 return true;
2998 return super::TraverseStmt(S, Q);
2999 }
3000
3001 bool TraverseTypeLoc(TypeLoc TL) {
3002 if (IgnoreNonTypeDependent && !TL.isNull() &&
3003 !TL.getType()->isDependentType())
3004 return true;
3005 return super::TraverseTypeLoc(TL);
3006 }
3007
3008 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
3009 return !Matches(TL.getTypePtr()->getDepth(), TL.getNameLoc());
3010 }
3011
3012 bool VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
3013 // For a best-effort search, keep looking until we find a location.
3014 return IgnoreNonTypeDependent || !Matches(T->getDepth());
3015 }
3016
3017 bool TraverseTemplateName(TemplateName N) {
3018 if (TemplateTemplateParmDecl *PD =
3019 dyn_cast_or_null<TemplateTemplateParmDecl>(N.getAsTemplateDecl()))
3020 if (Matches(PD->getDepth()))
3021 return false;
3022 return super::TraverseTemplateName(N);
3023 }
3024
3025 bool VisitDeclRefExpr(DeclRefExpr *E) {
3026 if (NonTypeTemplateParmDecl *PD =
3027 dyn_cast<NonTypeTemplateParmDecl>(E->getDecl()))
3028 if (Matches(PD->getDepth(), E->getExprLoc()))
3029 return false;
3030 return super::VisitDeclRefExpr(E);
3031 }
3032
3033 bool VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3034 return TraverseType(T->getReplacementType());
3035 }
3036
3037 bool
3038 VisitSubstTemplateTypeParmPackType(const SubstTemplateTypeParmPackType *T) {
3039 return TraverseTemplateArgument(T->getArgumentPack());
3040 }
3041
3042 bool TraverseInjectedClassNameType(const InjectedClassNameType *T) {
3043 return TraverseType(T->getInjectedSpecializationType());
3044 }
3045};
3046} // end anonymous namespace
3047
3048/// Determines whether a given type depends on the given parameter
3049/// list.
3050static bool
3051DependsOnTemplateParameters(QualType T, TemplateParameterList *Params) {
3052 if (!Params->size())
3053 return false;
3054
3055 DependencyChecker Checker(Params, /*IgnoreNonTypeDependent*/false);
3056 Checker.TraverseType(T);
3057 return Checker.Match;
3058}
3059
3060// Find the source range corresponding to the named type in the given
3061// nested-name-specifier, if any.
3062static SourceRange getRangeOfTypeInNestedNameSpecifier(ASTContext &Context,
3063 QualType T,
3064 const CXXScopeSpec &SS) {
3065 NestedNameSpecifierLoc NNSLoc(SS.getScopeRep(), SS.location_data());
3066 while (NestedNameSpecifier *NNS = NNSLoc.getNestedNameSpecifier()) {
3067 if (const Type *CurType = NNS->getAsType()) {
3068 if (Context.hasSameUnqualifiedType(T, QualType(CurType, 0)))
3069 return NNSLoc.getTypeLoc().getSourceRange();
3070 } else
3071 break;
3072
3073 NNSLoc = NNSLoc.getPrefix();
3074 }
3075
3076 return SourceRange();
3077}
3078
3079/// Match the given template parameter lists to the given scope
3080/// specifier, returning the template parameter list that applies to the
3081/// name.
3082///
3083/// \param DeclStartLoc the start of the declaration that has a scope
3084/// specifier or a template parameter list.
3085///
3086/// \param DeclLoc The location of the declaration itself.
3087///
3088/// \param SS the scope specifier that will be matched to the given template
3089/// parameter lists. This scope specifier precedes a qualified name that is
3090/// being declared.
3091///
3092/// \param TemplateId The template-id following the scope specifier, if there
3093/// is one. Used to check for a missing 'template<>'.
3094///
3095/// \param ParamLists the template parameter lists, from the outermost to the
3096/// innermost template parameter lists.
3097///
3098/// \param IsFriend Whether to apply the slightly different rules for
3099/// matching template parameters to scope specifiers in friend
3100/// declarations.
3101///
3102/// \param IsMemberSpecialization will be set true if the scope specifier
3103/// denotes a fully-specialized type, and therefore this is a declaration of
3104/// a member specialization.
3105///
3106/// \returns the template parameter list, if any, that corresponds to the
3107/// name that is preceded by the scope specifier @p SS. This template
3108/// parameter list may have template parameters (if we're declaring a
3109/// template) or may have no template parameters (if we're declaring a
3110/// template specialization), or may be NULL (if what we're declaring isn't
3111/// itself a template).
3112TemplateParameterList *Sema::MatchTemplateParametersToScopeSpecifier(
3113 SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS,
3114 TemplateIdAnnotation *TemplateId,
3115 ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend,
3116 bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic) {
3117 IsMemberSpecialization = false;
3118 Invalid = false;
3119
3120 // The sequence of nested types to which we will match up the template
3121 // parameter lists. We first build this list by starting with the type named
3122 // by the nested-name-specifier and walking out until we run out of types.
3123 SmallVector<QualType, 4> NestedTypes;
3124 QualType T;
3125 if (SS.getScopeRep()) {
3126 if (CXXRecordDecl *Record
3127 = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS, true)))
3128 T = Context.getTypeDeclType(Record);
3129 else
3130 T = QualType(SS.getScopeRep()->getAsType(), 0);
3131 }
3132
3133 // If we found an explicit specialization that prevents us from needing
3134 // 'template<>' headers, this will be set to the location of that
3135 // explicit specialization.
3136 SourceLocation ExplicitSpecLoc;
3137
3138 while (!T.isNull()) {
3139 NestedTypes.push_back(T);
3140
3141 // Retrieve the parent of a record type.
3142 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3143 // If this type is an explicit specialization, we're done.
3144 if (ClassTemplateSpecializationDecl *Spec
3145 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3146 if (!isa<ClassTemplatePartialSpecializationDecl>(Spec) &&
3147 Spec->getSpecializationKind() == TSK_ExplicitSpecialization) {
3148 ExplicitSpecLoc = Spec->getLocation();
3149 break;
3150 }
3151 } else if (Record->getTemplateSpecializationKind()
3152 == TSK_ExplicitSpecialization) {
3153 ExplicitSpecLoc = Record->getLocation();
3154 break;
3155 }
3156
3157 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Record->getParent()))
3158 T = Context.getTypeDeclType(Parent);
3159 else
3160 T = QualType();
3161 continue;
3162 }
3163
3164 if (const TemplateSpecializationType *TST
3165 = T->getAs<TemplateSpecializationType>()) {
3166 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3167 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Template->getDeclContext()))
3168 T = Context.getTypeDeclType(Parent);
3169 else
3170 T = QualType();
3171 continue;
3172 }
3173 }
3174
3175 // Look one step prior in a dependent template specialization type.
3176 if (const DependentTemplateSpecializationType *DependentTST
3177 = T->getAs<DependentTemplateSpecializationType>()) {
3178 if (NestedNameSpecifier *NNS = DependentTST->getQualifier())
3179 T = QualType(NNS->getAsType(), 0);
3180 else
3181 T = QualType();
3182 continue;
3183 }
3184
3185 // Look one step prior in a dependent name type.
3186 if (const DependentNameType *DependentName = T->getAs<DependentNameType>()){
3187 if (NestedNameSpecifier *NNS = DependentName->getQualifier())
3188 T = QualType(NNS->getAsType(), 0);
3189 else
3190 T = QualType();
3191 continue;
3192 }
3193
3194 // Retrieve the parent of an enumeration type.
3195 if (const EnumType *EnumT = T->getAs<EnumType>()) {
3196 // FIXME: Forward-declared enums require a TSK_ExplicitSpecialization
3197 // check here.
3198 EnumDecl *Enum = EnumT->getDecl();
3199
3200 // Get to the parent type.
3201 if (TypeDecl *Parent = dyn_cast<TypeDecl>(Enum->getParent()))
3202 T = Context.getTypeDeclType(Parent);
3203 else
3204 T = QualType();
3205 continue;
3206 }
3207
3208 T = QualType();
3209 }
3210 // Reverse the nested types list, since we want to traverse from the outermost
3211 // to the innermost while checking template-parameter-lists.
3212 std::reverse(NestedTypes.begin(), NestedTypes.end());
3213
3214 // C++0x [temp.expl.spec]p17:
3215 // A member or a member template may be nested within many
3216 // enclosing class templates. In an explicit specialization for
3217 // such a member, the member declaration shall be preceded by a
3218 // template<> for each enclosing class template that is
3219 // explicitly specialized.
3220 bool SawNonEmptyTemplateParameterList = false;
3221
3222 auto CheckExplicitSpecialization = [&](SourceRange Range, bool Recovery) {
3223 if (SawNonEmptyTemplateParameterList) {
3224 if (!SuppressDiagnostic)
3225 Diag(DeclLoc, diag::err_specialize_member_of_template)
3226 << !Recovery << Range;
3227 Invalid = true;
3228 IsMemberSpecialization = false;
3229 return true;
3230 }
3231
3232 return false;
3233 };
3234
3235 auto DiagnoseMissingExplicitSpecialization = [&] (SourceRange Range) {
3236 // Check that we can have an explicit specialization here.
3237 if (CheckExplicitSpecialization(Range, true))
3238 return true;
3239
3240 // We don't have a template header, but we should.
3241 SourceLocation ExpectedTemplateLoc;
3242 if (!ParamLists.empty())
3243 ExpectedTemplateLoc = ParamLists[0]->getTemplateLoc();
3244 else
3245 ExpectedTemplateLoc = DeclStartLoc;
3246
3247 if (!SuppressDiagnostic)
3248 Diag(DeclLoc, diag::err_template_spec_needs_header)
3249 << Range
3250 << FixItHint::CreateInsertion(ExpectedTemplateLoc, "template<> ");
3251 return false;
3252 };
3253
3254 unsigned ParamIdx = 0;
3255 for (unsigned TypeIdx = 0, NumTypes = NestedTypes.size(); TypeIdx != NumTypes;
3256 ++TypeIdx) {
3257 T = NestedTypes[TypeIdx];
3258
3259 // Whether we expect a 'template<>' header.
3260 bool NeedEmptyTemplateHeader = false;
3261
3262 // Whether we expect a template header with parameters.
3263 bool NeedNonemptyTemplateHeader = false;
3264
3265 // For a dependent type, the set of template parameters that we
3266 // expect to see.
3267 TemplateParameterList *ExpectedTemplateParams = nullptr;
3268
3269 // C++0x [temp.expl.spec]p15:
3270 // A member or a member template may be nested within many enclosing
3271 // class templates. In an explicit specialization for such a member, the
3272 // member declaration shall be preceded by a template<> for each
3273 // enclosing class template that is explicitly specialized.
3274 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) {
3275 if (ClassTemplatePartialSpecializationDecl *Partial
3276 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
3277 ExpectedTemplateParams = Partial->getTemplateParameters();
3278 NeedNonemptyTemplateHeader = true;
3279 } else if (Record->isDependentType()) {
3280 if (Record->getDescribedClassTemplate()) {
3281 ExpectedTemplateParams = Record->getDescribedClassTemplate()
3282 ->getTemplateParameters();
3283 NeedNonemptyTemplateHeader = true;
3284 }
3285 } else if (ClassTemplateSpecializationDecl *Spec
3286 = dyn_cast<ClassTemplateSpecializationDecl>(Record)) {
3287 // C++0x [temp.expl.spec]p4:
3288 // Members of an explicitly specialized class template are defined
3289 // in the same manner as members of normal classes, and not using
3290 // the template<> syntax.
3291 if (Spec->getSpecializationKind() != TSK_ExplicitSpecialization)
3292 NeedEmptyTemplateHeader = true;
3293 else
3294 continue;
3295 } else if (Record->getTemplateSpecializationKind()) {
3296 if (Record->getTemplateSpecializationKind()
3297 != TSK_ExplicitSpecialization &&
3298 TypeIdx == NumTypes - 1)
3299 IsMemberSpecialization = true;
3300
3301 continue;
3302 }
3303 } else if (const TemplateSpecializationType *TST
3304 = T->getAs<TemplateSpecializationType>()) {
3305 if (TemplateDecl *Template = TST->getTemplateName().getAsTemplateDecl()) {
3306 ExpectedTemplateParams = Template->getTemplateParameters();
3307 NeedNonemptyTemplateHeader = true;
3308 }
3309 } else if (T->getAs<DependentTemplateSpecializationType>()) {
3310 // FIXME: We actually could/should check the template arguments here
3311 // against the corresponding template parameter list.
3312 NeedNonemptyTemplateHeader = false;
3313 }
3314
3315 // C++ [temp.expl.spec]p16:
3316 // In an explicit specialization declaration for a member of a class
3317 // template or a member template that ap- pears in namespace scope, the
3318 // member template and some of its enclosing class templates may remain
3319 // unspecialized, except that the declaration shall not explicitly
3320 // specialize a class member template if its en- closing class templates
3321 // are not explicitly specialized as well.
3322 if (ParamIdx < ParamLists.size()) {
3323 if (ParamLists[ParamIdx]->size() == 0) {
3324 if (CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3325 false))
3326 return nullptr;
3327 } else
3328 SawNonEmptyTemplateParameterList = true;
3329 }
3330
3331 if (NeedEmptyTemplateHeader) {
3332 // If we're on the last of the types, and we need a 'template<>' header
3333 // here, then it's a member specialization.
3334 if (TypeIdx == NumTypes - 1)
3335 IsMemberSpecialization = true;
3336
3337 if (ParamIdx < ParamLists.size()) {
3338 if (ParamLists[ParamIdx]->size() > 0) {
3339 // The header has template parameters when it shouldn't. Complain.
3340 if (!SuppressDiagnostic)
3341 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3342 diag::err_template_param_list_matches_nontemplate)
3343 << T
3344 << SourceRange(ParamLists[ParamIdx]->getLAngleLoc(),
3345 ParamLists[ParamIdx]->getRAngleLoc())
3346 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3347 Invalid = true;
3348 return nullptr;
3349 }
3350
3351 // Consume this template header.
3352 ++ParamIdx;
3353 continue;
3354 }
3355
3356 if (!IsFriend)
3357 if (DiagnoseMissingExplicitSpecialization(
3358 getRangeOfTypeInNestedNameSpecifier(Context, T, SS)))
3359 return nullptr;
3360
3361 continue;
3362 }
3363
3364 if (NeedNonemptyTemplateHeader) {
3365 // In friend declarations we can have template-ids which don't
3366 // depend on the corresponding template parameter lists. But
3367 // assume that empty parameter lists are supposed to match this
3368 // template-id.
3369 if (IsFriend && T->isDependentType()) {
3370 if (ParamIdx < ParamLists.size() &&
3371 DependsOnTemplateParameters(T, ParamLists[ParamIdx]))
3372 ExpectedTemplateParams = nullptr;
3373 else
3374 continue;
3375 }
3376
3377 if (ParamIdx < ParamLists.size()) {
3378 // Check the template parameter list, if we can.
3379 if (ExpectedTemplateParams &&
3380 !TemplateParameterListsAreEqual(ParamLists[ParamIdx],
3381 ExpectedTemplateParams,
3382 !SuppressDiagnostic, TPL_TemplateMatch))
3383 Invalid = true;
3384
3385 if (!Invalid &&
3386 CheckTemplateParameterList(ParamLists[ParamIdx], nullptr,
3387 TPC_ClassTemplateMember))
3388 Invalid = true;
3389
3390 ++ParamIdx;
3391 continue;
3392 }
3393
3394 if (!SuppressDiagnostic)
3395 Diag(DeclLoc, diag::err_template_spec_needs_template_parameters)
3396 << T
3397 << getRangeOfTypeInNestedNameSpecifier(Context, T, SS);
3398 Invalid = true;
3399 continue;
3400 }
3401 }
3402
3403 // If there were at least as many template-ids as there were template
3404 // parameter lists, then there are no template parameter lists remaining for
3405 // the declaration itself.
3406 if (ParamIdx >= ParamLists.size()) {
3407 if (TemplateId && !IsFriend) {
3408 // We don't have a template header for the declaration itself, but we
3409 // should.
3410 DiagnoseMissingExplicitSpecialization(SourceRange(TemplateId->LAngleLoc,
3411 TemplateId->RAngleLoc));
3412
3413 // Fabricate an empty template parameter list for the invented header.
3414 return TemplateParameterList::Create(Context, SourceLocation(),
3415 SourceLocation(), None,
3416 SourceLocation(), nullptr);
3417 }
3418
3419 return nullptr;
3420 }
3421
3422 // If there were too many template parameter lists, complain about that now.
3423 if (ParamIdx < ParamLists.size() - 1) {
3424 bool HasAnyExplicitSpecHeader = false;
3425 bool AllExplicitSpecHeaders = true;
3426 for (unsigned I = ParamIdx, E = ParamLists.size() - 1; I != E; ++I) {
3427 if (ParamLists[I]->size() == 0)
3428 HasAnyExplicitSpecHeader = true;
3429 else
3430 AllExplicitSpecHeaders = false;
3431 }
3432
3433 if (!SuppressDiagnostic)
3434 Diag(ParamLists[ParamIdx]->getTemplateLoc(),
3435 AllExplicitSpecHeaders ? diag::warn_template_spec_extra_headers
3436 : diag::err_template_spec_extra_headers)
3437 << SourceRange(ParamLists[ParamIdx]->getTemplateLoc(),
3438 ParamLists[ParamLists.size() - 2]->getRAngleLoc());
3439
3440 // If there was a specialization somewhere, such that 'template<>' is
3441 // not required, and there were any 'template<>' headers, note where the
3442 // specialization occurred.
3443 if (ExplicitSpecLoc.isValid() && HasAnyExplicitSpecHeader &&
3444 !SuppressDiagnostic)
3445 Diag(ExplicitSpecLoc,
3446 diag::note_explicit_template_spec_does_not_need_header)
3447 << NestedTypes.back();
3448
3449 // We have a template parameter list with no corresponding scope, which
3450 // means that the resulting template declaration can't be instantiated
3451 // properly (we'll end up with dependent nodes when we shouldn't).
3452 if (!AllExplicitSpecHeaders)
3453 Invalid = true;
3454 }
3455
3456 // C++ [temp.expl.spec]p16:
3457 // In an explicit specialization declaration for a member of a class
3458 // template or a member template that ap- pears in namespace scope, the
3459 // member template and some of its enclosing class templates may remain
3460 // unspecialized, except that the declaration shall not explicitly
3461 // specialize a class member template if its en- closing class templates
3462 // are not explicitly specialized as well.
3463 if (ParamLists.back()->size() == 0 &&
3464 CheckExplicitSpecialization(ParamLists[ParamIdx]->getSourceRange(),
3465 false))
3466 return nullptr;
3467
3468 // Return the last template parameter list, which corresponds to the
3469 // entity being declared.
3470 return ParamLists.back();
3471}
3472
3473void Sema::NoteAllFoundTemplates(TemplateName Name) {
3474 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
3475 Diag(Template->getLocation(), diag::note_template_declared_here)
3476 << (isa<FunctionTemplateDecl>(Template)
3477 ? 0
3478 : isa<ClassTemplateDecl>(Template)
3479 ? 1
3480 : isa<VarTemplateDecl>(Template)
3481 ? 2
3482 : isa<TypeAliasTemplateDecl>(Template) ? 3 : 4)
3483 << Template->getDeclName();
3484 return;
3485 }
3486
3487 if (OverloadedTemplateStorage *OST = Name.getAsOverloadedTemplate()) {
3488 for (OverloadedTemplateStorage::iterator I = OST->begin(),
3489 IEnd = OST->end();
3490 I != IEnd; ++I)
3491 Diag((*I)->getLocation(), diag::note_template_declared_here)
3492 << 0 << (*I)->getDeclName();
3493
3494 return;
3495 }
3496}
3497
3498static QualType
3499checkBuiltinTemplateIdType(Sema &SemaRef, BuiltinTemplateDecl *BTD,
3500 const SmallVectorImpl<TemplateArgument> &Converted,
3501 SourceLocation TemplateLoc,
3502 TemplateArgumentListInfo &TemplateArgs) {
3503 ASTContext &Context = SemaRef.getASTContext();
3504 switch (BTD->getBuiltinTemplateKind()) {
3505 case BTK__make_integer_seq: {
3506 // Specializations of __make_integer_seq<S, T, N> are treated like
3507 // S<T, 0, ..., N-1>.
3508
3509 // C++14 [inteseq.intseq]p1:
3510 // T shall be an integer type.
3511 if (!Converted[1].getAsType()->isIntegralType(Context)) {
3512 SemaRef.Diag(TemplateArgs[1].getLocation(),
3513 diag::err_integer_sequence_integral_element_type);
3514 return QualType();
3515 }
3516
3517 // C++14 [inteseq.make]p1:
3518 // If N is negative the program is ill-formed.
3519 TemplateArgument NumArgsArg = Converted[2];
3520 llvm::APSInt NumArgs = NumArgsArg.getAsIntegral();
3521 if (NumArgs < 0) {
3522 SemaRef.Diag(TemplateArgs[2].getLocation(),
3523 diag::err_integer_sequence_negative_length);
3524 return QualType();
3525 }
3526
3527 QualType ArgTy = NumArgsArg.getIntegralType();
3528 TemplateArgumentListInfo SyntheticTemplateArgs;
3529 // The type argument gets reused as the first template argument in the
3530 // synthetic template argument list.
3531 SyntheticTemplateArgs.addArgument(TemplateArgs[1]);
3532 // Expand N into 0 ... N-1.
3533 for (llvm::APSInt I(NumArgs.getBitWidth(), NumArgs.isUnsigned());
3534 I < NumArgs; ++I) {
3535 TemplateArgument TA(Context, I, ArgTy);
3536 SyntheticTemplateArgs.addArgument(SemaRef.getTrivialTemplateArgumentLoc(
3537 TA, ArgTy, TemplateArgs[2].getLocation()));
3538 }
3539 // The first template argument will be reused as the template decl that
3540 // our synthetic template arguments will be applied to.
3541 return SemaRef.CheckTemplateIdType(Converted[0].getAsTemplate(),
3542 TemplateLoc, SyntheticTemplateArgs);
3543 }
3544
3545 case BTK__type_pack_element:
3546 // Specializations of
3547 // __type_pack_element<Index, T_1, ..., T_N>
3548 // are treated like T_Index.
3549 assert(Converted.size() == 2 &&(static_cast <bool> (Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? void (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "clang/lib/Sema/SemaTemplate.cpp", 3550, __extension__ __PRETTY_FUNCTION__
))
3550 "__type_pack_element should be given an index and a parameter pack")(static_cast <bool> (Converted.size() == 2 && "__type_pack_element should be given an index and a parameter pack"
) ? void (0) : __assert_fail ("Converted.size() == 2 && \"__type_pack_element should be given an index and a parameter pack\""
, "clang/lib/Sema/SemaTemplate.cpp", 3550, __extension__ __PRETTY_FUNCTION__
))
;
3551
3552 // If the Index is out of bounds, the program is ill-formed.
3553 TemplateArgument IndexArg = Converted[0], Ts = Converted[1];
3554 llvm::APSInt Index = IndexArg.getAsIntegral();
3555 assert(Index >= 0 && "the index used with __type_pack_element should be of "(static_cast <bool> (Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? void (0) : __assert_fail
("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "clang/lib/Sema/SemaTemplate.cpp", 3556, __extension__ __PRETTY_FUNCTION__
))
3556 "type std::size_t, and hence be non-negative")(static_cast <bool> (Index >= 0 && "the index used with __type_pack_element should be of "
"type std::size_t, and hence be non-negative") ? void (0) : __assert_fail
("Index >= 0 && \"the index used with __type_pack_element should be of \" \"type std::size_t, and hence be non-negative\""
, "clang/lib/Sema/SemaTemplate.cpp", 3556, __extension__ __PRETTY_FUNCTION__
))
;
3557 if (Index >= Ts.pack_size()) {
3558 SemaRef.Diag(TemplateArgs[0].getLocation(),
3559 diag::err_type_pack_element_out_of_bounds);
3560 return QualType();
3561 }
3562
3563 // We simply return the type at index `Index`.
3564 auto Nth = std::next(Ts.pack_begin(), Index.getExtValue());
3565 return Nth->getAsType();
3566 }
3567 llvm_unreachable("unexpected BuiltinTemplateDecl!")::llvm::llvm_unreachable_internal("unexpected BuiltinTemplateDecl!"
, "clang/lib/Sema/SemaTemplate.cpp", 3567)
;
3568}
3569
3570/// Determine whether this alias template is "enable_if_t".
3571/// libc++ >=14 uses "__enable_if_t" in C++11 mode.
3572static bool isEnableIfAliasTemplate(TypeAliasTemplateDecl *AliasTemplate) {
3573 return AliasTemplate->getName().equals("enable_if_t") ||
3574 AliasTemplate->getName().equals("__enable_if_t");
3575}
3576
3577/// Collect all of the separable terms in the given condition, which
3578/// might be a conjunction.
3579///
3580/// FIXME: The right answer is to convert the logical expression into
3581/// disjunctive normal form, so we can find the first failed term
3582/// within each possible clause.
3583static void collectConjunctionTerms(Expr *Clause,
3584 SmallVectorImpl<Expr *> &Terms) {
3585 if (auto BinOp = dyn_cast<BinaryOperator>(Clause->IgnoreParenImpCasts())) {
3586 if (BinOp->getOpcode() == BO_LAnd) {
3587 collectConjunctionTerms(BinOp->getLHS(), Terms);
3588 collectConjunctionTerms(BinOp->getRHS(), Terms);
3589 return;
3590 }
3591 }
3592
3593 Terms.push_back(Clause);
3594}
3595
3596// The ranges-v3 library uses an odd pattern of a top-level "||" with
3597// a left-hand side that is value-dependent but never true. Identify
3598// the idiom and ignore that term.
3599static Expr *lookThroughRangesV3Condition(Preprocessor &PP, Expr *Cond) {
3600 // Top-level '||'.
3601 auto *BinOp = dyn_cast<BinaryOperator>(Cond->IgnoreParenImpCasts());
3602 if (!BinOp) return Cond;
3603
3604 if (BinOp->getOpcode() != BO_LOr) return Cond;
3605
3606 // With an inner '==' that has a literal on the right-hand side.
3607 Expr *LHS = BinOp->getLHS();
3608 auto *InnerBinOp = dyn_cast<BinaryOperator>(LHS->IgnoreParenImpCasts());
3609 if (!InnerBinOp) return Cond;
3610
3611 if (InnerBinOp->getOpcode() != BO_EQ ||
3612 !isa<IntegerLiteral>(InnerBinOp->getRHS()))
3613 return Cond;
3614
3615 // If the inner binary operation came from a macro expansion named
3616 // CONCEPT_REQUIRES or CONCEPT_REQUIRES_, return the right-hand side
3617 // of the '||', which is the real, user-provided condition.
3618 SourceLocation Loc = InnerBinOp->getExprLoc();
3619 if (!Loc.isMacroID()) return Cond;
3620
3621 StringRef MacroName = PP.getImmediateMacroName(Loc);
3622 if (MacroName == "CONCEPT_REQUIRES" || MacroName == "CONCEPT_REQUIRES_")
3623 return BinOp->getRHS();
3624
3625 return Cond;
3626}
3627
3628namespace {
3629
3630// A PrinterHelper that prints more helpful diagnostics for some sub-expressions
3631// within failing boolean expression, such as substituting template parameters
3632// for actual types.
3633class FailedBooleanConditionPrinterHelper : public PrinterHelper {
3634public:
3635 explicit FailedBooleanConditionPrinterHelper(const PrintingPolicy &P)
3636 : Policy(P) {}
3637
3638 bool handledStmt(Stmt *E, raw_ostream &OS) override {
3639 const auto *DR = dyn_cast<DeclRefExpr>(E);
3640 if (DR && DR->getQualifier()) {
3641 // If this is a qualified name, expand the template arguments in nested
3642 // qualifiers.
3643 DR->getQualifier()->print(OS, Policy, true);
3644 // Then print the decl itself.
3645 const ValueDecl *VD = DR->getDecl();
3646 OS << VD->getName();
3647 if (const auto *IV = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
3648 // This is a template variable, print the expanded template arguments.
3649 printTemplateArgumentList(
3650 OS, IV->getTemplateArgs().asArray(), Policy,
3651 IV->getSpecializedTemplate()->getTemplateParameters());
3652 }
3653 return true;
3654 }
3655 return false;
3656 }
3657
3658private:
3659 const PrintingPolicy Policy;
3660};
3661
3662} // end anonymous namespace
3663
3664std::pair<Expr *, std::string>
3665Sema::findFailedBooleanCondition(Expr *Cond) {
3666 Cond = lookThroughRangesV3Condition(PP, Cond);
3667
3668 // Separate out all of the terms in a conjunction.
3669 SmallVector<Expr *, 4> Terms;
3670 collectConjunctionTerms(Cond, Terms);
3671
3672 // Determine which term failed.
3673 Expr *FailedCond = nullptr;
3674 for (Expr *Term : Terms) {
3675 Expr *TermAsWritten = Term->IgnoreParenImpCasts();
3676
3677 // Literals are uninteresting.
3678 if (isa<CXXBoolLiteralExpr>(TermAsWritten) ||
3679 isa<IntegerLiteral>(TermAsWritten))
3680 continue;
3681
3682 // The initialization of the parameter from the argument is
3683 // a constant-evaluated context.
3684 EnterExpressionEvaluationContext ConstantEvaluated(
3685 *this, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3686
3687 bool Succeeded;
3688 if (Term->EvaluateAsBooleanCondition(Succeeded, Context) &&
3689 !Succeeded) {
3690 FailedCond = TermAsWritten;
3691 break;
3692 }
3693 }
3694 if (!FailedCond)
3695 FailedCond = Cond->IgnoreParenImpCasts();
3696
3697 std::string Description;
3698 {
3699 llvm::raw_string_ostream Out(Description);
3700 PrintingPolicy Policy = getPrintingPolicy();
3701 Policy.PrintCanonicalTypes = true;
3702 FailedBooleanConditionPrinterHelper Helper(Policy);
3703 FailedCond->printPretty(Out, &Helper, Policy, 0, "\n", nullptr);
3704 }
3705 return { FailedCond, Description };
3706}
3707
3708QualType Sema::CheckTemplateIdType(TemplateName Name,
3709 SourceLocation TemplateLoc,
3710 TemplateArgumentListInfo &TemplateArgs) {
3711 DependentTemplateName *DTN
3712 = Name.getUnderlying().getAsDependentTemplateName();
3713 if (DTN && DTN->isIdentifier())
3714 // When building a template-id where the template-name is dependent,
3715 // assume the template is a type template. Either our assumption is
3716 // correct, or the code is ill-formed and will be diagnosed when the
3717 // dependent name is substituted.
3718 return Context.getDependentTemplateSpecializationType(ETK_None,
3719 DTN->getQualifier(),
3720 DTN->getIdentifier(),
3721 TemplateArgs);
3722
3723 if (Name.getAsAssumedTemplateName() &&
3724 resolveAssumedTemplateNameAsType(/*Scope*/nullptr, Name, TemplateLoc))
3725 return QualType();
3726
3727 TemplateDecl *Template = Name.getAsTemplateDecl();
3728 if (!Template || isa<FunctionTemplateDecl>(Template) ||
3729 isa<VarTemplateDecl>(Template) || isa<ConceptDecl>(Template)) {
3730 // We might have a substituted template template parameter pack. If so,
3731 // build a template specialization type for it.
3732 if (Name.getAsSubstTemplateTemplateParmPack())
3733 return Context.getTemplateSpecializationType(Name, TemplateArgs);
3734
3735 Diag(TemplateLoc, diag::err_template_id_not_a_type)
3736 << Name;
3737 NoteAllFoundTemplates(Name);
3738 return QualType();
3739 }
3740
3741 // Check that the template argument list is well-formed for this
3742 // template.
3743 SmallVector<TemplateArgument, 4> Converted;
3744 if (CheckTemplateArgumentList(Template, TemplateLoc, TemplateArgs,
3745 false, Converted,
3746 /*UpdateArgsWithConversions=*/true))
3747 return QualType();
3748
3749 QualType CanonType;
3750
3751 if (TypeAliasTemplateDecl *AliasTemplate =
3752 dyn_cast<TypeAliasTemplateDecl>(Template)) {
3753
3754 // Find the canonical type for this type alias template specialization.
3755 TypeAliasDecl *Pattern = AliasTemplate->getTemplatedDecl();
3756 if (Pattern->isInvalidDecl())
3757 return QualType();
3758
3759 TemplateArgumentList StackTemplateArgs(TemplateArgumentList::OnStack,
3760 Converted);
3761
3762 // Only substitute for the innermost template argument list.
3763 MultiLevelTemplateArgumentList TemplateArgLists;
3764 TemplateArgLists.addOuterTemplateArguments(&StackTemplateArgs);
3765 TemplateArgLists.addOuterRetainedLevels(
3766 AliasTemplate->getTemplateParameters()->getDepth());
3767
3768 LocalInstantiationScope Scope(*this);
3769 InstantiatingTemplate Inst(*this, TemplateLoc, Template);
3770 if (Inst.isInvalid())
3771 return QualType();
3772
3773 CanonType = SubstType(Pattern->getUnderlyingType(),
3774 TemplateArgLists, AliasTemplate->getLocation(),
3775 AliasTemplate->getDeclName());
3776 if (CanonType.isNull()) {
3777 // If this was enable_if and we failed to find the nested type
3778 // within enable_if in a SFINAE context, dig out the specific
3779 // enable_if condition that failed and present that instead.
3780 if (isEnableIfAliasTemplate(AliasTemplate)) {
3781 if (auto DeductionInfo = isSFINAEContext()) {
3782 if (*DeductionInfo &&
3783 (*DeductionInfo)->hasSFINAEDiagnostic() &&
3784 (*DeductionInfo)->peekSFINAEDiagnostic().second.getDiagID() ==
3785 diag::err_typename_nested_not_found_enable_if &&
3786 TemplateArgs[0].getArgument().getKind()
3787 == TemplateArgument::Expression) {
3788 Expr *FailedCond;
3789 std::string FailedDescription;
3790 std::tie(FailedCond, FailedDescription) =
3791 findFailedBooleanCondition(TemplateArgs[0].getSourceExpression());
3792
3793 // Remove the old SFINAE diagnostic.
3794 PartialDiagnosticAt OldDiag =
3795 {SourceLocation(), PartialDiagnostic::NullDiagnostic()};
3796 (*DeductionInfo)->takeSFINAEDiagnostic(OldDiag);
3797
3798 // Add a new SFINAE diagnostic specifying which condition
3799 // failed.
3800 (*DeductionInfo)->addSFINAEDiagnostic(
3801 OldDiag.first,
3802 PDiag(diag::err_typename_nested_not_found_requirement)
3803 << FailedDescription
3804 << FailedCond->getSourceRange());
3805 }
3806 }
3807 }
3808
3809 return QualType();
3810 }
3811 } else if (Name.isDependent() ||
3812 TemplateSpecializationType::anyDependentTemplateArguments(
3813 TemplateArgs, Converted)) {
3814 // This class template specialization is a dependent
3815 // type. Therefore, its canonical type is another class template
3816 // specialization type that contains all of the converted
3817 // arguments in canonical form. This ensures that, e.g., A<T> and
3818 // A<T, T> have identical types when A is declared as:
3819 //
3820 // template<typename T, typename U = T> struct A;
3821 CanonType = Context.getCanonicalTemplateSpecializationType(Name, Converted);
3822
3823 // This might work out to be a current instantiation, in which
3824 // case the canonical type needs to be the InjectedClassNameType.
3825 //
3826 // TODO: in theory this could be a simple hashtable lookup; most
3827 // changes to CurContext don't change the set of current
3828 // instantiations.
3829 if (isa<ClassTemplateDecl>(Template)) {
3830 for (DeclContext *Ctx = CurContext; Ctx; Ctx = Ctx->getLookupParent()) {
3831 // If we get out to a namespace, we're done.
3832 if (Ctx->isFileContext()) break;
3833
3834 // If this isn't a record, keep looking.
3835 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx);
3836 if (!Record) continue;
3837
3838 // Look for one of the two cases with InjectedClassNameTypes
3839 // and check whether it's the same template.
3840 if (!isa<ClassTemplatePartialSpecializationDecl>(Record) &&
3841 !Record->getDescribedClassTemplate())
3842 continue;
3843
3844 // Fetch the injected class name type and check whether its
3845 // injected type is equal to the type we just built.
3846 QualType ICNT = Context.getTypeDeclType(Record);
3847 QualType Injected = cast<InjectedClassNameType>(ICNT)
3848 ->getInjectedSpecializationType();
3849
3850 if (CanonType != Injected->getCanonicalTypeInternal())
3851 continue;
3852
3853 // If so, the canonical type of this TST is the injected
3854 // class name type of the record we just found.
3855 assert(ICNT.isCanonical())(static_cast <bool> (ICNT.isCanonical()) ? void (0) : __assert_fail
("ICNT.isCanonical()", "clang/lib/Sema/SemaTemplate.cpp", 3855
, __extension__ __PRETTY_FUNCTION__))
;
3856 CanonType = ICNT;
3857 break;
3858 }
3859 }
3860 } else if (ClassTemplateDecl *ClassTemplate
3861 = dyn_cast<ClassTemplateDecl>(Template)) {
3862 // Find the class template specialization declaration that
3863 // corresponds to these arguments.
3864 void *InsertPos = nullptr;
3865 ClassTemplateSpecializationDecl *Decl
3866 = ClassTemplate->findSpecialization(Converted, InsertPos);
3867 if (!Decl) {
3868 // This is the first time we have referenced this class template
3869 // specialization. Create the canonical declaration and add it to
3870 // the set of specializations.
3871 Decl = ClassTemplateSpecializationDecl::Create(
3872 Context, ClassTemplate->getTemplatedDecl()->getTagKind(),
3873 ClassTemplate->getDeclContext(),
3874 ClassTemplate->getTemplatedDecl()->getBeginLoc(),
3875 ClassTemplate->getLocation(), ClassTemplate, Converted, nullptr);
3876 ClassTemplate->AddSpecialization(Decl, InsertPos);
3877 if (ClassTemplate->isOutOfLine())
3878 Decl->setLexicalDeclContext(ClassTemplate->getLexicalDeclContext());
3879 }
3880
3881 if (Decl->getSpecializationKind() == TSK_Undeclared &&
3882 ClassTemplate->getTemplatedDecl()->hasAttrs()) {
3883 InstantiatingTemplate Inst(*this, TemplateLoc, Decl);
3884 if (!Inst.isInvalid()) {
3885 MultiLevelTemplateArgumentList TemplateArgLists;
3886 TemplateArgLists.addOuterTemplateArguments(Converted);
3887 InstantiateAttrsForDecl(TemplateArgLists,
3888 ClassTemplate->getTemplatedDecl(), Decl);
3889 }
3890 }
3891
3892 // Diagnose uses of this specialization.
3893 (void)DiagnoseUseOfDecl(Decl, TemplateLoc);
3894
3895 CanonType = Context.getTypeDeclType(Decl);
3896 assert(isa<RecordType>(CanonType) &&(static_cast <bool> (isa<RecordType>(CanonType) &&
"type of non-dependent specialization is not a RecordType") ?
void (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "clang/lib/Sema/SemaTemplate.cpp", 3897, __extension__ __PRETTY_FUNCTION__
))
3897 "type of non-dependent specialization is not a RecordType")(static_cast <bool> (isa<RecordType>(CanonType) &&
"type of non-dependent specialization is not a RecordType") ?
void (0) : __assert_fail ("isa<RecordType>(CanonType) && \"type of non-dependent specialization is not a RecordType\""
, "clang/lib/Sema/SemaTemplate.cpp", 3897, __extension__ __PRETTY_FUNCTION__
))
;
3898 } else if (auto *BTD = dyn_cast<BuiltinTemplateDecl>(Template)) {
3899 CanonType = checkBuiltinTemplateIdType(*this, BTD, Converted, TemplateLoc,
3900 TemplateArgs);
3901 }
3902
3903 // Build the fully-sugared type for this class template
3904 // specialization, which refers back to the class template
3905 // specialization we created or found.
3906 return Context.getTemplateSpecializationType(Name, TemplateArgs, CanonType);
3907}
3908
3909void Sema::ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &ParsedName,
3910 TemplateNameKind &TNK,
3911 SourceLocation NameLoc,
3912 IdentifierInfo *&II) {
3913 assert(TNK == TNK_Undeclared_template && "not an undeclared template name")(static_cast <bool> (TNK == TNK_Undeclared_template &&
"not an undeclared template name") ? void (0) : __assert_fail
("TNK == TNK_Undeclared_template && \"not an undeclared template name\""
, "clang/lib/Sema/SemaTemplate.cpp", 3913, __extension__ __PRETTY_FUNCTION__
))
;
3914
3915 TemplateName Name = ParsedName.get();
3916 auto *ATN = Name.getAsAssumedTemplateName();
3917 assert(ATN && "not an assumed template name")(static_cast <bool> (ATN && "not an assumed template name"
) ? void (0) : __assert_fail ("ATN && \"not an assumed template name\""
, "clang/lib/Sema/SemaTemplate.cpp", 3917, __extension__ __PRETTY_FUNCTION__
))
;
3918 II = ATN->getDeclName().getAsIdentifierInfo();
3919
3920 if (!resolveAssumedTemplateNameAsType(S, Name, NameLoc, /*Diagnose*/false)) {
3921 // Resolved to a type template name.
3922 ParsedName = TemplateTy::make(Name);
3923 TNK = TNK_Type_template;
3924 }
3925}
3926
3927bool Sema::resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
3928 SourceLocation NameLoc,
3929 bool Diagnose) {
3930 // We assumed this undeclared identifier to be an (ADL-only) function
3931 // template name, but it was used in a context where a type was required.
3932 // Try to typo-correct it now.
3933 AssumedTemplateStorage *ATN = Name.getAsAssumedTemplateName();
3934 assert(ATN && "not an assumed template name")(static_cast <bool> (ATN && "not an assumed template name"
) ? void (0) : __assert_fail ("ATN && \"not an assumed template name\""
, "clang/lib/Sema/SemaTemplate.cpp", 3934, __extension__ __PRETTY_FUNCTION__
))
;
3935
3936 LookupResult R(*this, ATN->getDeclName(), NameLoc, LookupOrdinaryName);
3937 struct CandidateCallback : CorrectionCandidateCallback {
3938 bool ValidateCandidate(const TypoCorrection &TC) override {
3939 return TC.getCorrectionDecl() &&
3940 getAsTypeTemplateDecl(TC.getCorrectionDecl());
3941 }
3942 std::unique_ptr<CorrectionCandidateCallback> clone() override {
3943 return std::make_unique<CandidateCallback>(*this);
3944 }
3945 } FilterCCC;
3946
3947 TypoCorrection Corrected =
3948 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
3949 FilterCCC, CTK_ErrorRecovery);
3950 if (Corrected && Corrected.getFoundDecl()) {
3951 diagnoseTypo(Corrected, PDiag(diag::err_no_template_suggest)
3952 << ATN->getDeclName());
3953 Name = TemplateName(Corrected.getCorrectionDeclAs<TemplateDecl>());
3954 return false;
3955 }
3956
3957 if (Diagnose)
3958 Diag(R.getNameLoc(), diag::err_no_template) << R.getLookupName();
3959 return true;
3960}
3961
3962TypeResult Sema::ActOnTemplateIdType(
3963 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
3964 TemplateTy TemplateD, IdentifierInfo *TemplateII,
3965 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
3966 ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc,
3967 bool IsCtorOrDtorName, bool IsClassName) {
3968 if (SS.isInvalid())
3969 return true;
3970
3971 if (!IsCtorOrDtorName && !IsClassName && SS.isSet()) {
3972 DeclContext *LookupCtx = computeDeclContext(SS, /*EnteringContext*/false);
3973
3974 // C++ [temp.res]p3:
3975 // A qualified-id that refers to a type and in which the
3976 // nested-name-specifier depends on a template-parameter (14.6.2)
3977 // shall be prefixed by the keyword typename to indicate that the
3978 // qualified-id denotes a type, forming an
3979 // elaborated-type-specifier (7.1.5.3).
3980 if (!LookupCtx && isDependentScopeSpecifier(SS)) {
3981 Diag(SS.getBeginLoc(), diag::err_typename_missing_template)
3982 << SS.getScopeRep() << TemplateII->getName();
3983 // Recover as if 'typename' were specified.
3984 // FIXME: This is not quite correct recovery as we don't transform SS
3985 // into the corresponding dependent form (and we don't diagnose missing
3986 // 'template' keywords within SS as a result).
3987 return ActOnTypenameType(nullptr, SourceLocation(), SS, TemplateKWLoc,
3988 TemplateD, TemplateII, TemplateIILoc, LAngleLoc,
3989 TemplateArgsIn, RAngleLoc);
3990 }
3991
3992 // Per C++ [class.qual]p2, if the template-id was an injected-class-name,
3993 // it's not actually allowed to be used as a type in most cases. Because
3994 // we annotate it before we know whether it's valid, we have to check for
3995 // this case here.
3996 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
3997 if (LookupRD && LookupRD->getIdentifier() == TemplateII) {
3998 Diag(TemplateIILoc,
3999 TemplateKWLoc.isInvalid()
4000 ? diag::err_out_of_line_qualified_id_type_names_constructor
4001 : diag::ext_out_of_line_qualified_id_type_names_constructor)
4002 << TemplateII << 0 /*injected-class-name used as template name*/
4003 << 1 /*if any keyword was present, it was 'template'*/;
4004 }
4005 }
4006
4007 TemplateName Template = TemplateD.get();
4008 if (Template.getAsAssumedTemplateName() &&
4009 resolveAssumedTemplateNameAsType(S, Template, TemplateIILoc))
4010 return true;
4011
4012 // Translate the parser's template argument list in our AST format.
4013 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4014 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4015
4016 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4017 QualType T
4018 = Context.getDependentTemplateSpecializationType(ETK_None,
4019 DTN->getQualifier(),
4020 DTN->getIdentifier(),
4021 TemplateArgs);
4022 // Build type-source information.
4023 TypeLocBuilder TLB;
4024 DependentTemplateSpecializationTypeLoc SpecTL
4025 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4026 SpecTL.setElaboratedKeywordLoc(SourceLocation());
4027 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4028 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4029 SpecTL.setTemplateNameLoc(TemplateIILoc);
4030 SpecTL.setLAngleLoc(LAngleLoc);
4031 SpecTL.setRAngleLoc(RAngleLoc);
4032 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4033 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4034 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4035 }
4036
4037 QualType SpecTy = CheckTemplateIdType(Template, TemplateIILoc, TemplateArgs);
4038 if (SpecTy.isNull())
4039 return true;
4040
4041 // Build type-source information.
4042 TypeLocBuilder TLB;
4043 TemplateSpecializationTypeLoc SpecTL =
4044 TLB.push<TemplateSpecializationTypeLoc>(SpecTy);
4045 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4046 SpecTL.setTemplateNameLoc(TemplateIILoc);
4047 SpecTL.setLAngleLoc(LAngleLoc);
4048 SpecTL.setRAngleLoc(RAngleLoc);
4049 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4050 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4051
4052 // Create an elaborated-type-specifier containing the nested-name-specifier.
4053 QualType ElTy = getElaboratedType(
4054 ETK_None, !IsCtorOrDtorName ? SS : CXXScopeSpec(), SpecTy);
4055 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(ElTy);
4056 ElabTL.setElaboratedKeywordLoc(SourceLocation());
4057 if (!ElabTL.isEmpty())
4058 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4059 return CreateParsedType(ElTy, TLB.getTypeSourceInfo(Context, ElTy));
4060}
4061
4062TypeResult Sema::ActOnTagTemplateIdType(TagUseKind TUK,
4063 TypeSpecifierType TagSpec,
4064 SourceLocation TagLoc,
4065 CXXScopeSpec &SS,
4066 SourceLocation TemplateKWLoc,
4067 TemplateTy TemplateD,
4068 SourceLocation TemplateLoc,
4069 SourceLocation LAngleLoc,
4070 ASTTemplateArgsPtr TemplateArgsIn,
4071 SourceLocation RAngleLoc) {
4072 if (SS.isInvalid())
4073 return TypeResult(true);
4074
4075 TemplateName Template = TemplateD.get();
4076
4077 // Translate the parser's template argument list in our AST format.
4078 TemplateArgumentListInfo TemplateArgs(LAngleLoc, RAngleLoc);
4079 translateTemplateArguments(TemplateArgsIn, TemplateArgs);
4080
4081 // Determine the tag kind
4082 TagTypeKind TagKind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
4083 ElaboratedTypeKeyword Keyword
4084 = TypeWithKeyword::getKeywordForTagTypeKind(TagKind);
4085
4086 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
4087 QualType T = Context.getDependentTemplateSpecializationType(Keyword,
4088 DTN->getQualifier(),
4089 DTN->getIdentifier(),
4090 TemplateArgs);
4091
4092 // Build type-source information.
4093 TypeLocBuilder TLB;
4094 DependentTemplateSpecializationTypeLoc SpecTL
4095 = TLB.push<DependentTemplateSpecializationTypeLoc>(T);
4096 SpecTL.setElaboratedKeywordLoc(TagLoc);
4097 SpecTL.setQualifierLoc(SS.getWithLocInContext(Context));
4098 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4099 SpecTL.setTemplateNameLoc(TemplateLoc);
4100 SpecTL.setLAngleLoc(LAngleLoc);
4101 SpecTL.setRAngleLoc(RAngleLoc);
4102 for (unsigned I = 0, N = SpecTL.getNumArgs(); I != N; ++I)
4103 SpecTL.setArgLocInfo(I, TemplateArgs[I].getLocInfo());
4104 return CreateParsedType(T, TLB.getTypeSourceInfo(Context, T));
4105 }
4106
4107 if (TypeAliasTemplateDecl *TAT =
4108 dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
4109 // C++0x [dcl.type.elab]p2:
4110 // If the identifier resolves to a typedef-name or the simple-template-id
4111 // resolves to an alias template specialization, the
4112 // elaborated-type-specifier is ill-formed.
4113 Diag(TemplateLoc, diag::err_tag_reference_non_tag)
4114 << TAT << NTK_TypeAliasTemplate << TagKind;
4115 Diag(TAT->getLocation(), diag::note_declared_at);
4116 }
4117
4118 QualType Result = CheckTemplateIdType(Template, TemplateLoc, TemplateArgs);
4119 if (Result.isNull())
4120 return TypeResult(true);
4121
4122 // Check the tag kind
4123 if (const RecordType *RT = Result->getAs<RecordType>()) {
4124 RecordDecl *D = RT->getDecl();
4125
4126 IdentifierInfo *Id = D->getIdentifier();
4127 assert(Id && "templated class must have an identifier")(static_cast <bool> (Id && "templated class must have an identifier"
) ? void (0) : __assert_fail ("Id && \"templated class must have an identifier\""
, "clang/lib/Sema/SemaTemplate.cpp", 4127, __extension__ __PRETTY_FUNCTION__
))
;
4128
4129 if (!isAcceptableTagRedeclaration(D, TagKind, TUK == TUK_Definition,
4130 TagLoc, Id)) {
4131 Diag(TagLoc, diag::err_use_with_wrong_tag)
4132 << Result
4133 << FixItHint::CreateReplacement(SourceRange(TagLoc), D->getKindName());
4134 Diag(D->getLocation(), diag::note_previous_use);
4135 }
4136 }
4137
4138 // Provide source-location information for the template specialization.
4139 TypeLocBuilder TLB;
4140 TemplateSpecializationTypeLoc SpecTL
4141 = TLB.push<TemplateSpecializationTypeLoc>(Result);
4142 SpecTL.setTemplateKeywordLoc(TemplateKWLoc);
4143 SpecTL.setTemplateNameLoc(TemplateLoc);
4144 SpecTL.setLAngleLoc(LAngleLoc);
4145 SpecTL.setRAngleLoc(RAngleLoc);
4146 for (unsigned i = 0, e = SpecTL.getNumArgs(); i != e; ++i)
4147 SpecTL.setArgLocInfo(i, TemplateArgs[i].getLocInfo());
4148
4149 // Construct an elaborated type containing the nested-name-specifier (if any)
4150 // and tag keyword.
4151 Result = Context.getElaboratedType(Keyword, SS.getScopeRep(), Result);
4152 ElaboratedTypeLoc ElabTL = TLB.push<ElaboratedTypeLoc>(Result);
4153 ElabTL.setElaboratedKeywordLoc(TagLoc);
4154 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
4155 return CreateParsedType(Result, TLB.getTypeSourceInfo(Context, Result));
4156}
4157
4158static bool CheckTemplateSpecializationScope(Sema &S, NamedDecl *Specialized,
4159 NamedDecl *PrevDecl,
4160 SourceLocation Loc,
4161 bool IsPartialSpecialization);
4162
4163static TemplateSpecializationKind getTemplateSpecializationKind(Decl *D);
4164
4165static bool isTemplateArgumentTemplateParameter(
4166 const TemplateArgument &Arg, unsigned Depth, unsigned Index) {
4167 switch (Arg.getKind()) {
4168 case TemplateArgument::Null:
4169 case TemplateArgument::NullPtr:
4170 case TemplateArgument::Integral:
4171 case TemplateArgument::Declaration:
4172 case TemplateArgument::Pack:
4173 case TemplateArgument::TemplateExpansion:
4174 return false;
4175
4176 case TemplateArgument::Type: {
4177 QualType Type = Arg.getAsType();
4178 const TemplateTypeParmType *TPT =
4179 Arg.getAsType()->getAs<TemplateTypeParmType>();
4180 return TPT && !Type.hasQualifiers() &&
4181 TPT->getDepth() == Depth && TPT->getIndex() == Index;
4182 }
4183
4184 case TemplateArgument::Expression: {
4185 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Arg.getAsExpr());
4186 if (!DRE || !DRE->getDecl())
4187 return false;
4188 const NonTypeTemplateParmDecl *NTTP =
4189 dyn_cast<NonTypeTemplateParmDecl>(DRE->getDecl());
4190 return NTTP && NTTP->getDepth() == Depth && NTTP->getIndex() == Index;
4191 }
4192
4193 case TemplateArgument::Template:
4194 const TemplateTemplateParmDecl *TTP =
4195 dyn_cast_or_null<TemplateTemplateParmDecl>(
4196 Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl());
4197 return TTP && TTP->getDepth() == Depth && TTP->getIndex() == Index;
4198 }
4199 llvm_unreachable("unexpected kind of template argument")::llvm::llvm_unreachable_internal("unexpected kind of template argument"
, "clang/lib/Sema/SemaTemplate.cpp", 4199)
;
4200}
4201
4202static bool isSameAsPrimaryTemplate(TemplateParameterList *Params,
4203 ArrayRef<TemplateArgument> Args) {
4204 if (Params->size() != Args.size())
4205 return false;
4206
4207 unsigned Depth = Params->getDepth();
4208
4209 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4210 TemplateArgument Arg = Args[I];
4211
4212 // If the parameter is a pack expansion, the argument must be a pack
4213 // whose only element is a pack expansion.
4214 if (Params->getParam(I)->isParameterPack()) {
4215 if (Arg.getKind() != TemplateArgument::Pack || Arg.pack_size() != 1 ||
4216 !Arg.pack_begin()->isPackExpansion())
4217 return false;
4218 Arg = Arg.pack_begin()->getPackExpansionPattern();
4219 }
4220
4221 if (!isTemplateArgumentTemplateParameter(Arg, Depth, I))
4222 return false;
4223 }
4224
4225 return true;
4226}
4227
4228template<typename PartialSpecDecl>
4229static void checkMoreSpecializedThanPrimary(Sema &S, PartialSpecDecl *Partial) {
4230 if (Partial->getDeclContext()->isDependentContext())
4231 return;
4232
4233 // FIXME: Get the TDK from deduction in order to provide better diagnostics
4234 // for non-substitution-failure issues?
4235 TemplateDeductionInfo Info(Partial->getLocation());
4236 if (S.isMoreSpecializedThanPrimary(Partial, Info))
4237 return;
4238
4239 auto *Template = Partial->getSpecializedTemplate();
4240 S.Diag(Partial->getLocation(),
4241 diag::ext_partial_spec_not_more_specialized_than_primary)
4242 << isa<VarTemplateDecl>(Template);
4243
4244 if (Info.hasSFINAEDiagnostic()) {
4245 PartialDiagnosticAt Diag = {SourceLocation(),
4246 PartialDiagnostic::NullDiagnostic()};
4247 Info.takeSFINAEDiagnostic(Diag);
4248 SmallString<128> SFINAEArgString;
4249 Diag.second.EmitToString(S.getDiagnostics(), SFINAEArgString);
4250 S.Diag(Diag.first,
4251 diag::note_partial_spec_not_more_specialized_than_primary)
4252 << SFINAEArgString;
4253 }
4254
4255 S.Diag(Template->getLocation(), diag::note_template_decl_here);
4256 SmallVector<const Expr *, 3> PartialAC, TemplateAC;
4257 Template->getAssociatedConstraints(TemplateAC);
4258 Partial->getAssociatedConstraints(PartialAC);
4259 S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(Partial, PartialAC, Template,
4260 TemplateAC);
4261}
4262
4263static void
4264noteNonDeducibleParameters(Sema &S, TemplateParameterList *TemplateParams,
4265 const llvm::SmallBitVector &DeducibleParams) {
4266 for (unsigned I = 0, N = DeducibleParams.size(); I != N; ++I) {
4267 if (!DeducibleParams[I]) {
4268 NamedDecl *Param = TemplateParams->getParam(I);
4269 if (Param->getDeclName())
4270 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4271 << Param->getDeclName();
4272 else
4273 S.Diag(Param->getLocation(), diag::note_non_deducible_parameter)
4274 << "(anonymous)";
4275 }
4276 }
4277}
4278
4279
4280template<typename PartialSpecDecl>
4281static void checkTemplatePartialSpecialization(Sema &S,
4282 PartialSpecDecl *Partial) {
4283 // C++1z [temp.class.spec]p8: (DR1495)
4284 // - The specialization shall be more specialized than the primary
4285 // template (14.5.5.2).
4286 checkMoreSpecializedThanPrimary(S, Partial);
4287
4288 // C++ [temp.class.spec]p8: (DR1315)
4289 // - Each template-parameter shall appear at least once in the
4290 // template-id outside a non-deduced context.
4291 // C++1z [temp.class.spec.match]p3 (P0127R2)
4292 // If the template arguments of a partial specialization cannot be
4293 // deduced because of the structure of its template-parameter-list
4294 // and the template-id, the program is ill-formed.
4295 auto *TemplateParams = Partial->getTemplateParameters();
4296 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4297 S.MarkUsedTemplateParameters(Partial->getTemplateArgs(), true,
4298 TemplateParams->getDepth(), DeducibleParams);
4299
4300 if (!DeducibleParams.all()) {
4301 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4302 S.Diag(Partial->getLocation(), diag::ext_partial_specs_not_deducible)
4303 << isa<VarTemplatePartialSpecializationDecl>(Partial)
4304 << (NumNonDeducible > 1)
4305 << SourceRange(Partial->getLocation(),
4306 Partial->getTemplateArgsAsWritten()->RAngleLoc);
4307 noteNonDeducibleParameters(S, TemplateParams, DeducibleParams);
4308 }
4309}
4310
4311void Sema::CheckTemplatePartialSpecialization(
4312 ClassTemplatePartialSpecializationDecl *Partial) {
4313 checkTemplatePartialSpecialization(*this, Partial);
4314}
4315
4316void Sema::CheckTemplatePartialSpecialization(
4317 VarTemplatePartialSpecializationDecl *Partial) {
4318 checkTemplatePartialSpecialization(*this, Partial);
4319}
4320
4321void Sema::CheckDeductionGuideTemplate(FunctionTemplateDecl *TD) {
4322 // C++1z [temp.param]p11:
4323 // A template parameter of a deduction guide template that does not have a
4324 // default-argument shall be deducible from the parameter-type-list of the
4325 // deduction guide template.
4326 auto *TemplateParams = TD->getTemplateParameters();
4327 llvm::SmallBitVector DeducibleParams(TemplateParams->size());
4328 MarkDeducedTemplateParameters(TD, DeducibleParams);
4329 for (unsigned I = 0; I != TemplateParams->size(); ++I) {
4330 // A parameter pack is deducible (to an empty pack).
4331 auto *Param = TemplateParams->getParam(I);
4332 if (Param->isParameterPack() || hasVisibleDefaultArgument(Param))
4333 DeducibleParams[I] = true;
4334 }
4335
4336 if (!DeducibleParams.all()) {
4337 unsigned NumNonDeducible = DeducibleParams.size() - DeducibleParams.count();
4338 Diag(TD->getLocation(), diag::err_deduction_guide_template_not_deducible)
4339 << (NumNonDeducible > 1);
4340 noteNonDeducibleParameters(*this, TemplateParams, DeducibleParams);
4341 }
4342}
4343
4344DeclResult Sema::ActOnVarTemplateSpecialization(
4345 Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc,
4346 TemplateParameterList *TemplateParams, StorageClass SC,
4347 bool IsPartialSpecialization) {
4348 // D must be variable template id.
4349 assert(D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId &&(static_cast <bool> (D.getName().getKind() == UnqualifiedIdKind
::IK_TemplateId && "Variable template specialization is declared with a template id."
) ? void (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template id.\""
, "clang/lib/Sema/SemaTemplate.cpp", 4350, __extension__ __PRETTY_FUNCTION__
))
4350 "Variable template specialization is declared with a template id.")(static_cast <bool> (D.getName().getKind() == UnqualifiedIdKind
::IK_TemplateId && "Variable template specialization is declared with a template id."
) ? void (0) : __assert_fail ("D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId && \"Variable template specialization is declared with a template id.\""
, "clang/lib/Sema/SemaTemplate.cpp", 4350, __extension__ __PRETTY_FUNCTION__
))
;
4351
4352 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
4353 TemplateArgumentListInfo TemplateArgs =
4354 makeTemplateArgumentListInfo(*this, *TemplateId);
4355 SourceLocation TemplateNameLoc = D.getIdentifierLoc();
4356 SourceLocation LAngleLoc = TemplateId->LAngleLoc;
4357 SourceLocation RAngleLoc = TemplateId->RAngleLoc;
4358
4359 TemplateName Name = TemplateId->Template.get();
4360
4361 // The template-id must name a variable template.
4362 VarTemplateDecl *VarTemplate =
4363 dyn_cast_or_null<VarTemplateDecl>(Name.getAsTemplateDecl());
4364 if (!VarTemplate) {
4365 NamedDecl *FnTemplate;
4366 if (auto *OTS = Name.getAsOverloadedTemplate())
4367 FnTemplate = *OTS->begin();
4368 else
4369 FnTemplate = dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4370 if (FnTemplate)
4371 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template_but_method)
4372 << FnTemplate->getDeclName();
4373 return Diag(D.getIdentifierLoc(), diag::err_var_spec_no_template)
4374 << IsPartialSpecialization;
4375 }
4376
4377 // Check for unexpanded parameter packs in any of the template arguments.
4378 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
4379 if (DiagnoseUnexpandedParameterPack(TemplateArgs[I],
4380 UPPC_PartialSpecialization))
4381 return true;
4382
4383 // Check that the template argument list is well-formed for this
4384 // template.
4385 SmallVector<TemplateArgument, 4> Converted;
4386 if (CheckTemplateArgumentList(VarTemplate, TemplateNameLoc, TemplateArgs,
4387 false, Converted,
4388 /*UpdateArgsWithConversions=*/true))
4389 return true;
4390
4391 // Find the variable template (partial) specialization declaration that
4392 // corresponds to these arguments.
4393 if (IsPartialSpecialization) {
4394 if (CheckTemplatePartialSpecializationArgs(TemplateNameLoc, VarTemplate,
4395 TemplateArgs.size(), Converted))
4396 return true;
4397
4398 // FIXME: Move these checks to CheckTemplatePartialSpecializationArgs so we
4399 // also do them during instantiation.
4400 if (!Name.isDependent() &&
4401 !TemplateSpecializationType::anyDependentTemplateArguments(TemplateArgs,
4402 Converted)) {
4403 Diag(TemplateNameLoc, diag::err_partial_spec_fully_specialized)
4404 << VarTemplate->getDeclName();
4405 IsPartialSpecialization = false;
4406 }
4407
4408 if (isSameAsPrimaryTemplate(VarTemplate->getTemplateParameters(),
4409 Converted) &&
4410 (!Context.getLangOpts().CPlusPlus20 ||
4411 !TemplateParams->hasAssociatedConstraints())) {
4412 // C++ [temp.class.spec]p9b3:
4413 //
4414 // -- The argument list of the specialization shall not be identical
4415 // to the implicit argument list of the primary template.
4416 Diag(TemplateNameLoc, diag::err_partial_spec_args_match_primary_template)
4417 << /*variable template*/ 1
4418 << /*is definition*/(SC != SC_Extern && !CurContext->isRecord())
4419 << FixItHint::CreateRemoval(SourceRange(LAngleLoc, RAngleLoc));
4420 // FIXME: Recover from this by treating the declaration as a redeclaration
4421 // of the primary template.
4422 return true;
4423 }
4424 }
4425
4426 void *InsertPos = nullptr;
4427 VarTemplateSpecializationDecl *PrevDecl = nullptr;
4428
4429 if (IsPartialSpecialization)
4430 PrevDecl = VarTemplate->findPartialSpecialization(Converted, TemplateParams,
4431 InsertPos);
4432 else
4433 PrevDecl = VarTemplate->findSpecialization(Converted, InsertPos);
4434
4435 VarTemplateSpecializationDecl *Specialization = nullptr;
4436
4437 // Check whether we can declare a variable template specialization in
4438 // the current scope.
4439 if (CheckTemplateSpecializationScope(*this, VarTemplate, PrevDecl,
4440 TemplateNameLoc,
4441 IsPartialSpecialization))
4442 return true;
4443
4444 if (PrevDecl && PrevDecl->getSpecializationKind() == TSK_Undeclared) {
4445 // Since the only prior variable template specialization with these
4446 // arguments was referenced but not declared, reuse that
4447 // declaration node as our own, updating its source location and
4448 // the list of outer template parameters to reflect our new declaration.
4449 Specialization = PrevDecl;
4450 Specialization->setLocation(TemplateNameLoc);
4451 PrevDecl = nullptr;
4452 } else if (IsPartialSpecialization) {
4453 // Create a new class template partial specialization declaration node.
4454 VarTemplatePartialSpecializationDecl *PrevPartial =
4455 cast_or_null<VarTemplatePartialSpecializationDecl>(PrevDecl);
4456 VarTemplatePartialSpecializationDecl *Partial =
4457 VarTemplatePartialSpecializationDecl::Create(
4458 Context, VarTemplate->getDeclContext(), TemplateKWLoc,
4459 TemplateNameLoc, TemplateParams, VarTemplate, DI->getType(), DI, SC,
4460 Converted, TemplateArgs);
4461
4462 if (!PrevPartial)
4463 VarTemplate->AddPartialSpecialization(Partial, InsertPos);
4464 Specialization = Partial;
4465
4466 // If we are providing an explicit specialization of a member variable
4467 // template specialization, make a note of that.
4468 if (PrevPartial && PrevPartial->getInstantiatedFromMember())
4469 PrevPartial->setMemberSpecialization();
4470
4471 CheckTemplatePartialSpecialization(Partial);
4472 } else {
4473 // Create a new class template specialization declaration node for
4474 // this explicit specialization or friend declaration.
4475 Specialization = VarTemplateSpecializationDecl::Create(
4476 Context, VarTemplate->getDeclContext(), TemplateKWLoc, TemplateNameLoc,
4477 VarTemplate, DI->getType(), DI, SC, Converted);
4478 Specialization->setTemplateArgsInfo(TemplateArgs);
4479
4480 if (!PrevDecl)
4481 VarTemplate->AddSpecialization(Specialization, InsertPos);
4482 }
4483
4484 // C++ [temp.expl.spec]p6:
4485 // If a template, a member template or the member of a class template is
4486 // explicitly specialized then that specialization shall be declared
4487 // before the first use of that specialization that would cause an implicit
4488 // instantiation to take place, in every translation unit in which such a
4489 // use occurs; no diagnostic is required.
4490 if (PrevDecl && PrevDecl->getPointOfInstantiation().isValid()) {
4491 bool Okay = false;
4492 for (Decl *Prev = PrevDecl; Prev; Prev = Prev->getPreviousDecl()) {
4493 // Is there any previous explicit specialization declaration?
4494 if (getTemplateSpecializationKind(Prev) == TSK_ExplicitSpecialization) {
4495 Okay = true;
4496 break;
4497 }
4498 }
4499
4500 if (!Okay) {
4501 SourceRange Range(TemplateNameLoc, RAngleLoc);
4502 Diag(TemplateNameLoc, diag::err_specialization_after_instantiation)
4503 << Name << Range;
4504
4505 Diag(PrevDecl->getPointOfInstantiation(),
4506 diag::note_instantiation_required_here)
4507 << (PrevDecl->getTemplateSpecializationKind() !=
4508 TSK_ImplicitInstantiation);
4509 return true;
4510 }
4511 }
4512
4513 Specialization->setTemplateKeywordLoc(TemplateKWLoc);
4514 Specialization->setLexicalDeclContext(CurContext);
4515
4516 // Add the specialization into its lexical context, so that it can
4517 // be seen when iterating through the list of declarations in that
4518 // context. However, specializations are not found by name lookup.
4519 CurContext->addDecl(Specialization);
4520
4521 // Note that this is an explicit specialization.
4522 Specialization->setSpecializationKind(TSK_ExplicitSpecialization);
4523
4524 if (PrevDecl) {
4525 // Check that this isn't a redefinition of this specialization,
4526 // merging with previous declarations.
4527 LookupResult PrevSpec(*this, GetNameForDeclarator(D), LookupOrdinaryName,
4528 forRedeclarationInCurContext());
4529 PrevSpec.addDecl(PrevDecl);
4530 D.setRedeclaration(CheckVariableDeclaration(Specialization, PrevSpec));
4531 } else if (Specialization->isStaticDataMember() &&
4532 Specialization->isOutOfLine()) {
4533 Specialization->setAccess(VarTemplate->getAccess());
4534 }
4535
4536 return Specialization;
4537}
4538
4539namespace {
4540/// A partial specialization whose template arguments have matched
4541/// a given template-id.
4542struct PartialSpecMatchResult {
4543 VarTemplatePartialSpecializationDecl *Partial;
4544 TemplateArgumentList *Args;
4545};
4546} // end anonymous namespace
4547
4548DeclResult
4549Sema::CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc,
4550 SourceLocation TemplateNameLoc,
4551 const TemplateArgumentListInfo &TemplateArgs) {
4552 assert(Template && "A variable template id without template?")(static_cast <bool> (Template && "A variable template id without template?"
) ? void (0) : __assert_fail ("Template && \"A variable template id without template?\""
, "clang/lib/Sema/SemaTemplate.cpp", 4552, __extension__ __PRETTY_FUNCTION__
))
;
4553
4554 // Check that the template argument list is well-formed for this template.
4555 SmallVector<TemplateArgument, 4> Converted;
4556 if (CheckTemplateArgumentList(
4557 Template, TemplateNameLoc,
4558 const_cast<TemplateArgumentListInfo &>(TemplateArgs), false,
4559 Converted, /*UpdateArgsWithConversions=*/true))
4560 return true;
4561
4562 // Produce a placeholder value if the specialization is dependent.
4563 if (Template->getDeclContext()->isDependentContext() ||
4564 TemplateSpecializationType::anyDependentTemplateArguments(TemplateArgs,
4565 Converted))
4566 return DeclResult();
4567
4568 // Find the variable template specialization declaration that
4569 // corresponds to these arguments.
4570 void *InsertPos = nullptr;
4571 if (VarTemplateSpecializationDecl *Spec = Template->findSpecialization(
4572 Converted, InsertPos)) {
4573 checkSpecializationReachability(TemplateNameLoc, Spec);
4574 // If we already have a variable template specialization, return it.
4575 return Spec;
4576 }
4577
4578 // This is the first time we have referenced this variable template
4579 // specialization. Create the canonical declaration and add it to
4580 // the set of specializations, based on the closest partial specialization
4581 // that it represents. That is,
4582 VarDecl *InstantiationPattern = Template->getTemplatedDecl();
4583 TemplateArgumentList TemplateArgList(TemplateArgumentList::OnStack,
4584 Converted);
4585 TemplateArgumentList *InstantiationArgs = &TemplateArgList;
4586 bool AmbiguousPartialSpec = false;
4587 typedef PartialSpecMatchResult MatchResult;
4588 SmallVector<MatchResult, 4> Matched;
4589 SourceLocation PointOfInstantiation = TemplateNameLoc;
4590 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation,
4591 /*ForTakingAddress=*/false);
4592
4593 // 1. Attempt to find the closest partial specialization that this
4594 // specializes, if any.
4595 // TODO: Unify with InstantiateClassTemplateSpecialization()?
4596 // Perhaps better after unification of DeduceTemplateArguments() and
4597 // getMoreSpecializedPartialSpecialization().
4598 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
4599 Template->getPartialSpecializations(PartialSpecs);
4600
4601 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
4602 VarTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
4603 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4604
4605 if (TemplateDeductionResult Result =
4606 DeduceTemplateArguments(Partial, TemplateArgList, Info)) {
4607 // Store the failed-deduction information for use in diagnostics, later.
4608 // TODO: Actually use the failed-deduction info?
4609 FailedCandidates.addCandidate().set(
4610 DeclAccessPair::make(Template, AS_public), Partial,
4611 MakeDeductionFailureInfo(Context, Result, Info));
4612 (void)Result;
4613 } else {
4614 Matched.push_back(PartialSpecMatchResult());
4615 Matched.back().Partial = Partial;
4616 Matched.back().Args = Info.take();
4617 }
4618 }
4619
4620 if (Matched.size() >= 1) {
4621 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
4622 if (Matched.size() == 1) {
4623 // -- If exactly one matching specialization is found, the
4624 // instantiation is generated from that specialization.
4625 // We don't need to do anything for this.
4626 } else {
4627 // -- If more than one matching specialization is found, the
4628 // partial order rules (14.5.4.2) are used to determine
4629 // whether one of the specializations is more specialized
4630 // than the others. If none of the specializations is more
4631 // specialized than all of the other matching
4632 // specializations, then the use of the variable template is
4633 // ambiguous and the program is ill-formed.
4634 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
4635 PEnd = Matched.end();
4636 P != PEnd; ++P) {
4637 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
4638 PointOfInstantiation) ==
4639 P->Partial)
4640 Best = P;
4641 }
4642
4643 // Determine if the best partial specialization is more specialized than
4644 // the others.
4645 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
4646 PEnd = Matched.end();
4647 P != PEnd; ++P) {
4648 if (P != Best && getMoreSpecializedPartialSpecialization(
4649 P->Partial, Best->Partial,
4650 PointOfInstantiation) != Best->Partial) {
4651 AmbiguousPartialSpec = true;
4652 break;
4653 }
4654 }
4655 }
4656
4657 // Instantiate using the best variable template partial specialization.
4658 InstantiationPattern = Best->Partial;
4659 InstantiationArgs = Best->Args;
4660 } else {
4661 // -- If no match is found, the instantiation is generated
4662 // from the primary template.
4663 // InstantiationPattern = Template->getTemplatedDecl();
4664 }
4665
4666 // 2. Create the canonical declaration.
4667 // Note that we do not instantiate a definition until we see an odr-use
4668 // in DoMarkVarDeclReferenced().
4669 // FIXME: LateAttrs et al.?
4670 VarTemplateSpecializationDecl *Decl = BuildVarTemplateInstantiation(
4671 Template, InstantiationPattern, *InstantiationArgs, TemplateArgs,
4672 Converted, TemplateNameLoc /*, LateAttrs, StartingScope*/);
4673 if (!Decl)
4674 return true;
4675
4676 if (AmbiguousPartialSpec) {
4677 // Partial ordering did not produce a clear winner. Complain.
4678 Decl->setInvalidDecl();
4679 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
4680 << Decl;
4681
4682 // Print the matching partial specializations.
4683 for (MatchResult P : Matched)
4684 Diag(P.Partial->getLocation(), diag::note_partial_spec_match)
4685 << getTemplateArgumentBindingsText(P.Partial->getTemplateParameters(),
4686 *P.Args);
4687 return true;
4688 }
4689
4690 if (VarTemplatePartialSpecializationDecl *D =
4691 dyn_cast<VarTemplatePartialSpecializationDecl>(InstantiationPattern))
4692 Decl->setInstantiationOf(D, InstantiationArgs);
4693
4694 checkSpecializationReachability(TemplateNameLoc, Decl);
4695
4696 assert(Decl && "No variable template specialization?")(static_cast <bool> (Decl && "No variable template specialization?"
) ? void (0) : __assert_fail ("Decl && \"No variable template specialization?\""
, "clang/lib/Sema/SemaTemplate.cpp", 4696, __extension__ __PRETTY_FUNCTION__
))
;
4697 return Decl;
4698}
4699
4700ExprResult
4701Sema::CheckVarTemplateId(const CXXScopeSpec &SS,
4702 const DeclarationNameInfo &NameInfo,
4703 VarTemplateDecl *Template, SourceLocation TemplateLoc,
4704 const TemplateArgumentListInfo *TemplateArgs) {
4705
4706 DeclResult Decl = CheckVarTemplateId(Template, TemplateLoc, NameInfo.getLoc(),
4707 *TemplateArgs);
4708 if (Decl.isInvalid())
4709 return ExprError();
4710
4711 if (!Decl.get())
4712 return ExprResult();
4713
4714 VarDecl *Var = cast<VarDecl>(Decl.get());
4715 if (!Var->getTemplateSpecializationKind())
4716 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
4717 NameInfo.getLoc());
4718
4719 // Build an ordinary singleton decl ref.
4720 return BuildDeclarationNameExpr(SS, NameInfo, Var,
4721 /*FoundD=*/nullptr, TemplateArgs);
4722}
4723
4724void Sema::diagnoseMissingTemplateArguments(TemplateName Name,
4725 SourceLocation Loc) {
4726 Diag(Loc, diag::err_template_missing_args)
4727 << (int)getTemplateNameKindForDiagnostics(Name) << Name;
4728 if (TemplateDecl *TD = Name.getAsTemplateDecl()) {
4729 Diag(TD->getLocation(), diag::note_template_decl_here)
4730 << TD->getTemplateParameters()->getSourceRange();
4731 }
4732}
4733
4734ExprResult
4735Sema::CheckConceptTemplateId(const CXXScopeSpec &SS,
4736 SourceLocation TemplateKWLoc,
4737 const DeclarationNameInfo &ConceptNameInfo,
4738 NamedDecl *FoundDecl,
4739 ConceptDecl *NamedConcept,
4740 const TemplateArgumentListInfo *TemplateArgs) {
4741 assert(NamedConcept && "A concept template id without a template?")(static_cast <bool> (NamedConcept && "A concept template id without a template?"
) ? void (0) : __assert_fail ("NamedConcept && \"A concept template id without a template?\""
, "clang/lib/Sema/SemaTemplate.cpp", 4741, __extension__ __PRETTY_FUNCTION__
))
;
4742
4743 llvm::SmallVector<TemplateArgument, 4> Converted;
4744 if (CheckTemplateArgumentList(NamedConcept, ConceptNameInfo.getLoc(),
4745 const_cast<TemplateArgumentListInfo&>(*TemplateArgs),
4746 /*PartialTemplateArgs=*/false, Converted,
4747 /*UpdateArgsWithConversions=*/false))
4748 return ExprError();
4749
4750 ConstraintSatisfaction Satisfaction;
4751 bool AreArgsDependent =
4752 TemplateSpecializationType::anyDependentTemplateArguments(*TemplateArgs,
4753 Converted);
4754 MultiLevelTemplateArgumentList MLTAL;
4755 MLTAL.addOuterTemplateArguments(Converted);
4756 LocalInstantiationScope Scope(*this);
4757 if (!AreArgsDependent &&
4758 CheckConstraintSatisfaction(
4759 NamedConcept, {NamedConcept->getConstraintExpr()}, MLTAL,
4760 SourceRange(SS.isSet() ? SS.getBeginLoc() : ConceptNameInfo.getLoc(),
4761 TemplateArgs->getRAngleLoc()),
4762 Satisfaction))
4763 return ExprError();
4764
4765 return ConceptSpecializationExpr::Create(Context,
4766 SS.isSet() ? SS.getWithLocInContext(Context) : NestedNameSpecifierLoc{},
4767 TemplateKWLoc, ConceptNameInfo, FoundDecl, NamedConcept,
4768 ASTTemplateArgumentListInfo::Create(Context, *TemplateArgs), Converted,
4769 AreArgsDependent ? nullptr : &Satisfaction);
4770}
4771
4772ExprResult Sema::BuildTemplateIdExpr(const CXXScopeSpec &SS,
4773 SourceLocation TemplateKWLoc,
4774 LookupResult &R,
4775 bool RequiresADL,
4776 const TemplateArgumentListInfo *TemplateArgs) {
4777 // FIXME: Can we do any checking at this point? I guess we could check the
4778 // template arguments that we have against the template name, if the template
4779 // name refers to a single template. That's not a terribly common case,
4780 // though.
4781 // foo<int> could identify a single function unambiguously
4782 // This approach does NOT work, since f<int>(1);
4783 // gets resolved prior to resorting to overload resolution
4784 // i.e., template<class T> void f(double);
4785 // vs template<class T, class U> void f(U);
4786
4787 // These should be filtered out by our callers.
4788 assert(!R.isAmbiguous() && "ambiguous lookup when building templateid")(static_cast <bool> (!R.isAmbiguous() && "ambiguous lookup when building templateid"
) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"ambiguous lookup when building templateid\""
, "clang/lib/Sema/SemaTemplate.cpp", 4788, __extension__ __PRETTY_FUNCTION__
))
;
4789
4790 // Non-function templates require a template argument list.
4791 if (auto *TD = R.getAsSingle<TemplateDecl>()) {
4792 if (!TemplateArgs && !isa<FunctionTemplateDecl>(TD)) {
4793 diagnoseMissingTemplateArguments(TemplateName(TD), R.getNameLoc());
4794 return ExprError();
4795 }
4796 }
4797
4798 // In C++1y, check variable template ids.
4799 if (R.getAsSingle<VarTemplateDecl>()) {
4800 ExprResult Res = CheckVarTemplateId(SS, R.getLookupNameInfo(),
4801 R.getAsSingle<VarTemplateDecl>(),
4802 TemplateKWLoc, TemplateArgs);
4803 if (Res.isInvalid() || Res.isUsable())
4804 return Res;
4805 // Result is dependent. Carry on to build an UnresolvedLookupEpxr.
4806 }
4807
4808 if (R.getAsSingle<ConceptDecl>()) {
4809 return CheckConceptTemplateId(SS, TemplateKWLoc, R.getLookupNameInfo(),
4810 R.getFoundDecl(),
4811 R.getAsSingle<ConceptDecl>(), TemplateArgs);
4812 }
4813
4814 // We don't want lookup warnings at this point.
4815 R.suppressDiagnostics();
4816
4817 UnresolvedLookupExpr *ULE
4818 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
4819 SS.getWithLocInContext(Context),
4820 TemplateKWLoc,
4821 R.getLookupNameInfo(),
4822 RequiresADL, TemplateArgs,
4823 R.begin(), R.end());
4824
4825 return ULE;
4826}
4827
4828// We actually only call this from template instantiation.
4829ExprResult
4830Sema::BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
4831 SourceLocation TemplateKWLoc,
4832 const DeclarationNameInfo &NameInfo,
4833 const TemplateArgumentListInfo *TemplateArgs) {
4834
4835 assert(TemplateArgs || TemplateKWLoc.isValid())(static_cast <bool> (TemplateArgs || TemplateKWLoc.isValid
()) ? void (0) : __assert_fail ("TemplateArgs || TemplateKWLoc.isValid()"
, "clang/lib/Sema/SemaTemplate.cpp", 4835, __extension__ __PRETTY_FUNCTION__
))
;
4836 DeclContext *DC;
4837 if (!(DC = computeDeclContext(SS, false)) ||
4838 DC->isDependentContext() ||
4839 RequireCompleteDeclContext(SS, DC))
4840 return BuildDependentDeclRefExpr(SS, TemplateKWLoc, NameInfo, TemplateArgs);
4841
4842 bool MemberOfUnknownSpecialization;
4843 LookupResult R(*this, NameInfo, LookupOrdinaryName);
4844 if (LookupTemplateName(R, (Scope *)nullptr, SS, QualType(),
4845 /*Entering*/false, MemberOfUnknownSpecialization,
4846 TemplateKWLoc))
4847 return ExprError();
4848
4849 if (R.isAmbiguous())
4850 return ExprError();
4851
4852 if (R.empty()) {
4853 Diag(NameInfo.getLoc(), diag::err_no_member)
4854 << NameInfo.getName() << DC << SS.getRange();
4855 return ExprError();
4856 }
4857
4858 if (ClassTemplateDecl *Temp = R.getAsSingle<ClassTemplateDecl>()) {
4859 Diag(NameInfo.getLoc(), diag::err_template_kw_refers_to_class_template)
4860 << SS.getScopeRep()
4861 << NameInfo.getName().getAsString() << SS.getRange();
4862 Diag(Temp->getLocation(), diag::note_referenced_class_template);
4863 return ExprError();
4864 }
4865
4866 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/ false, TemplateArgs);
4867}
4868
4869/// Form a template name from a name that is syntactically required to name a
4870/// template, either due to use of the 'template' keyword or because a name in
4871/// this syntactic context is assumed to name a template (C++ [temp.names]p2-4).
4872///
4873/// This action forms a template name given the name of the template and its
4874/// optional scope specifier. This is used when the 'template' keyword is used
4875/// or when the parsing context unambiguously treats a following '<' as
4876/// introducing a template argument list. Note that this may produce a
4877/// non-dependent template name if we can perform the lookup now and identify
4878/// the named template.
4879///
4880/// For example, given "x.MetaFun::template apply", the scope specifier
4881/// \p SS will be "MetaFun::", \p TemplateKWLoc contains the location
4882/// of the "template" keyword, and "apply" is the \p Name.
4883TemplateNameKind Sema::ActOnTemplateName(Scope *S,
4884 CXXScopeSpec &SS,
4885 SourceLocation TemplateKWLoc,
4886 const UnqualifiedId &Name,
4887 ParsedType ObjectType,
4888 bool EnteringContext,
4889 TemplateTy &Result,
4890 bool AllowInjectedClassName) {
4891 if (TemplateKWLoc.isValid() && S && !S->getTemplateParamParent())
4892 Diag(TemplateKWLoc,
4893 getLangOpts().CPlusPlus11 ?
4894 diag::warn_cxx98_compat_template_outside_of_template :
4895 diag::ext_template_outside_of_template)
4896 << FixItHint::CreateRemoval(TemplateKWLoc);
4897
4898 if (SS.isInvalid())
4899 return TNK_Non_template;
4900
4901 // Figure out where isTemplateName is going to look.
4902 DeclContext *LookupCtx = nullptr;
4903 if (SS.isNotEmpty())
4904 LookupCtx = computeDeclContext(SS, EnteringContext);
4905 else if (ObjectType)
4906 LookupCtx = computeDeclContext(GetTypeFromParser(ObjectType));
4907
4908 // C++0x [temp.names]p5:
4909 // If a name prefixed by the keyword template is not the name of
4910 // a template, the program is ill-formed. [Note: the keyword
4911 // template may not be applied to non-template members of class
4912 // templates. -end note ] [ Note: as is the case with the
4913 // typename prefix, the template prefix is allowed in cases
4914 // where it is not strictly necessary; i.e., when the
4915 // nested-name-specifier or the expression on the left of the ->
4916 // or . is not dependent on a template-parameter, or the use
4917 // does not appear in the scope of a template. -end note]
4918 //
4919 // Note: C++03 was more strict here, because it banned the use of
4920 // the "template" keyword prior to a template-name that was not a
4921 // dependent name. C++ DR468 relaxed this requirement (the
4922 // "template" keyword is now permitted). We follow the C++0x
4923 // rules, even in C++03 mode with a warning, retroactively applying the DR.
4924 bool MemberOfUnknownSpecialization;
4925 TemplateNameKind TNK = isTemplateName(S, SS, TemplateKWLoc.isValid(), Name,
4926 ObjectType, EnteringContext, Result,
4927 MemberOfUnknownSpecialization);
4928 if (TNK != TNK_Non_template) {
4929 // We resolved this to a (non-dependent) template name. Return it.
4930 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
4931 if (!AllowInjectedClassName && SS.isNotEmpty() && LookupRD &&
4932 Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
4933 Name.Identifier && LookupRD->getIdentifier() == Name.Identifier) {
4934 // C++14 [class.qual]p2:
4935 // In a lookup in which function names are not ignored and the
4936 // nested-name-specifier nominates a class C, if the name specified
4937 // [...] is the injected-class-name of C, [...] the name is instead
4938 // considered to name the constructor
4939 //
4940 // We don't get here if naming the constructor would be valid, so we
4941 // just reject immediately and recover by treating the
4942 // injected-class-name as naming the template.
4943 Diag(Name.getBeginLoc(),
4944 diag::ext_out_of_line_qualified_id_type_names_constructor)
4945 << Name.Identifier
4946 << 0 /*injected-class-name used as template name*/
4947 << TemplateKWLoc.isValid();
4948 }
4949 return TNK;
4950 }
4951
4952 if (!MemberOfUnknownSpecialization) {
4953 // Didn't find a template name, and the lookup wasn't dependent.
4954 // Do the lookup again to determine if this is a "nothing found" case or
4955 // a "not a template" case. FIXME: Refactor isTemplateName so we don't
4956 // need to do this.
4957 DeclarationNameInfo DNI = GetNameFromUnqualifiedId(Name);
4958 LookupResult R(*this, DNI.getName(), Name.getBeginLoc(),
4959 LookupOrdinaryName);
4960 bool MOUS;
4961 // Tell LookupTemplateName that we require a template so that it diagnoses
4962 // cases where it finds a non-template.
4963 RequiredTemplateKind RTK = TemplateKWLoc.isValid()
4964 ? RequiredTemplateKind(TemplateKWLoc)
4965 : TemplateNameIsRequired;
4966 if (!LookupTemplateName(R, S, SS, ObjectType.get(), EnteringContext, MOUS,
4967 RTK, nullptr, /*AllowTypoCorrection=*/false) &&
4968 !R.isAmbiguous()) {
4969 if (LookupCtx)
4970 Diag(Name.getBeginLoc(), diag::err_no_member)
4971 << DNI.getName() << LookupCtx << SS.getRange();
4972 else
4973 Diag(Name.getBeginLoc(), diag::err_undeclared_use)
4974 << DNI.getName() << SS.getRange();
4975 }
4976 return TNK_Non_template;
4977 }
4978
4979 NestedNameSpecifier *Qualifier = SS.getScopeRep();
4980
4981 switch (Name.getKind()) {
4982 case UnqualifiedIdKind::IK_Identifier:
4983 Result = TemplateTy::make(
4984 Context.getDependentTemplateName(Qualifier, Name.Identifier));
4985 return TNK_Dependent_template_name;
4986
4987 case UnqualifiedIdKind::IK_OperatorFunctionId:
4988 Result = TemplateTy::make(Context.getDependentTemplateName(
4989 Qualifier, Name.OperatorFunctionId.Operator));
4990 return TNK_Function_template;
4991
4992 case UnqualifiedIdKind::IK_LiteralOperatorId:
4993 // This is a kind of template name, but can never occur in a dependent
4994 // scope (literal operators can only be declared at namespace scope).
4995 break;
4996
4997 default:
4998 break;
4999 }
5000
5001 // This name cannot possibly name a dependent template. Diagnose this now
5002 // rather than building a dependent template name that can never be valid.
5003 Diag(Name.getBeginLoc(),
5004 diag::err_template_kw_refers_to_dependent_non_template)
5005 << GetNameFromUnqualifiedId(Name).getName() << Name.getSourceRange()
5006 << TemplateKWLoc.isValid() << TemplateKWLoc;
5007 return TNK_Non_template;
5008}
5009
5010bool Sema::CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
5011 TemplateArgumentLoc &AL,
5012 SmallVectorImpl<TemplateArgument> &Converted) {
5013 const TemplateArgument &Arg = AL.getArgument();
5014 QualType ArgType;
5015 TypeSourceInfo *TSI = nullptr;
5016
5017 // Check template type parameter.
5018 switch(Arg.getKind()) {
5019 case TemplateArgument::Type:
5020 // C++ [temp.arg.type]p1:
5021 // A template-argument for a template-parameter which is a
5022 // type shall be a type-id.
5023 ArgType = Arg.getAsType();
5024 TSI = AL.getTypeSourceInfo();
5025 break;
5026 case TemplateArgument::Template:
5027 case TemplateArgument::TemplateExpansion: {
5028 // We have a template type parameter but the template argument
5029 // is a template without any arguments.
5030 SourceRange SR = AL.getSourceRange();
5031 TemplateName Name = Arg.getAsTemplateOrTemplatePattern();
5032 diagnoseMissingTemplateArguments(Name, SR.getEnd());
5033 return true;
5034 }
5035 case TemplateArgument::Expression: {
5036 // We have a template type parameter but the template argument is an
5037 // expression; see if maybe it is missing the "typename" keyword.
5038 CXXScopeSpec SS;
5039 DeclarationNameInfo NameInfo;
5040
5041 if (DependentScopeDeclRefExpr *ArgExpr =
5042 dyn_cast<DependentScopeDeclRefExpr>(Arg.getAsExpr())) {
5043 SS.Adopt(ArgExpr->getQualifierLoc());
5044 NameInfo = ArgExpr->getNameInfo();
5045 } else if (CXXDependentScopeMemberExpr *ArgExpr =
5046 dyn_cast<CXXDependentScopeMemberExpr>(Arg.getAsExpr())) {
5047 if (ArgExpr->isImplicitAccess()) {
5048 SS.Adopt(ArgExpr->getQualifierLoc());
5049 NameInfo = ArgExpr->getMemberNameInfo();
5050 }
5051 }
5052
5053 if (auto *II = NameInfo.getName().getAsIdentifierInfo()) {
5054 LookupResult Result(*this, NameInfo, LookupOrdinaryName);
5055 LookupParsedName(Result, CurScope, &SS);
5056
5057 if (Result.getAsSingle<TypeDecl>() ||
5058 Result.getResultKind() ==
5059 LookupResult::NotFoundInCurrentInstantiation) {
5060 assert(SS.getScopeRep() && "dependent scope expr must has a scope!")(static_cast <bool> (SS.getScopeRep() && "dependent scope expr must has a scope!"
) ? void (0) : __assert_fail ("SS.getScopeRep() && \"dependent scope expr must has a scope!\""
, "clang/lib/Sema/SemaTemplate.cpp", 5060, __extension__ __PRETTY_FUNCTION__
))
;
5061 // Suggest that the user add 'typename' before the NNS.
5062 SourceLocation Loc = AL.getSourceRange().getBegin();
5063 Diag(Loc, getLangOpts().MSVCCompat
5064 ? diag::ext_ms_template_type_arg_missing_typename
5065 : diag::err_template_arg_must_be_type_suggest)
5066 << FixItHint::CreateInsertion(Loc, "typename ");
5067 Diag(Param->getLocation(), diag::note_template_param_here);
5068
5069 // Recover by synthesizing a type using the location information that we
5070 // already have.
5071 ArgType =
5072 Context.getDependentNameType(ETK_Typename, SS.getScopeRep(), II);
5073 TypeLocBuilder TLB;
5074 DependentNameTypeLoc TL = TLB.push<DependentNameTypeLoc>(ArgType);
5075 TL.setElaboratedKeywordLoc(SourceLocation(/*synthesized*/));
5076 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5077 TL.setNameLoc(NameInfo.getLoc());
5078 TSI = TLB.getTypeSourceInfo(Context, ArgType);
5079
5080 // Overwrite our input TemplateArgumentLoc so that we can recover
5081 // properly.
5082 AL = TemplateArgumentLoc(TemplateArgument(ArgType),
5083 TemplateArgumentLocInfo(TSI));
5084
5085 break;
5086 }
5087 }
5088 // fallthrough
5089 [[fallthrough]];
5090 }
5091 default: {
5092 // We have a template type parameter but the template argument
5093 // is not a type.
5094 SourceRange SR = AL.getSourceRange();
5095 Diag(SR.getBegin(), diag::err_template_arg_must_be_type) << SR;
5096 Diag(Param->getLocation(), diag::note_template_param_here);
5097
5098 return true;
5099 }
5100 }
5101
5102 if (CheckTemplateArgument(TSI))
5103 return true;
5104
5105 // Add the converted template type argument.
5106 ArgType = Context.getCanonicalType(ArgType);
5107
5108 // Objective-C ARC:
5109 // If an explicitly-specified template argument type is a lifetime type
5110 // with no lifetime qualifier, the __strong lifetime qualifier is inferred.
5111 if (getLangOpts().ObjCAutoRefCount &&
5112 ArgType->isObjCLifetimeType() &&
5113 !ArgType.getObjCLifetime()) {
5114 Qualifiers Qs;
5115 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
5116 ArgType = Context.getQualifiedType(ArgType, Qs);
5117 }
5118
5119 Converted.push_back(TemplateArgument(ArgType));
5120 return false;
5121}
5122
5123/// Substitute template arguments into the default template argument for
5124/// the given template type parameter.
5125///
5126/// \param SemaRef the semantic analysis object for which we are performing
5127/// the substitution.
5128///
5129/// \param Template the template that we are synthesizing template arguments
5130/// for.
5131///
5132/// \param TemplateLoc the location of the template name that started the
5133/// template-id we are checking.
5134///
5135/// \param RAngleLoc the location of the right angle bracket ('>') that
5136/// terminates the template-id.
5137///
5138/// \param Param the template template parameter whose default we are
5139/// substituting into.
5140///
5141/// \param Converted the list of template arguments provided for template
5142/// parameters that precede \p Param in the template parameter list.
5143/// \returns the substituted template argument, or NULL if an error occurred.
5144static TypeSourceInfo *
5145SubstDefaultTemplateArgument(Sema &SemaRef,
5146 TemplateDecl *Template,
5147 SourceLocation TemplateLoc,
5148 SourceLocation RAngleLoc,
5149 TemplateTypeParmDecl *Param,
5150 SmallVectorImpl<TemplateArgument> &Converted) {
5151 TypeSourceInfo *ArgType = Param->getDefaultArgumentInfo();
5152
5153 // If the argument type is dependent, instantiate it now based
5154 // on the previously-computed template arguments.
5155 if (ArgType->getType()->isInstantiationDependentType()) {
5156 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
5157 Param, Template, Converted,
5158 SourceRange(TemplateLoc, RAngleLoc));
5159 if (Inst.isInvalid())
5160 return nullptr;
5161
5162 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5163
5164 // Only substitute for the innermost template argument list.
5165 MultiLevelTemplateArgumentList TemplateArgLists;
5166 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
5167 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5168 TemplateArgLists.addOuterTemplateArguments(None);
5169
5170 bool ForLambdaCallOperator = false;
5171 if (const auto *Rec = dyn_cast<CXXRecordDecl>(Template->getDeclContext()))
5172 ForLambdaCallOperator = Rec->isLambda();
5173 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext(),
5174 !ForLambdaCallOperator);
5175 ArgType =
5176 SemaRef.SubstType(ArgType, TemplateArgLists,
5177 Param->getDefaultArgumentLoc(), Param->getDeclName());
5178 }
5179
5180 return ArgType;
5181}
5182
5183/// Substitute template arguments into the default template argument for
5184/// the given non-type template parameter.
5185///
5186/// \param SemaRef the semantic analysis object for which we are performing
5187/// the substitution.
5188///
5189/// \param Template the template that we are synthesizing template arguments
5190/// for.
5191///
5192/// \param TemplateLoc the location of the template name that started the
5193/// template-id we are checking.
5194///
5195/// \param RAngleLoc the location of the right angle bracket ('>') that
5196/// terminates the template-id.
5197///
5198/// \param Param the non-type template parameter whose default we are
5199/// substituting into.
5200///
5201/// \param Converted the list of template arguments provided for template
5202/// parameters that precede \p Param in the template parameter list.
5203///
5204/// \returns the substituted template argument, or NULL if an error occurred.
5205static ExprResult
5206SubstDefaultTemplateArgument(Sema &SemaRef,
5207 TemplateDecl *Template,
5208 SourceLocation TemplateLoc,
5209 SourceLocation RAngleLoc,
5210 NonTypeTemplateParmDecl *Param,
5211 SmallVectorImpl<TemplateArgument> &Converted) {
5212 Sema::InstantiatingTemplate Inst(SemaRef, TemplateLoc,
5213 Param, Template, Converted,
5214 SourceRange(TemplateLoc, RAngleLoc));
5215 if (Inst.isInvalid())
5216 return ExprError();
5217
5218 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5219
5220 // Only substitute for the innermost template argument list.
5221 MultiLevelTemplateArgumentList TemplateArgLists;
5222 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
5223 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5224 TemplateArgLists.addOuterTemplateArguments(None);
5225
5226 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5227 EnterExpressionEvaluationContext ConstantEvaluated(
5228 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5229 return SemaRef.SubstExpr(Param->getDefaultArgument(), TemplateArgLists);
5230}
5231
5232/// Substitute template arguments into the default template argument for
5233/// the given template template parameter.
5234///
5235/// \param SemaRef the semantic analysis object for which we are performing
5236/// the substitution.
5237///
5238/// \param Template the template that we are synthesizing template arguments
5239/// for.
5240///
5241/// \param TemplateLoc the location of the template name that started the
5242/// template-id we are checking.
5243///
5244/// \param RAngleLoc the location of the right angle bracket ('>') that
5245/// terminates the template-id.
5246///
5247/// \param Param the template template parameter whose default we are
5248/// substituting into.
5249///
5250/// \param Converted the list of template arguments provided for template
5251/// parameters that precede \p Param in the template parameter list.
5252///
5253/// \param QualifierLoc Will be set to the nested-name-specifier (with
5254/// source-location information) that precedes the template name.
5255///
5256/// \returns the substituted template argument, or NULL if an error occurred.
5257static TemplateName
5258SubstDefaultTemplateArgument(Sema &SemaRef,
5259 TemplateDecl *Template,
5260 SourceLocation TemplateLoc,
5261 SourceLocation RAngleLoc,
5262 TemplateTemplateParmDecl *Param,
5263 SmallVectorImpl<TemplateArgument> &Converted,
5264 NestedNameSpecifierLoc &QualifierLoc) {
5265 Sema::InstantiatingTemplate Inst(
5266 SemaRef, TemplateLoc, TemplateParameter(Param), Template, Converted,
5267 SourceRange(TemplateLoc, RAngleLoc));
5268 if (Inst.isInvalid())
5269 return TemplateName();
5270
5271 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5272
5273 // Only substitute for the innermost template argument list.
5274 MultiLevelTemplateArgumentList TemplateArgLists;
5275 TemplateArgLists.addOuterTemplateArguments(&TemplateArgs);
5276 for (unsigned i = 0, e = Param->getDepth(); i != e; ++i)
5277 TemplateArgLists.addOuterTemplateArguments(None);
5278
5279 Sema::ContextRAII SavedContext(SemaRef, Template->getDeclContext());
5280 // Substitute into the nested-name-specifier first,
5281 QualifierLoc = Param->getDefaultArgument().getTemplateQualifierLoc();
5282 if (QualifierLoc) {
5283 QualifierLoc =
5284 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgLists);
5285 if (!QualifierLoc)
5286 return TemplateName();
5287 }
5288
5289 return SemaRef.SubstTemplateName(
5290 QualifierLoc,
5291 Param->getDefaultArgument().getArgument().getAsTemplate(),
5292 Param->getDefaultArgument().getTemplateNameLoc(),
5293 TemplateArgLists);
5294}
5295
5296/// If the given template parameter has a default template
5297/// argument, substitute into that default template argument and
5298/// return the corresponding template argument.
5299TemplateArgumentLoc
5300Sema::SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
5301 SourceLocation TemplateLoc,
5302 SourceLocation RAngleLoc,
5303 Decl *Param,
5304 SmallVectorImpl<TemplateArgument>
5305 &Converted,
5306 bool &HasDefaultArg) {
5307 HasDefaultArg = false;
5308
5309 if (TemplateTypeParmDecl *TypeParm = dyn_cast<TemplateTypeParmDecl>(Param)) {
5310 if (!hasReachableDefaultArgument(TypeParm))
5311 return TemplateArgumentLoc();
5312
5313 HasDefaultArg = true;
5314 TypeSourceInfo *DI = SubstDefaultTemplateArgument(*this, Template,
5315 TemplateLoc,
5316 RAngleLoc,
5317 TypeParm,
5318 Converted);
5319 if (DI)
5320 return TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
5321
5322 return TemplateArgumentLoc();
5323 }
5324
5325 if (NonTypeTemplateParmDecl *NonTypeParm
5326 = dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5327 if (!hasReachableDefaultArgument(NonTypeParm))
5328 return TemplateArgumentLoc();
5329
5330 HasDefaultArg = true;
5331 ExprResult Arg = SubstDefaultTemplateArgument(*this, Template,
5332 TemplateLoc,
5333 RAngleLoc,
5334 NonTypeParm,
5335 Converted);
5336 if (Arg.isInvalid())
5337 return TemplateArgumentLoc();
5338
5339 Expr *ArgE = Arg.getAs<Expr>();
5340 return TemplateArgumentLoc(TemplateArgument(ArgE), ArgE);
5341 }
5342
5343 TemplateTemplateParmDecl *TempTempParm
5344 = cast<TemplateTemplateParmDecl>(Param);
5345 if (!hasReachableDefaultArgument(TempTempParm))
5346 return TemplateArgumentLoc();
5347
5348 HasDefaultArg = true;
5349 NestedNameSpecifierLoc QualifierLoc;
5350 TemplateName TName = SubstDefaultTemplateArgument(*this, Template,
5351 TemplateLoc,
5352 RAngleLoc,
5353 TempTempParm,
5354 Converted,
5355 QualifierLoc);
5356 if (TName.isNull())
5357 return TemplateArgumentLoc();
5358
5359 return TemplateArgumentLoc(
5360 Context, TemplateArgument(TName),
5361 TempTempParm->getDefaultArgument().getTemplateQualifierLoc(),
5362 TempTempParm->getDefaultArgument().getTemplateNameLoc());
5363}
5364
5365/// Convert a template-argument that we parsed as a type into a template, if
5366/// possible. C++ permits injected-class-names to perform dual service as
5367/// template template arguments and as template type arguments.
5368static TemplateArgumentLoc
5369convertTypeTemplateArgumentToTemplate(ASTContext &Context, TypeLoc TLoc) {
5370 // Extract and step over any surrounding nested-name-specifier.
5371 NestedNameSpecifierLoc QualLoc;
5372 if (auto ETLoc = TLoc.getAs<ElaboratedTypeLoc>()) {
5373 if (ETLoc.getTypePtr()->getKeyword() != ETK_None)
5374 return TemplateArgumentLoc();
5375
5376 QualLoc = ETLoc.getQualifierLoc();
5377 TLoc = ETLoc.getNamedTypeLoc();
5378 }
5379 // If this type was written as an injected-class-name, it can be used as a
5380 // template template argument.
5381 if (auto InjLoc = TLoc.getAs<InjectedClassNameTypeLoc>())
5382 return TemplateArgumentLoc(Context, InjLoc.getTypePtr()->getTemplateName(),
5383 QualLoc, InjLoc.getNameLoc());
5384
5385 // If this type was written as an injected-class-name, it may have been
5386 // converted to a RecordType during instantiation. If the RecordType is
5387 // *not* wrapped in a TemplateSpecializationType and denotes a class
5388 // template specialization, it must have come from an injected-class-name.
5389 if (auto RecLoc = TLoc.getAs<RecordTypeLoc>())
5390 if (auto *CTSD =
5391 dyn_cast<ClassTemplateSpecializationDecl>(RecLoc.getDecl()))
5392 return TemplateArgumentLoc(Context,
5393 TemplateName(CTSD->getSpecializedTemplate()),
5394 QualLoc, RecLoc.getNameLoc());
5395
5396 return TemplateArgumentLoc();
5397}
5398
5399/// Check that the given template argument corresponds to the given
5400/// template parameter.
5401///
5402/// \param Param The template parameter against which the argument will be
5403/// checked.
5404///
5405/// \param Arg The template argument, which may be updated due to conversions.
5406///
5407/// \param Template The template in which the template argument resides.
5408///
5409/// \param TemplateLoc The location of the template name for the template
5410/// whose argument list we're matching.
5411///
5412/// \param RAngleLoc The location of the right angle bracket ('>') that closes
5413/// the template argument list.
5414///
5415/// \param ArgumentPackIndex The index into the argument pack where this
5416/// argument will be placed. Only valid if the parameter is a parameter pack.
5417///
5418/// \param Converted The checked, converted argument will be added to the
5419/// end of this small vector.
5420///
5421/// \param CTAK Describes how we arrived at this particular template argument:
5422/// explicitly written, deduced, etc.
5423///
5424/// \returns true on error, false otherwise.
5425bool Sema::CheckTemplateArgument(NamedDecl *Param,
5426 TemplateArgumentLoc &Arg,
5427 NamedDecl *Template,
5428 SourceLocation TemplateLoc,
5429 SourceLocation RAngleLoc,
5430 unsigned ArgumentPackIndex,
5431 SmallVectorImpl<TemplateArgument> &Converted,
5432 CheckTemplateArgumentKind CTAK) {
5433 // Check template type parameters.
5434 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
5435 return CheckTemplateTypeArgument(TTP, Arg, Converted);
5436
5437 // Check non-type template parameters.
5438 if (NonTypeTemplateParmDecl *NTTP =dyn_cast<NonTypeTemplateParmDecl>(Param)) {
5439 // Do substitution on the type of the non-type template parameter
5440 // with the template arguments we've seen thus far. But if the
5441 // template has a dependent context then we cannot substitute yet.
5442 QualType NTTPType = NTTP->getType();
5443 if (NTTP->isParameterPack() && NTTP->isExpandedParameterPack())
5444 NTTPType = NTTP->getExpansionType(ArgumentPackIndex);
5445
5446 if (NTTPType->isInstantiationDependentType() &&
5447 !isa<TemplateTemplateParmDecl>(Template) &&
5448 !Template->getDeclContext()->isDependentContext()) {
5449 // Do substitution on the type of the non-type template parameter.
5450 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5451 NTTP, Converted,
5452 SourceRange(TemplateLoc, RAngleLoc));
5453 if (Inst.isInvalid())
5454 return true;
5455
5456 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack,
5457 Converted);
5458
5459 // If the parameter is a pack expansion, expand this slice of the pack.
5460 if (auto *PET = NTTPType->getAs<PackExpansionType>()) {
5461 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this,
5462 ArgumentPackIndex);
5463 NTTPType = SubstType(PET->getPattern(),
5464 MultiLevelTemplateArgumentList(TemplateArgs),
5465 NTTP->getLocation(),
5466 NTTP->getDeclName());
5467 } else {
5468 NTTPType = SubstType(NTTPType,
5469 MultiLevelTemplateArgumentList(TemplateArgs),
5470 NTTP->getLocation(),
5471 NTTP->getDeclName());
5472 }
5473
5474 // If that worked, check the non-type template parameter type
5475 // for validity.
5476 if (!NTTPType.isNull())
5477 NTTPType = CheckNonTypeTemplateParameterType(NTTPType,
5478 NTTP->getLocation());
5479 if (NTTPType.isNull())
5480 return true;
5481 }
5482
5483 switch (Arg.getArgument().getKind()) {
5484 case TemplateArgument::Null:
5485 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "clang/lib/Sema/SemaTemplate.cpp", 5485)
;
5486
5487 case TemplateArgument::Expression: {
5488 TemplateArgument Result;
5489 unsigned CurSFINAEErrors = NumSFINAEErrors;
5490 ExprResult Res =
5491 CheckTemplateArgument(NTTP, NTTPType, Arg.getArgument().getAsExpr(),
5492 Result, CTAK);
5493 if (Res.isInvalid())
5494 return true;
5495 // If the current template argument causes an error, give up now.
5496 if (CurSFINAEErrors < NumSFINAEErrors)
5497 return true;
5498
5499 // If the resulting expression is new, then use it in place of the
5500 // old expression in the template argument.
5501 if (Res.get() != Arg.getArgument().getAsExpr()) {
5502 TemplateArgument TA(Res.get());
5503 Arg = TemplateArgumentLoc(TA, Res.get());
5504 }
5505
5506 Converted.push_back(Result);
5507 break;
5508 }
5509
5510 case TemplateArgument::Declaration:
5511 case TemplateArgument::Integral:
5512 case TemplateArgument::NullPtr:
5513 // We've already checked this template argument, so just copy
5514 // it to the list of converted arguments.
5515 Converted.push_back(Arg.getArgument());
5516 break;
5517
5518 case TemplateArgument::Template:
5519 case TemplateArgument::TemplateExpansion:
5520 // We were given a template template argument. It may not be ill-formed;
5521 // see below.
5522 if (DependentTemplateName *DTN
5523 = Arg.getArgument().getAsTemplateOrTemplatePattern()
5524 .getAsDependentTemplateName()) {
5525 // We have a template argument such as \c T::template X, which we
5526 // parsed as a template template argument. However, since we now
5527 // know that we need a non-type template argument, convert this
5528 // template name into an expression.
5529
5530 DeclarationNameInfo NameInfo(DTN->getIdentifier(),
5531 Arg.getTemplateNameLoc());
5532
5533 CXXScopeSpec SS;
5534 SS.Adopt(Arg.getTemplateQualifierLoc());
5535 // FIXME: the template-template arg was a DependentTemplateName,
5536 // so it was provided with a template keyword. However, its source
5537 // location is not stored in the template argument structure.
5538 SourceLocation TemplateKWLoc;
5539 ExprResult E = DependentScopeDeclRefExpr::Create(
5540 Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
5541 nullptr);
5542
5543 // If we parsed the template argument as a pack expansion, create a
5544 // pack expansion expression.
5545 if (Arg.getArgument().getKind() == TemplateArgument::TemplateExpansion){
5546 E = ActOnPackExpansion(E.get(), Arg.getTemplateEllipsisLoc());
5547 if (E.isInvalid())
5548 return true;
5549 }
5550
5551 TemplateArgument Result;
5552 E = CheckTemplateArgument(NTTP, NTTPType, E.get(), Result);
5553 if (E.isInvalid())
5554 return true;
5555
5556 Converted.push_back(Result);
5557 break;
5558 }
5559
5560 // We have a template argument that actually does refer to a class
5561 // template, alias template, or template template parameter, and
5562 // therefore cannot be a non-type template argument.
5563 Diag(Arg.getLocation(), diag::err_template_arg_must_be_expr)
5564 << Arg.getSourceRange();
5565
5566 Diag(Param->getLocation(), diag::note_template_param_here);
5567 return true;
5568
5569 case TemplateArgument::Type: {
5570 // We have a non-type template parameter but the template
5571 // argument is a type.
5572
5573 // C++ [temp.arg]p2:
5574 // In a template-argument, an ambiguity between a type-id and
5575 // an expression is resolved to a type-id, regardless of the
5576 // form of the corresponding template-parameter.
5577 //
5578 // We warn specifically about this case, since it can be rather
5579 // confusing for users.
5580 QualType T = Arg.getArgument().getAsType();
5581 SourceRange SR = Arg.getSourceRange();
5582 if (T->isFunctionType())
5583 Diag(SR.getBegin(), diag::err_template_arg_nontype_ambig) << SR << T;
5584 else
5585 Diag(SR.getBegin(), diag::err_template_arg_must_be_expr) << SR;
5586 Diag(Param->getLocation(), diag::note_template_param_here);
5587 return true;
5588 }
5589
5590 case TemplateArgument::Pack:
5591 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "clang/lib/Sema/SemaTemplate.cpp", 5591)
;
5592 }
5593
5594 return false;
5595 }
5596
5597
5598 // Check template template parameters.
5599 TemplateTemplateParmDecl *TempParm = cast<TemplateTemplateParmDecl>(Param);
5600
5601 TemplateParameterList *Params = TempParm->getTemplateParameters();
5602 if (TempParm->isExpandedParameterPack())
5603 Params = TempParm->getExpansionTemplateParameters(ArgumentPackIndex);
5604
5605 // Substitute into the template parameter list of the template
5606 // template parameter, since previously-supplied template arguments
5607 // may appear within the template template parameter.
5608 //
5609 // FIXME: Skip this if the parameters aren't instantiation-dependent.
5610 {
5611 // Set up a template instantiation context.
5612 LocalInstantiationScope Scope(*this);
5613 InstantiatingTemplate Inst(*this, TemplateLoc, Template,
5614 TempParm, Converted,
5615 SourceRange(TemplateLoc, RAngleLoc));
5616 if (Inst.isInvalid())
5617 return true;
5618
5619 TemplateArgumentList TemplateArgs(TemplateArgumentList::OnStack, Converted);
5620 Params = SubstTemplateParams(Params, CurContext,
5621 MultiLevelTemplateArgumentList(TemplateArgs));
5622 if (!Params)
5623 return true;
5624 }
5625
5626 // C++1z [temp.local]p1: (DR1004)
5627 // When [the injected-class-name] is used [...] as a template-argument for
5628 // a template template-parameter [...] it refers to the class template
5629 // itself.
5630 if (Arg.getArgument().getKind() == TemplateArgument::Type) {
5631 TemplateArgumentLoc ConvertedArg = convertTypeTemplateArgumentToTemplate(
5632 Context, Arg.getTypeSourceInfo()->getTypeLoc());
5633 if (!ConvertedArg.getArgument().isNull())
5634 Arg = ConvertedArg;
5635 }
5636
5637 switch (Arg.getArgument().getKind()) {
5638 case TemplateArgument::Null:
5639 llvm_unreachable("Should never see a NULL template argument here")::llvm::llvm_unreachable_internal("Should never see a NULL template argument here"
, "clang/lib/Sema/SemaTemplate.cpp", 5639)
;
5640
5641 case TemplateArgument::Template:
5642 case TemplateArgument::TemplateExpansion:
5643 if (CheckTemplateTemplateArgument(TempParm, Params, Arg))
5644 return true;
5645
5646 Converted.push_back(Arg.getArgument());
5647 break;
5648
5649 case TemplateArgument::Expression:
5650 case TemplateArgument::Type:
5651 // We have a template template parameter but the template
5652 // argument does not refer to a template.
5653 Diag(Arg.getLocation(), diag::err_template_arg_must_be_template)
5654 << getLangOpts().CPlusPlus11;
5655 return true;
5656
5657 case TemplateArgument::Declaration:
5658 llvm_unreachable("Declaration argument with template template parameter")::llvm::llvm_unreachable_internal("Declaration argument with template template parameter"
, "clang/lib/Sema/SemaTemplate.cpp", 5658)
;
5659 case TemplateArgument::Integral:
5660 llvm_unreachable("Integral argument with template template parameter")::llvm::llvm_unreachable_internal("Integral argument with template template parameter"
, "clang/lib/Sema/SemaTemplate.cpp", 5660)
;
5661 case TemplateArgument::NullPtr:
5662 llvm_unreachable("Null pointer argument with template template parameter")::llvm::llvm_unreachable_internal("Null pointer argument with template template parameter"
, "clang/lib/Sema/SemaTemplate.cpp", 5662)
;
5663
5664 case TemplateArgument::Pack:
5665 llvm_unreachable("Caller must expand template argument packs")::llvm::llvm_unreachable_internal("Caller must expand template argument packs"
, "clang/lib/Sema/SemaTemplate.cpp", 5665)
;
5666 }
5667
5668 return false;
5669}
5670
5671/// Diagnose a missing template argument.
5672template<typename TemplateParmDecl>
5673static bool diagnoseMissingArgument(Sema &S, SourceLocation Loc,
5674 TemplateDecl *TD,
5675 const TemplateParmDecl *D,
5676 TemplateArgumentListInfo &Args) {
5677 // Dig out the most recent declaration of the template parameter; there may be
5678 // declarations of the template that are more recent than TD.
5679 D = cast<TemplateParmDecl>(cast<TemplateDecl>(TD->getMostRecentDecl())
5680 ->getTemplateParameters()
5681 ->getParam(D->getIndex()));
5682
5683 // If there's a default argument that's not reachable, diagnose that we're
5684 // missing a module import.
5685 llvm::SmallVector<Module*, 8> Modules;
5686 if (D->hasDefaultArgument() && !S.hasReachableDefaultArgument(D, &Modules)) {
5687 S.diagnoseMissingImport(Loc, cast<NamedDecl>(TD),
5688 D->getDefaultArgumentLoc(), Modules,
5689 Sema::MissingImportKind::DefaultArgument,
5690 /*Recover*/true);
5691 return true;
5692 }
5693
5694 // FIXME: If there's a more recent default argument that *is* visible,
5695 // diagnose that it was declared too late.
5696
5697 TemplateParameterList *Params = TD->getTemplateParameters();
5698
5699 S.Diag(Loc, diag::err_template_arg_list_different_arity)
5700 << /*not enough args*/0
5701 << (int)S.getTemplateNameKindForDiagnostics(TemplateName(TD))
5702 << TD;
5703 S.Diag(TD->getLocation(), diag::note_template_decl_here)
5704 << Params->getSourceRange();
5705 return true;
5706}
5707
5708/// Check that the given template argument list is well-formed
5709/// for specializing the given template.
5710bool Sema::CheckTemplateArgumentList(
5711 TemplateDecl *Template, SourceLocation TemplateLoc,
5712 TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs,
5713 SmallVectorImpl<TemplateArgument> &Converted,
5714 bool UpdateArgsWithConversions, bool *ConstraintsNotSatisfied) {
5715
5716 if (ConstraintsNotSatisfied)
5717 *ConstraintsNotSatisfied = false;
5718
5719 // Make a copy of the template arguments for processing. Only make the
5720 // changes at the end when successful in matching the arguments to the
5721 // template.
5722 TemplateArgumentListInfo NewArgs = TemplateArgs;
5723
5724 // Make sure we get the template parameter list from the most
5725 // recent declaration, since that is the only one that is guaranteed to
5726 // have all the default template argument information.
5727 TemplateParameterList *Params =
5728 cast<TemplateDecl>(Template->getMostRecentDecl())
5729 ->getTemplateParameters();
5730
5731 SourceLocation RAngleLoc = NewArgs.getRAngleLoc();
5732
5733 // C++ [temp.arg]p1:
5734 // [...] The type and form of each template-argument specified in
5735 // a template-id shall match the type and form specified for the
5736 // corresponding parameter declared by the template in its
5737 // template-parameter-list.
5738 bool isTemplateTemplateParameter = isa<TemplateTemplateParmDecl>(Template);
5739 SmallVector<TemplateArgument, 2> ArgumentPack;
5740 unsigned ArgIdx = 0, NumArgs = NewArgs.size();
5741 LocalInstantiationScope InstScope(*this, true);
5742 for (TemplateParameterList::iterator Param = Params->begin(),
5743 ParamEnd = Params->end();
5744 Param != ParamEnd; /* increment in loop */) {
5745 // If we have an expanded parameter pack, make sure we don't have too
5746 // many arguments.
5747 if (Optional<unsigned> Expansions = getExpandedPackSize(*Param)) {
5748 if (*Expansions == ArgumentPack.size()) {
5749 // We're done with this parameter pack. Pack up its arguments and add
5750 // them to the list.
5751 Converted.push_back(
5752 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5753 ArgumentPack.clear();
5754
5755 // This argument is assigned to the next parameter.
5756 ++Param;
5757 continue;
5758 } else if (ArgIdx == NumArgs && !PartialTemplateArgs) {
5759 // Not enough arguments for this parameter pack.
5760 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5761 << /*not enough args*/0
5762 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5763 << Template;
5764 Diag(Template->getLocation(), diag::note_template_decl_here)
5765 << Params->getSourceRange();
5766 return true;
5767 }
5768 }
5769
5770 if (ArgIdx < NumArgs) {
5771 // Check the template argument we were given.
5772 if (CheckTemplateArgument(*Param, NewArgs[ArgIdx], Template,
5773 TemplateLoc, RAngleLoc,
5774 ArgumentPack.size(), Converted))
5775 return true;
5776
5777 bool PackExpansionIntoNonPack =
5778 NewArgs[ArgIdx].getArgument().isPackExpansion() &&
5779 (!(*Param)->isTemplateParameterPack() || getExpandedPackSize(*Param));
5780 if (PackExpansionIntoNonPack && (isa<TypeAliasTemplateDecl>(Template) ||
5781 isa<ConceptDecl>(Template))) {
5782 // Core issue 1430: we have a pack expansion as an argument to an
5783 // alias template, and it's not part of a parameter pack. This
5784 // can't be canonicalized, so reject it now.
5785 // As for concepts - we cannot normalize constraints where this
5786 // situation exists.
5787 Diag(NewArgs[ArgIdx].getLocation(),
5788 diag::err_template_expansion_into_fixed_list)
5789 << (isa<ConceptDecl>(Template) ? 1 : 0)
5790 << NewArgs[ArgIdx].getSourceRange();
5791 Diag((*Param)->getLocation(), diag::note_template_param_here);
5792 return true;
5793 }
5794
5795 // We're now done with this argument.
5796 ++ArgIdx;
5797
5798 if ((*Param)->isTemplateParameterPack()) {
5799 // The template parameter was a template parameter pack, so take the
5800 // deduced argument and place it on the argument pack. Note that we
5801 // stay on the same template parameter so that we can deduce more
5802 // arguments.
5803 ArgumentPack.push_back(Converted.pop_back_val());
5804 } else {
5805 // Move to the next template parameter.
5806 ++Param;
5807 }
5808
5809 // If we just saw a pack expansion into a non-pack, then directly convert
5810 // the remaining arguments, because we don't know what parameters they'll
5811 // match up with.
5812 if (PackExpansionIntoNonPack) {
5813 if (!ArgumentPack.empty()) {
5814 // If we were part way through filling in an expanded parameter pack,
5815 // fall back to just producing individual arguments.
5816 Converted.insert(Converted.end(),
5817 ArgumentPack.begin(), ArgumentPack.end());
5818 ArgumentPack.clear();
5819 }
5820
5821 while (ArgIdx < NumArgs) {
5822 Converted.push_back(NewArgs[ArgIdx].getArgument());
5823 ++ArgIdx;
5824 }
5825
5826 return false;
5827 }
5828
5829 continue;
5830 }
5831
5832 // If we're checking a partial template argument list, we're done.
5833 if (PartialTemplateArgs) {
5834 if ((*Param)->isTemplateParameterPack() && !ArgumentPack.empty())
5835 Converted.push_back(
5836 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5837 return false;
5838 }
5839
5840 // If we have a template parameter pack with no more corresponding
5841 // arguments, just break out now and we'll fill in the argument pack below.
5842 if ((*Param)->isTemplateParameterPack()) {
5843 assert(!getExpandedPackSize(*Param) &&(static_cast <bool> (!getExpandedPackSize(*Param) &&
"Should have dealt with this already") ? void (0) : __assert_fail
("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "clang/lib/Sema/SemaTemplate.cpp", 5844, __extension__ __PRETTY_FUNCTION__
))
5844 "Should have dealt with this already")(static_cast <bool> (!getExpandedPackSize(*Param) &&
"Should have dealt with this already") ? void (0) : __assert_fail
("!getExpandedPackSize(*Param) && \"Should have dealt with this already\""
, "clang/lib/Sema/SemaTemplate.cpp", 5844, __extension__ __PRETTY_FUNCTION__
))
;
5845
5846 // A non-expanded parameter pack before the end of the parameter list
5847 // only occurs for an ill-formed template parameter list, unless we've
5848 // got a partial argument list for a function template, so just bail out.
5849 if (Param + 1 != ParamEnd)
5850 return true;
5851
5852 Converted.push_back(
5853 TemplateArgument::CreatePackCopy(Context, ArgumentPack));
5854 ArgumentPack.clear();
5855
5856 ++Param;
5857 continue;
5858 }
5859
5860 // Check whether we have a default argument.
5861 TemplateArgumentLoc Arg;
5862
5863 // Retrieve the default template argument from the template
5864 // parameter. For each kind of template parameter, we substitute the
5865 // template arguments provided thus far and any "outer" template arguments
5866 // (when the template parameter was part of a nested template) into
5867 // the default argument.
5868 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*Param)) {
5869 if (!hasReachableDefaultArgument(TTP))
5870 return diagnoseMissingArgument(*this, TemplateLoc, Template, TTP,
5871 NewArgs);
5872
5873 TypeSourceInfo *ArgType = SubstDefaultTemplateArgument(*this,
5874 Template,
5875 TemplateLoc,
5876 RAngleLoc,
5877 TTP,
5878 Converted);
5879 if (!ArgType)
5880 return true;
5881
5882 Arg = TemplateArgumentLoc(TemplateArgument(ArgType->getType()),
5883 ArgType);
5884 } else if (NonTypeTemplateParmDecl *NTTP
5885 = dyn_cast<NonTypeTemplateParmDecl>(*Param)) {
5886 if (!hasReachableDefaultArgument(NTTP))
5887 return diagnoseMissingArgument(*this, TemplateLoc, Template, NTTP,
5888 NewArgs);
5889
5890 ExprResult E = SubstDefaultTemplateArgument(*this, Template,
5891 TemplateLoc,
5892 RAngleLoc,
5893 NTTP,
5894 Converted);
5895 if (E.isInvalid())
5896 return true;
5897
5898 Expr *Ex = E.getAs<Expr>();
5899 Arg = TemplateArgumentLoc(TemplateArgument(Ex), Ex);
5900 } else {
5901 TemplateTemplateParmDecl *TempParm
5902 = cast<TemplateTemplateParmDecl>(*Param);
5903
5904 if (!hasReachableDefaultArgument(TempParm))
5905 return diagnoseMissingArgument(*this, TemplateLoc, Template, TempParm,
5906 NewArgs);
5907
5908 NestedNameSpecifierLoc QualifierLoc;
5909 TemplateName Name = SubstDefaultTemplateArgument(*this, Template,
5910 TemplateLoc,
5911 RAngleLoc,
5912 TempParm,
5913 Converted,
5914 QualifierLoc);
5915 if (Name.isNull())
5916 return true;
5917
5918 Arg = TemplateArgumentLoc(
5919 Context, TemplateArgument(Name), QualifierLoc,
5920 TempParm->getDefaultArgument().getTemplateNameLoc());
5921 }
5922
5923 // Introduce an instantiation record that describes where we are using
5924 // the default template argument. We're not actually instantiating a
5925 // template here, we just create this object to put a note into the
5926 // context stack.
5927 InstantiatingTemplate Inst(*this, RAngleLoc, Template, *Param, Converted,
5928 SourceRange(TemplateLoc, RAngleLoc));
5929 if (Inst.isInvalid())
5930 return true;
5931
5932 // Check the default template argument.
5933 if (CheckTemplateArgument(*Param, Arg, Template, TemplateLoc,
5934 RAngleLoc, 0, Converted))
5935 return true;
5936
5937 // Core issue 150 (assumed resolution): if this is a template template
5938 // parameter, keep track of the default template arguments from the
5939 // template definition.
5940 if (isTemplateTemplateParameter)
5941 NewArgs.addArgument(Arg);
5942
5943 // Move to the next template parameter and argument.
5944 ++Param;
5945 ++ArgIdx;
5946 }
5947
5948 // If we're performing a partial argument substitution, allow any trailing
5949 // pack expansions; they might be empty. This can happen even if
5950 // PartialTemplateArgs is false (the list of arguments is complete but
5951 // still dependent).
5952 if (ArgIdx < NumArgs && CurrentInstantiationScope &&
5953 CurrentInstantiationScope->getPartiallySubstitutedPack()) {
5954 while (ArgIdx < NumArgs && NewArgs[ArgIdx].getArgument().isPackExpansion())
5955 Converted.push_back(NewArgs[ArgIdx++].getArgument());
5956 }
5957
5958 // If we have any leftover arguments, then there were too many arguments.
5959 // Complain and fail.
5960 if (ArgIdx < NumArgs) {
5961 Diag(TemplateLoc, diag::err_template_arg_list_different_arity)
5962 << /*too many args*/1
5963 << (int)getTemplateNameKindForDiagnostics(TemplateName(Template))
5964 << Template
5965 << SourceRange(NewArgs[ArgIdx].getLocation(), NewArgs.getRAngleLoc());
5966 Diag(Template->getLocation(), diag::note_template_decl_here)
5967 << Params->getSourceRange();
5968 return true;
5969 }
5970
5971 // No problems found with the new argument list, propagate changes back
5972 // to caller.
5973 if (UpdateArgsWithConversions)
5974 TemplateArgs = std::move(NewArgs);
5975
5976 if (!PartialTemplateArgs) {
5977 // FIXME: This will be changed a bit once deferred concept instantiation is
5978 // implemented.